1987WEB视界-分享互联网热点话题和事件

您现在的位置是:首页 > WEB开发 > 正文

WEB开发

uniapp中的分享功能实现(APP,小程序,公众号)

1987web2024-03-25WEB开发48
uniapp中的分享功能实现(APP,小程序,公众号)uniapp中的分享功能实现(APP,小程序,公众号)

uniapp中的分享功能实现(APP,小程序,公众号)

uniapp中的分享功能实现(APP,小程序,公众号)

1.APP端的分享

app端的分享可以直接使用uniapp封装的方法uni.share,uni-app的App引擎已经封装了微信、QQ、微博的分享SDK,开发者可以直接调用相关功能。可以分享到微信、QQ、微博,每个社交平台被称为分享服务提供商,即provider。可以分享文字、图片、图文横条、音乐、视频等多种形式。同时注意,分享为小程序也使用本API。即在App里可以通过本API把一个内容以小程序(通常为内容页)方式直接分享给微信好友。直接上代码。

class="item"@click="appShare(WXSceneSession)"> class="iconfont icon-weixin3"> class="">微信好友 class="item"@click="appShare(WXSenceTimeline)"> class="iconfont icon-pengyouquan"> class="">微信朋友圈appShare(scene) {let that = thislet routes = getCurrentPages(); // 获取当前打开过的页面路由数组let curRoute = routes[routes.length - 1].$page.fullPath // 获取当前页面路由,也就是最后一个打开的页面路由uni.share({provider: "weixin", //分享服务提供商(即weixin|qq|sinaweibo)scene: scene, //场景,可取值参考下面说明。type: 0, //分享形式href: `${HTTP_IP_URL}${curRoute}&spread=${that.uid}`, //跳转链接title: that.storeInfo.storeName, //分享内容的标题summary: that.storeInfo.storeInfo, //分享内容的摘要imageUrl: that.storeInfo.image, //图片地址success: function(res) {that.posters = false; //成功后关闭底部弹框},fail: function(err) {uni.showToast({title: 分享失败,icon: none,duration: 2000})that.posters = false;}});},

type 值说明

说明

provider支持度

0

图文

weixin、sinaweibo

1

纯文字

weixin、qq

2

图片

weixin、qq

3

音乐

weixin、qq

4

视频

weixin、sinaweibo

5

小程序

weixin

scene 值说明

说明

WXSceneSession

分享到聊天界面

WXSenceTimeline

分享到朋友圈

WXSceneFavorite

分享到微信收藏

uni.share 在App端各社交平台分享配置说明

打开 manifest.json -> App模块权限配置,勾选 Share(分享);按如下文档具体配置微信、微博、QQ的参数

在 manifest.json 的 App SDK 配置里,勾选微信消息及朋友圈,并填写 appid,如需在iOS平台使用还需要配置通用链接。

2.小程序端的分享

小程序中的分享有两种,一种是通过右上角的胶囊分享,还可以通过在页面中写button,通过open-type="share"方式分享。

//onShareAppMessage 分享给朋友//onShareTimeline 分享到朋友圈// #ifdef MPonShareAppMessage:function(res){if(res.from===button){// 来自页面内转发按钮console.log(res.target)}letthat=this;return{title:这是标题,imageUrl:这是描述,path:/pages/goods_details/index?id=+that.id,}},// #endif

3.公众号的分享

公众号中的分享需要使用微信的JS-SDK,可以直接下载js文件引入,也可以通过npm下载。 公众号的分享比较繁琐,我们可以将其封装一下,在需要使用的地方传入对应的title,link和jsapi,就可以简便操作。

新建wechat.js,并在main.js中将其挂载到vue的原型上

// #ifdef H5importWechatJSSDKfrom"@/plugin/jweixin-module/index.js";import{getWechatConfig,wechatAuth}from"@/api/public";import{WX_AUTH,STATE_KEY,LOGINTYPE,BACK_URL}from@/config/cache;import{parseQuery}from@/utils;importstorefrom@/store;importCachefrom@/utils/cache;classAuthWechat{constructor(){//微信实例化对象this.instance=WechatJSSDK;//是否实例化this.status=false;this.initConfig={};}isAndroid(){letu=navigator.userAgent;returnu.indexOf(Android)>-1||u.indexOf(Adr)>-1;}signLink(){if(typeofwindow.entryUrl===undefined||window.entryUrl===){window.entryUrl=location.href.split(#)[0]}return/(Android)/i.test(navigator.userAgent)?location.href.split(#)[0]:window.entryUrl;}/*** 初始化wechat(分享配置)*/wechat(){returnnewPromise((resolve,reject)=>{// if (this.status && !this.isAndroid()) return resolve(this.instance);getWechatConfig().then(res=>{this.instance.config(res.data);this.initConfig=res.data;this.status=true;this.instance.ready(()=>{resolve(this.instance);})}).catch(err=>{console.log(微信分享配置失败,err);this.status=false;reject(err);});});}/*** 验证是否初始化*/verifyInstance(){letthat=this;returnnewPromise((resolve,reject)=>{if(that.instance===null&&!that.status){that.wechat().then(res=>{resolve(that.instance);}).catch(()=>{returnreject();})}else{returnresolve(that.instance);}})}// 微信公众号的共享地址openAddress(){returnnewPromise((resolve,reject)=>{this.wechat().then(wx=>{this.toPromise(wx.openAddress).then(res=>{resolve(res);}).catch(err=>{reject(err);});}).catch(err=>{reject(err);})});}// 获取经纬度;location(){returnnewPromise((resolve,reject)=>{this.wechat().then(wx=>{this.toPromise(wx.getLocation,{type:wgs84}).then(res=>{resolve(res);}).catch(err=>{reject(err);});}).catch(err=>{reject(err);})});}// 使用微信内置地图查看位置接口;seeLocation(config){returnnewPromise((resolve,reject)=>{this.wechat().then(wx=>{this.toPromise(wx.openLocation,config).then(res=>{resolve(res);}).catch(err=>{reject(err);});}).catch(err=>{reject(err);})});}/*** 微信支付* @param {Object} config*/pay(config){returnnewPromise((resolve,reject)=>{this.wechat().then((wx)=>{this.toPromise(wx.chooseWXPay,config).then(res=>{resolve(res);}).catch(res=>{resolve(res);});}).catch(res=>{reject(res);});});}toPromise(fn,config={}){returnnewPromise((resolve,reject)=>{fn({...config,success(res){resolve(res);},fail(err){reject(err);},complete(err){reject(err);},cancel(err){reject(err);}});});}/*** 自动去授权*/oAuth(snsapiBase,url){if(uni.getStorageSync(WX_AUTH)&&store.state.app.token&&snsapiBase==snsapi_base)return;const{code}=parseQuery();if(!code||code==uni.getStorageSync(snsapiCode)){returnthis.toAuth(snsapiBase,url);}else{if(Cache.has(snsapiKey))returnthis.auth(code).catch(error=>{uni.showToast({title:error,icon:none})})}}clearAuthStatus(){}/*** 授权登录获取token* @param {Object} code*/auth(code){returnnewPromise((resolve,reject)=>{wechatAuth(code,Cache.get("spread")).then(({data})=>{resolve(data);Cache.set(WX_AUTH,code);Cache.clear(STATE_KEY);// Cache.clear(spread);loginType&&Cache.clear(LOGINTYPE);}).catch(reject);});}/*** 获取跳转授权后的地址* @param {Object} appId*/getAuthUrl(appId,snsapiBase,backUrl){leturl=`${location.origin}${backUrl}`if(url.indexOf(?)==-1){url=url+?}else{url=url+&}constredirect_uri=encodeURIComponent(`${url}scope=${snsapiBase}&back_url=`+encodeURIComponent(encodeURIComponent(uni.getStorageSync(BACK_URL)?uni.getStorageSync(BACK_URL):location.pathname+location.search)));uni.removeStorageSync(BACK_URL);conststate=encodeURIComponent((""+Math.random()).split(".")[1]+"authorizestate");uni.setStorageSync(STATE_KEY,state);return`https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appId}&redirect_uri=${redirect_uri}&response_type=code&scope=snsapi_userinfo&state=${state}#wechat_redirect`;// if(snsapiBase===snsapi_base){// return `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appId}&redirect_uri=${redirect_uri}&response_type=code&scope=snsapi_base&state=${state}#wechat_redirect`;// }else{// return `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appId}&redirect_uri=${redirect_uri}&response_type=code&scope=snsapi_userinfo&state=${state}#wechat_redirect`;// }}/*** 跳转自动登录*/toAuth(snsapiBase,backUrl){letthat=this;this.wechat().then(wx=>{location.href=this.getAuthUrl(that.initConfig.appId,snsapiBase,backUrl);})}/*** 绑定事件* @param {Object} name 事件名* @param {Object} config 参数*/wechatEvevt(name,config){letthat=this;returnnewPromise((resolve,reject)=>{letconfigDefault={fail(res){if(that.instance)returnreject({is_ready:true,wx:that.instance});that.verifyInstance().then(wx=>{returnreject({is_ready:true,wx:wx});})},success(res){returnresolve(res,2222);}};Object.assign(configDefault,config);that.wechat().then(wx=>{if(typeofname===object){name.forEach(item=>{wx[item]&&wx[item](configDefault)})}else{wx[name]&&wx[name](configDefault)}})});}isWeixin(){returnnavigator.userAgent.toLowerCase().indexOf("micromessenger")!==-1;}}exportdefaultnewAuthWechat();// #endif

在需要使用的地方:

// 微信分享;setOpenShare:function(data){letthat=this;if(that.$wechat.isWeixin()){letconfigAppMessage={desc:data.synopsis,title:data.title,link:location.href,imgUrl:data.img};that.$wechat.wechatEvevt(["updateAppMessageShareData","updateTimelineShareData"],configAppMessage);}},

微信公众号环境中点击右上角三个点就可以分享,所以setOpenShare事件可以提前让他执行,如果需要通过自定义方式通过按钮点击分享,可以将setOpenShare事件放在按钮的点击事件里面。

h5示例: CRMEB-JAVA.gitee开源地址: CRMEB-JAVA.都看到这里了,点击上面gitee链接给个star吧