1、先登錄微信公眾平臺(tái),進(jìn)入“公眾號(hào)設(shè)置”的“功能設(shè)置”里填寫“JS接口安全域名”,進(jìn)入“基礎(chǔ)配置”,將服務(wù)端部署ip配置到IP白名單中。
2、引入JS文件 在需要調(diào)用JS接口的頁(yè)面引入如下JS文件,(支持 https):http://res.wx.qq.com/open/js/jweixin-1.6.0.js
3、通過config接口注入權(quán)限驗(yàn)證配置,所需參數(shù)從服務(wù)端接口獲取;
服務(wù)端生成簽名時(shí)需要配置當(dāng)前網(wǎng)頁(yè)的URL(不包含#及其后面部分,需域名,本地ip試了不行),可由前端將調(diào)用掃一掃的頁(yè)面url傳給服務(wù)端生成簽名的接口;
let signData = await request('api/demo/auth/sign', { method: 'POST', body: {
"url": window.location.origin + window.location.pathname, //當(dāng)前網(wǎng)頁(yè)的URL傳給后端
} })
console.log('signData',signData);
wx.config({
debug: true, // 開啟調(diào)試模式,調(diào)用的所有api的返回值會(huì)在客戶端alert出來(lái),若要查看傳入的參數(shù),可以在pc端打開,參數(shù)信息會(huì)通過log打出,僅在pc端時(shí)才會(huì)打印。
appId: 'wx7048dabe52c67347', // 必填,公眾號(hào)的唯一標(biāo)識(shí)
timestamp: signData.timestamp, // 必填,生成簽名的時(shí)間戳
nonceStr: signData.nonceStr, // 必填,生成簽名的隨機(jī)串
signature: signData.signature,// 必填,簽名
jsApiList: ['scanQRCode'] // 必填,需要使用的JS接口列表
});
4、調(diào)用微信掃一掃;
wx.scanQRCode({
needResult: 1, // 默認(rèn)為0,掃描結(jié)果由微信處理,1則直接返回掃描結(jié)果,
scanType: ["qrCode","barCode"], // 可以指定掃二維碼還是一維碼,默認(rèn)二者都有
success: function (res) {
var result = res.resultStr; // 當(dāng)needResult 為 1 時(shí),掃碼返回的結(jié)果
console.log(result);
request('api/demo/user/query', {
method: 'POST', body: {
"number": result
}
}).then(res => {
console.log(res);
jumpPage('/search/result', JSON.parse(res.data))
})
}
})
5、如果要獲取微信用戶信息,需網(wǎng)頁(yè)鑒權(quán)-Oauth2,只有通過微信認(rèn)證的服務(wù)號(hào)有權(quán)限,訂閱號(hào)不行,進(jìn)入“公眾號(hào)設(shè)置”的“功能設(shè)置”里進(jìn)行網(wǎng)頁(yè)授權(quán)域名填寫;參考鏈接
6、成功demo(前端獲取到code后傳給服務(wù)端接口,接口返回openId,或者用戶信息)
let openId = ''
let code = this.getUrlParam('code','?' + window.location.href.split('?')[1])
const url = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=xxx&redirect_uri=https://xxx.com/deme/&response_type=code&scope=snsapi_base&state=STATE`
if(!sessionStorage.getItem('openId')){
if(code){
request('api/demo/auth/receive', { method: 'POST', body: {
code: code,
} }).then(res=>{
openId = res.openId
sessionStorage.setItem('openId',openId)
this.getUserInfo() //通過openId獲取用戶信息
history.pushState('', '', 'https://xxx.com/deme/')
})
}else{
window.location.href = url
}
}else{
this.getUserInfo() //通過openId獲取用戶信息
}
// 回調(diào)回來(lái)的地址是:https://xxx.com/deme/?code=xxxxxx&state=xxx
// 如果你是使用hash路由的,一般的取url參數(shù)的方法會(huì)有點(diǎn)小問題,需要手動(dòng)調(diào)整下
getUrlParam = (name, location) => {
const reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)');
const { hash, search } = window.location;
const result = ((location||(hash || search)).split('?')[1] || '').match(reg);
return result ? decodeURIComponent(result[2]) : null;
}