认证微信公众号后添加安全的域名后可以查看对应的appid 和 secret;
根据appid和secret请求微信提供的api,拿到对应的access_token;
https.get('https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET', function(res) {
//这里的回调函数能够拿到包含access_token的一个json数据
//{"access_token":"ACCESS_TOKEN","expires_in":7200}
})
根据获取到的access_token请求微信的api获取签名所需的ticket
https.get('https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=ACCESS_TOKEN&type=jsapi', function(res) {
//这里的回调函数能拿到ticket
/**
* {
'errcode': 0,
'errmsg': 'ok',
'ticket': '字符串',
'expires_in': 7200
}
*/
})
生成签名(需要参数如下)
ticket: 已经拿到
noncestr: 随机串
timestamp: 时间戳
url: 打开前端页面的url
//noncestr
var noncestr = Math.random().toString(36).substr(2, 15);
//timestamp
var timestamp = parseInt(new Date().getTime() / 1000) + '';
//签名算法
var calcSignature = function (ticket, noncestr, timestamp, url) {
var str = 'jsapi_ticket=' + ticket + '&noncestr=' + noncestr + '×tamp=' + timestamp + '&url' + url
shaObj = new jsSHA(str, 'TEXT');
return shaObj.getHash('SHA-1', 'HEX');
}
//签名生成成功
var signature = calcSignature(ticket, noncestr, timestamp, url);
access_token和ticket生成后的有效期是7200s,微信官方建议将其进行缓存,避免短时间内大量的请求微信服务器,导致请求上限机制被触发
在html中引入所必须的微信js-sdk: https://res.wx.qq.com/open/js/jweixin-1.2.0.js
通过ajax的方式想后台服务器发送请求,拿到带有signature, timestamp, appid, nonceStr的数据后对wx.config进行配置
//config:进行配置
wx.config({
debug: true, //开启debug模式,在验证签名过程中会返回对应信息
appId: appid,
timestamp: timestamp,
nonceStr: nonceStr,
signature: signature,
jsApiList: ['onMenuShareTimeline', 'onMenuShareAppMessage', 'onMenuShareQQ', 'onMenuShareWeibo', 'onMenuShareQZone']
})
//ready中调用api
wx.ready(function(){
var sdata = {
title: 'str',
desc: 'str',
link: link,
imgUrl: url,
success: function () {
alert('用户确认分享后执行的回调函数');
},
cancel: function () {
alert('用户取消分享后执行的回调函数');
}
};
wx.onMenuShareTimeline(sdata);
wx.onMenuShareAppMessage(sdata);
});