2015 是 Hybrid App 崛起之年 ,Web App 和 Native App 各有其強大之處,也有著致命的缺點,人們一邊追求native流暢的用戶體驗,一邊同時期望產品能夠快速的迭代更新,Hybrid 成為必然的趨勢。
鵝廠一馬當先,發布了業內震驚一時的 JS-SDK , 這對于基于微信的h5開發者來說簡直是如降甘露,從此開發者們告別了用箭頭來提示右上角可以分享,并且隨時可以使用微信的原生能力,微信變成了一個超級瀏覽器。
一、準備工作
1.在微信公眾平臺申請測試賬號,并設置好好 JS 接口安全域名 (注:域名必須可以外網訪問)
2.查看微信開發者文檔
二、開始編碼
使用微信 sdk 必須自己實現微信的簽名算法。
大概需要4個步驟:
1.獲取access_token;
2.根據access_token 獲取jsapi_ticket
3. 根據 appId(公眾號唯一id)、noncestr(隨機字符串)、timestamp(時間戳)、url(當前頁面完整url,不包括#aaa=bbb) 通過sha1算法簽名
4.將信息返回給前端 , 設置wx.config。
由于獲取access_token 和jsapi_ticket 的接口都有訪問限制,所以明確指出需要第三方做緩存處理。此處我們緩存jsapi_ticket 就可以了。
/config/wechat.cfg.js
module.exports = { grant_type: 'client_credential', appid: 'xxxxxxxxxxxxxxx', secret: 'xxxxxxxxxxxxxxxxxxxxxxxxxx', noncestr:'Wm3WZYTPz0wzccnW', accessTokenUrl:'https://api.weixin.qq.com/cgi-bin/token', ticketUrl:'https://api.weixin.qq.com/cgi-bin/ticket/getticket', cache_duration:1000*60*60*24 //緩存時長為24小時}最主要部分是簽名:
signature.js
var request = require('request'), cache = require('memory-cache'), sha1 = require('sha1'), config = require('../config/wechat.cfg');exports.sign = function (url,callback) { var noncestr = config.noncestr, timestamp = Math.floor(Date.now()/1000), //精確到秒 jsapi_ticket; if(cache.get('ticket')){ jsapi_ticket = cache.get('ticket'); console.log('1' + 'jsapi_ticket=' + jsapi_ticket + '&noncestr=' + noncestr + '×tamp=' + timestamp + '&url=' + url); callback({ noncestr:noncestr, timestamp:timestamp, url:url, jsapi_ticket:jsapi_ticket, signature:sha1('jsapi_ticket=' + jsapi_ticket + '&noncestr=' + noncestr + '×tamp=' + timestamp + '&url=' + url) }); }else{ request(config.accessTokenUrl + '?grant_type=' + config.grant_type + '&appid=' + config.appid + '&secret=' + config.secret ,function(error, response, body){ if (!error && response.statusCode == 200) { var tokenMap = JSON.parse(body); request(config.ticketUrl + '?access_token=' + tokenMap.access_token + '&type=jsapi', function(error, resp, json){ if (!error && response.statusCode == 200) { var ticketMap = JSON.parse(json); cache.put('ticket',ticketMap.ticket,config.cache_duration); //加入緩存 console.log('jsapi_ticket=' + ticketMap.ticket + '&noncestr=' + noncestr + '×tamp=' + timestamp + '&url=' + url); callback({ noncestr:noncestr, timestamp:timestamp, url:url, jsapi_ticket:ticketMap.ticket, signature:sha1('jsapi_ticket=' + ticketMap.ticket + '&noncestr=' + noncestr + '×tamp=' + timestamp + '&url=' + url) }); } }) } }) }}
新聞熱點
疑難解答