微信分享sdk操作指南

2019-03-01  本文已影响0人  54黄药师

后端

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}
})
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
        }
     */
})
//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 + '&timestamp=' + 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,微信官方建议将其进行缓存,避免短时间内大量的请求微信服务器,导致请求上限机制被触发

客户端

//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);
});
上一篇下一篇

猜你喜欢

热点阅读