Simple Application of WeChat JS-SDK Based on nodejs

Source: Internet
Author: User

Simple Application of JS-SDK Based on nodejs
2015 is the year of the rise of the Hybrid App. Web apps and Native apps have their own strengths and fatal weaknesses. while pursuing a smooth native user experience, hybrid will become an inevitable trend when we expect fast iteration and update of products. Goose factory immediately first, released the industry was shocked by the moment of JS-SDK, which is based on h5 developers is simply like a drop of nectar, from then on the developers say goodbye to the use of arrows to prompt the upper right corner can be shared, the native capabilities that can be used at any time become a super browser. I. Preparations 1. apply for a test account on the public platform and set up a secure domain name for the JS interface (Note: The domain name must be accessible from the Internet. view developer documentation (http://mp.weixin.qq.com/wiki/7/aaa137b55fb2e0456bf8dd9148dd613f.html) 2. Start coding a signature algorithm that must be self-implemented using the sdk. Four steps are required: 1. get access_token; 2. obtain jsapi_ticket 3 based on access_token. according to appId (unique public id), noncestr (random string), timestamp (timestamp), and url (complete url of the current page, excluding # aaa = bbb) use the sha1 algorithm to sign the signature. 4. return the information to the front-end and set wx. config. Since access restrictions are imposed on the interfaces used to obtain access_token and jsapi_ticket, it is clearly pointed out that a third party must perform cache processing. Here we can cache jsapi_ticket. /Config/wechat. cfg. js

Module. exports = {grant_type: 'client _ credential ', appid: 'xxxxxxxxxxxxxxxxxx', secret: 'cret', noncestr: 'signature', accessTokenUrl: 'https: // signature, ticketUrl: 'https: // api.weixin.qq.com/cgi-bin/ticket/getticket', cache_duration: 1000*60*60*24 // The cache duration is 24 hours}

 

Signature: 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), // precise to the second jsapi_ticket; if (cache. get ('ticket ') {jsapi_ticket = cache. get ('ticket '); console. log ('1' + 'jsapi _ ticket = '+ jsapi_ticket +' & noncestr = '+ noncest R + '& timestamp =' + timestamp + '& url =' + url); callback ({noncestr: noncestr, timestamp: timestamp, url: url, jsapi_ticket: jsapi_ticket, signature: sha1 ('jsapi _ ticket = '+ jsapi_ticket +' & noncestr = '+ noncestr +' & timestamp = '+ 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); // Add it to the cache console. log ('jsapi _ ticket = '+ ticketMap. ticket + '& noncestr =' + noncestr + '& timestamp =' + timestamp + '& url =' + url); callback ({noncestr: noncestr, timestamp: timestamp, url: url, jsapi_ticket: ticketMap. ticket, signature: sha1 ('jsapi _ ticket = '+ ticketMap. ticket + '& noncestr =' + noncestr + '& timestamp =' + timestamp + '& url =' + url )});}})}})}}

 

Because it is a simple demo, promise is not used, but a common callback is used. Client
Document. getElementById ('refresh '). onclick = function () {location. reload ();}/*** the following content is mostly taken from the official demo ***/wx. config ({debug: true, // enable the debugging mode. The returned values of all called APIs are displayed in the client alert. To view the input parameters, you can open them on the pc, the parameter information is output through log and printed only on the pc end. AppId: appId, // required. The only identifier of the public account is timestamp: timestamp, // required. The signature timestamp is nonceStr, // required, signature generation random string signature: signature, // required, signature, see Appendix 1 jsApiList: ['checkjsapi', 'onmenusharetimeline', 'onmenushareappmessage', 'onmenushareqq ', 'onmenushareweio ', 'hidemenuitems', 'showmenuitems ', 'region', 'delete', 'translateobject', 'startrecord', 'stoprecord', 'onrecordend', 'play Voice ', 'pausevoice', 'stopvoice ', 'uploadvoice', 'downloadvoice ', 'chooseimage', 'previewimage', 'uploadimage', 'downloadimage', 'getnetworktype ', 'openlocation', 'getlocation', 'hideoptionmenu ', 'showoptionmenu', 'closewindow', 'scanqrcode', 'choosewxpay', 'openproductspecificview', 'addcard ', 'choosecard ', 'opencard'] // required. List of JS interfaces to be used,}); wx. ready (function () {// 1 determines whether the current version supports the specified JS interface and supports batch docu determination. Ment. querySelector ('# checkJsApi '). onclick = function () {wx. checkJsApi ({jsApiList: ['getnetworktype', 'previewimage'], success: function (res) {alert (JSON. stringify (res) ;}}) ;}; // 2. the sharing interface // 2.1 listens for "share to a friend", and click the button to customize the sharing content and the sharing result interface document. querySelector ('# onmenushareappmessage '). onclick = function () {wx. onMenuShareAppMessage ({title: 'son of the Internet ', desc:' when I grow up, I slowly find out all the things around me and what others tell me, note They don't have to, but they can be changed. More importantly, if something is wrong, you should change it. ', Link: 'http: // movie.douban.com/subject/25783694/', imgUrl: 'http: // container, trigger: function (res) {// do not try to use ajax asynchronous requests in trigger to modify the content of this share, because the client share operation is a synchronous operation, at this time, the ajax return packet will not return alert ('user click to send to friend ');}, success: function (res) {alert ('shared ');}, cancel: function (res) {alert ('canceled ');}, fail: function (res) {alert (JSON. stringify (res) ;}}); alert ('register to get the "send to friend" status event ');}; // 5 image interface // 5.1 Image taking, Local Image Selection var images = {localId: [], serverId: []}; document. querySelector ('# chooseimage '). onclick = function () {wx. chooseImage ({success: function (res) {images. localId = res. localIds; alert ('selected' + res. localIds. length + 'image') ;}};}; // 5.2 preview document. querySelector ('# previewimage '). onclick = function () {wx. previewImage ({current: 'http: // scheme, urls: ['HTTP: // img3.douban.com/view/photo/photo/public/p2152117150.jpg', 'HTTP: // scheme, 'HTTP: // img3.douban.com/view/photo/photo/public/p2154254700.jpg']}) ;}; // 7.2 obtain the current geographic position document. querySelector ('# getlocation '). onclick = function () {wx. getLocation ({success: function (res) {alert (JSON. stringify (res) ;}, cancel: function (res) {alert ('user denied authorization to obtain geographic location ');}});}; // 9 native interface // 9.1.1 scan the QR code and return the result document. querySelector ('# scanqrcode0 '). onclick = function () {wx. scanQRCode () ;};}); wx. error (function (res) {JSON. stringify (res )});

 


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.