Home  >  Article  >  Web Front-end  >  Share the whole process of connecting Nodejs to WeChat JS-SDK

Share the whole process of connecting Nodejs to WeChat JS-SDK

不言
不言Original
2018-07-11 16:58:352109browse

This article mainly introduces the whole process of sharing Nodejs to access WeChat JS-SDK. It has a certain reference value. Now I share it with everyone. Friends in need can refer to it.

I thought it was connected WeChat JS-SDK is a very simple thing. I ended up stuck in the pit for several days. After consulting all kinds of useless information, I finally came up with it after a lot of trouble. I will write it down and hope that others will see it later. This article can help you climb out of the pit early

Step 1: Set the JS interface security domain name

After logging in to your WeChat public platform, select Settings-》Public Account Settings from the left menu -》Function Settings-》JS interface security domain name. It lists several precautions for you, such as the domain name to be registered and passed, and MP_verify_nnbEERhXNfbMC8Z0.txt to be uploaded to the server. Just follow this step and a request will be sent to the address you filled in. , after you receive it, you need to use sha1 encryption for comparison

Nodejs code:

var express = require('express');
var crypto = require('crypto');  //引入加密模块
var config = require('./config');//引入配置文件
var http = require('http');

var app = express();
 
app.get('/wx', function (req, res) {

    //1.获取微信服务器Get请求的参数 signature、timestamp、nonce、echostr
    var signature = req.query.signature,//微信加密签名
        timestamp = req.query.timestamp,//时间戳
        nonce = req.query.nonce,//随机数
        echostr = req.query.echostr;//随机字符串

    //2.将token、timestamp、nonce三个参数进行字典序排序
   
    var array = [config.token, timestamp, nonce];
    array.sort();

    //3.将三个参数字符串拼接成一个字符串进行sha1加密
    var tempStr = array.join('');
    const hashCode = crypto.createHash('sha1'); //创建加密类型 
    var resultCode = hashCode.update(tempStr, 'utf8').digest('hex'); //对传入的字符串进行加密
    console.log(signature)
    //4.开发者获得加密后的字符串可与signature对比,标识该请求来源于微信
    if (resultCode === signature) {
        res.send(echostr);
    } else {
        res.send('mismatch');
    }
});


var server = app.listen(3000, function () {
    var host = server.address().address;
    var port = server.address().port;
    console.log('Example app listening at http://%s:%s', host, port);
});

config file code:

{
    "token":"test",
    "appId":"wx1c9dedd4d06c8f14",
    "appSecret":"07b365cb9e600b5ce04915f59623eb99"
}

Step 2: How to call the interface in the front-end html

Officially provided http://203.195.235.76/jssdk/ This is still very helpful. The front-end configuration is copied from here. First create an html page to call the interface to implement the function. Here you need Note that some interfaces cannot be called without authentication of subscription accounts (see Baidu results for specific permissions: https://jingyan.baidu.com/art...)

I call pictures here to take pictures/select this on my mobile phone Function, create the Image.html page, the Image.html code is as follows: (Most of the code here is copied from the official page, this is not the point)

<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <title>选择图像</title>
    <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=0">
</head>

<body>
    <button class="btn btn_primary" id="checkJsApi">checkJsApi</button>
    <h3 id="menu-image">图像接口</h3>
    <span class="desc">拍照或从手机相册中选图接口</span>
    <button class="btn btn_primary" id="chooseImage">chooseImage</button>
 


</body>
<script src="http://203.195.235.76/jssdk/js/zepto.min.js"></script>
<script src="http://res.wx.qq.com/open/js/jweixin-1.0.0.js"></script>
<script>
    $.get("http:/xx.xx.cn/getsign", function (res) {
        console.log(res)
        wx.config({
            debug: true, // 开启调试模式
            appId: "你的appid", // 必填,公众号的唯一标识
            timestamp: res.timestamp, // 必填,生成签名的时间戳
            nonceStr: res.noncestr, // 必填,生成签名的随机串
            signature: res.signature,// 必填,签名,见附录1
            jsApiList: ['chooseImage',
                'previewImage',
                'uploadImage',
                'downloadImage'] // 必填,需要使用的JS接口列表,所有JS接口列表见附录2
        });
    })

