uniapp之(zhī)h5公衆号分享和(hé / huò)授權
發表時(shí)間:2020-11-3
發布人(rén):融晨科技
浏覽次數:329
一,微信分享
1,安裝jweixin-module
npm i jweixin-module
2,在(zài)需要(yào / yāo)分享的(de)頁面引入
<script>
// #ifdef H5
let jweixin = require('jweixin-module')
// #endif
.....
</script>
3,設置分享内容(或者點擊觸發分享)
distributrShare() {
this.$http({
apiName: "wxJsdkConfig",
type: "POST",
data: {
url: encodeURIComponent(window.location.href),
//後台通過域名進行授權
}
}).then(res = >{
var _self = this jweixin.config({
debug: true,
// 開啓調試模式,調用的(de)所有api的(de)返回值會在(zài)客戶端alert出(chū)來(lái),若要(yào / yāo)查看傳入的(de)參數,可以(yǐ)在(zài)pc端打開,參數信息會通過log打出(chū),僅在(zài)pc端時(shí)才會打印。
appId: res.data.appId,
// 必填,公衆号的(de)唯一标識
timestamp: res.data.timestamp,
// 必填,生成簽名的(de)時(shí)間戳
nonceStr: res.data.nonceStr,
// 必填,生成簽名的(de)随機串
signature: res.data.signature,
// 必填,簽名
jsApiList: ['updateTimelineShareData', 'updateAppMessageShareData', ] // 必填,需要(yào / yāo)使用的(de)JS接口列表
})
jweixin.ready(function(res) {
//分享給朋友
jweixin.updateAppMessageShareData({
title: _self.title,
desc: "快來(lái)嗨購吧!",
link: window.location.href + "&inviteCode=" + _self.userInfo.inviteCode,
imgUrl: _self.picUrl,
trigger: function trigger(res) {
// alert(res);
},
success: function success(res) {
// alert('已分享');
},
cancel: function cancel(res) {
// alert('已取消');
},
fail: function fail(res) {
// alert(2, JSON.stringify(res));
}
});
}) jweixin.error(err = >{
// console.log("jsapi錯誤:",err)
})
}).
catch(err = >{
// console.log(3,err)
})
},
注意幾點:
a:公衆号的(de)分享隻能通過右上(shàng)角h5的(de)分享觸發,默認分享當前頁面,分享隻是(shì)配置分享内容
b:當前分享頁面的(de)鏈接必須在(zài)後台配置JS接口安全域名和(hé / huò)網頁授權域名,
c:傳到(dào)後台的(de)鏈接需要(yào / yāo)encodeURIComponent轉碼,不(bù)能包括端口号,
d:安卓上(shàng)可以(yǐ),IOS上(shàng)報fail link must be in js secure domain list參考:解決微信H5網頁分享報錯:fail link must be in js secure domain list
e:invalid signature參考關于(yú)微信公衆号開發config:invalid signature錯誤的(de)解決方法
二,授權登錄
頁面:
...async>//判斷是(shì)否是(shì)微信浏覽器
isWxBrowser() {
if (window.navigator.userAgent.toLowerCase().match(/MicroMessenger/i) == "micromessenger") {
return true
} else {
return false
}
},
//jdk配置
async configWeiXin(callback) {
//獲取公衆号配置
let resConfig = await http({
apiName: "wxJsdkConfig",
type: "POST",
data: {
url: encodeURIComponent(window.location.href),
//後台通過域名進行授權
}
}) if (resConfig) {
let apiList = [ // 可能需要(yào / yāo)用到(dào)的(de)能力
'onMenuShareAppMessage', 'onMenuShareTimeline', 'hideOptionMenu', 'showOptionMenu', 'chooseWXPay'];
let info = {
// debug: true, // 調試,發布的(de)時(shí)候改爲(wéi / wèi)false
appId: resConfig.data.appId,
nonceStr: resConfig.data.nonceStr,
timestamp: resConfig.data.timestamp,
signature: resConfig.data.signature,
jsApiList: apiList
};
jweixin.config(info);
jweixin.error(err = >{
console.log('config fail:', err);
});
jweixin.ready(res = >{
console.log(3, res) if (callback) callback(jweixin, resConfig.data.appId); // 配置成功回調
// uni.setStorageSync('msg',JSON.stringify(res.data))
// uni.setStorageSync('msg',JSON.parse(res.message.replace(/"/,/'/)))
});
}
},
//公衆号授權
async wxJsdkAuthorize(_appid, isLogin = false) {
let link = window.location.href;
// let link=window.location.origin+'/pages/public/middlePage'
let _code = ''
if (link.includes("code=")) {
_code = link.split("code=")[1].split('&')[0]
}
// 如果拿到(dào)_code,調用授權接口,沒有拿到(dào)就(jiù)跳轉微信授權鏈接獲取
if (_code) {
if (isLogin) {
await http({
apiName: "wxWebLogin",
type: 'POST',
data: {
code: _code
}
}).then(res = >{
uni.showToast({
title: '登錄成功',
mask: false,
duration: 1500
});
this.setSesion(res.data) this.getUserInfo() this.afterLoginJump()
}).
catch(err = >{
uni.setStorageSync('msg', err.data) console.log(uni.getStorageInfoSync('msg').openId) if (err.code == 500070) {
uni.redirectTo({
url: '/pages/public/bindMobile'
})
} else {
uni.redirectTo({
url: '/pages/set/loginPwd'
})
}
})
} else {
await http({
apiName: "wxJsdkLogin",
data: {
code: _code
}
}).then(res = >{
})
//code傳到(dào)後台關聯賬戶
uni.setStorageSync("wxJsdkLogin", true)
}
} else {
let appid = _appid;
let uri = encodeURIComponent(link);
let authURL = `https: //open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=${uri}&response_type=code&scope=snsapi_userinfo&state=123#wechat_redirect`;
window.location.href = authURL;
}
},
jsApiCall(data, callback_succ_func, callback_error_func) {
//使用原生的(de),避免初始化appid問題
WeixinJSBridge.invoke('getBrandWCPayRequest', {
appId: data['appId'],
timeStamp: data['timeStamp'],
nonceStr: data['nonceStr'],
// 支付簽名随機串,不(bù)長于(yú) 32 位
package: data['package'],
// 統一支付接口返回的(de)prepay_id參數值,提交格式如:prepay_id=\*\*\*)
signType: data['signType'],
// 簽名方式,默認爲(wéi / wèi)'SHA1',使用新版支付需傳入'MD5'
paySign: data['paySign'],
// 支付簽名
},
function(res) {
var msg = res.err_msg ? res.err_msg: res.errMsg;
//WeixinJSBridge.log(msg);
switch (msg) {
case 'get_brand_wcpay_request:ok':
//支付成功時(shí)
if (callback_succ_func) {
callback_succ_func(res);
}
break;
default:
//支付失敗時(shí)
WeixinJSBridge.log('支付失敗!' + msg + ',請返回重試.');
if (callback_error_func) {
callback_error_func({
msg: msg
});
}
break;
}
})
},
//WeixinJSBridge判斷
wxJsPay(data, callback_succ_func, callback_error_func) {
if (typeof WeixinJSBridge == "undefined") {
if (document.addEventListener) {
document.addEventListener('WeixinJSBridgeReady', this.jsApiCall, false);
} else if (document.attachEvent) {
document.attachEvent('WeixinJSBridgeReady', this.jsApiCall);
document.attachEvent('onWeixinJSBridgeReady', this.jsApiCall);
}
} else {
this.jsApiCall(data, callback_succ_func, callback_error_func);
}
},