一、JS-SDK说明文档https://developers.weixin.qq.com/doc/offiaccount/OA_Web_Apps/JS-SDK.htmldevelopers.weixin.qq.com
1.生成签名,用sign.js
2.使用,用check_sign.js
3.生成签名之前,必须要先获取access_token(要保存在后台),然后根据获取的access_token,再获取jsapi_ticket(临时票据,也要保存在后台)。
二、首先获取access_token
1.分清两种access_token
网页授权access_token和普通access_token:
1)网页授权access_token,微信网页授权是通过OAuth2.0机制实现的,在用户授权给公众号后,公众号可以获取到一个网页授权特有的接口调用凭证(网页授权access_token),通过网页授权access_token可以进行授权后接口调用,如获取用户基本信息;获取此access_token需要给微信服务器接口(https://api.weixin.qq.com/sns/oauth2/access_token)三个参数(code,appid,appsercet)
/*1.获取code的url(访问微信官方服务器获取code)--- 用户操作之后才能有code,如点击页面的授权按钮。*/
`https://open.weixin.qq.com/connect/oauth2/authorize?appid=${APPID}&redirect_uri=${url}&response_type=code&scope=snsapi_userinfo&state=STATE&connect_redirect=1#wechat_redirect`
/*2.获取网页授权access_token的url(访问微信官方服务器获取)*/
`https://api.weixin.qq.com/sns/oauth2/access_token?appid=${APPID}&secret=${SECRET}&code=${CODE}&grant_type=authorization_code`
2)其他微信接口,需要通过基础支持中的“获取access_token”接口来获取到的普通access_token调用。获取此access_token需要给微信服务器接口(https://api.weixin.qq.com/cgi-bin/token)两个参数(appid,appsercet)
/*获取js-sdk的jsapi_ticket(临时票据),获取普通access_token的url(访问微信官方服务器获取临时票据)*/
`https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${APPID}&secret=${SECRET}`
三、应用
挖坑。。。
四、我遇到的报错及排查
1.前台访问后台的接口(该接口用于生成wx.config()所需要的参数appId、 timestamp、nonceStr及signature);此处采用的是vue2.全家桶,前后台分离,前台采用axios发起请求。在微信开发者工具上也可以获得4个参数,但是一直报错 “63002无效的签名” --- 解决:前台发起请求的代码块,保证url一定要传递给后台。
2. “分享给朋友”及“分享到朋友圈“的自定义配置不生效--- 解决:用回即将废弃的api。
const url = encodeURIComponent(location.href.split('#')[0])
axios.get(`https://xxxx/api/usersticket?url=${url}`).then((res) => {
const {APPID, timestamp, noncestr, signature, url} = res.data
wx.config({
debug: false, // 测试时改为true。 appId: APPID,
timestamp,
nonceStr: noncestr,
signature,
jsApiList: [
'onMenuShareAppMessage',
'onMenuShareTimeline'
]
})
wx.ready(() => {
wx.onMenuShareAppMessage({
title: '自定义',
desc: '自定义',
link: url,
imgUrl: '自定义',
success: () => {
console.log('分享成功了!')
},
cancel: () => {
console.log('分享失败了!')
}
})
wx.onMenuShareTimeline({
title: '自定义',
link: url,
imgUrl: '自定义',
success: () => {
console.log('分享成功了!')
},
cancel: () => {
console.log('分享失败了!')
}
})
})
wx.error(res => {
console.log(res)
})
}).catch(err => {
console.log(err)
})