</script>

<script>
  
    wx.error(function(res){
        console.log(JSON.stringify(res))
    })
    wx.ready(function () {
        // 1 判断当前版本是否支持指定 JS 接口,支持批量判断
        document.querySelector('#checkJsApi').onclick = function () {
            wx.checkJsApi({
                jsApiList: [
                    'chooseImage',
                    'previewImage',
                    'uploadImage',
                    'downloadImage'
                ],
                success: function (res) {
                    alert(JSON.stringify(res));
                }
            });
        };

        // 5 图片接口
        // 5.1 拍照、本地选图
        var images = {
            localId: []
        };
        document.querySelector('#chooseImage').onclick = function () {
           
            wx.chooseImage({
                success: function (res) {
                    images.localId = res.localIds;
                    alert('已选择 ' + res.localIds.length + ' 张图片');
                },
                error:function(res){
                    alert("error")
                    alert("res")
                }
            });
        };
    })
</script>
</html>

Step 3: Generate signature authentication in the background

Finally we have reached the point where we have been stuck for the past few days. The config: invalid signature error occurred repeatedly. Later, I finally found the problem. 1. The generation timestamp must be accurate to the second. 2. The URL required during generation. In fact, it is the url address of the front page.

Let’s do it step by step. First, create jssdk.js, which is used to return the information required by wx.config (specifically what does each one mean? Please refer to the official documentation for this. The writing is very clear https://mp.weixin.qq.com/wiki...), you can print out the generated token/ticket during development, and use the official tool https://mp.weixin .qq.com/debu... Test and compare whether the signature is consistent

The complete jssdk.js code is as follows:

var request = require('request'),
    cache = require('memory-cache'),
    sha1 = require('sha1')

var express = require('express');

var app = express();
app.use('/wx', express.static('static'));

app.get('/getsign', function (req, res) {
    var url = "http://xx.xx.cn/wx/Image.html"
    console.log(url)
    var noncestr = "123456",
        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 + '&timestamp=' + timestamp + '&url=' + url);
        obj = {
            noncestr: noncestr,
            timestamp: timestamp,
            url: url,
            jsapi_ticket: jsapi_ticket,
            signature: sha1('jsapi_ticket=' + jsapi_ticket + '&noncestr=' + noncestr + '&timestamp=' + timestamp + '&url=' + url)
        };
        res.send(obj)
    } else {
        request('https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=appid&secret=secret', function (error, response, body) {
            if (!error && response.statusCode == 200) {
                var tokenMap = JSON.parse(body);
                request('https://api.weixin.qq.com/cgi-bin/ticket/getticket?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, (1000 * 60 * 60 * 24));  //加入缓存
                        // console.log('jsapi_ticket=' + ticketMap.ticket + '&noncestr=' + noncestr + '&timestamp=' + timestamp + '&url=' + url);
                        obj = {
                            noncestr: noncestr,
                            timestamp: timestamp,
                            url: url,
                            jsapi_ticket: ticketMap.ticket,
                            signature: sha1('jsapi_ticket=' + ticketMap.ticket + '&noncestr=' + noncestr + '&timestamp=' + timestamp + '&url=' + url)
                        }
                        res.send(obj)
                    }
                })
            }
        })
    }
});


var server = app.listen(3000, function () {
    var host = server.address().address;
    var port = server.address().port;
    console.log('Example app listening at http://%s:%s', host, port);
});

Step 4: How to debug

1. After everything is written, you can’t see the effect when you run Image.html on the browser. You have to run WeChat on your mobile phone to see the effect. At this time, you can use the grass QR code https://cli.im/url. I have been using it, and it is very good. To use, you paste the address (http://xx.xx.cn/wx/Image.html) and generate a QR code, just scan it with your mobile phone WeChat

2.Image.html The debug in wx.config must be set to true. Add

    wx.error(function(res){
        console.log(JSON.stringify(res))
    })

outside wx.ready. The above is the entire content of this article. I hope it will be helpful to everyone's study. For more related content, please Follow PHP Chinese website!

Related recommendations:

Introduction to Node asynchronous I/O

The above is the detailed content of Share the whole process of connecting Nodejs to WeChat JS-SDK. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn