Table of Contents
Step 1: Set the JS interface security domain name
Step 2: How to call the interface in the front-end html
Step 3: Generate signature authentication in the background
Step 4: How to debug
Home Web Front-end JS Tutorial Share the whole process of connecting Nodejs to WeChat JS-SDK

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

Jul 11, 2018 pm 04:58 PM
WeChat js-sdk

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);
});
Copy after login

config file code:

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

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>
Copy after login

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);
});
Copy after login

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))
    })
Copy after login

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 of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What should I do if I encounter garbled code printing for front-end thermal paper receipts? What should I do if I encounter garbled code printing for front-end thermal paper receipts? Apr 04, 2025 pm 02:42 PM

Frequently Asked Questions and Solutions for Front-end Thermal Paper Ticket Printing In Front-end Development, Ticket Printing is a common requirement. However, many developers are implementing...

Demystifying JavaScript: What It Does and Why It Matters Demystifying JavaScript: What It Does and Why It Matters Apr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

Who gets paid more Python or JavaScript? Who gets paid more Python or JavaScript? Apr 04, 2025 am 12:09 AM

There is no absolute salary for Python and JavaScript developers, depending on skills and industry needs. 1. Python may be paid more in data science and machine learning. 2. JavaScript has great demand in front-end and full-stack development, and its salary is also considerable. 3. Influencing factors include experience, geographical location, company size and specific skills.

How to merge array elements with the same ID into one object using JavaScript? How to merge array elements with the same ID into one object using JavaScript? Apr 04, 2025 pm 05:09 PM

How to merge array elements with the same ID into one object in JavaScript? When processing data, we often encounter the need to have the same ID...

Is JavaScript hard to learn? Is JavaScript hard to learn? Apr 03, 2025 am 12:20 AM

Learning JavaScript is not difficult, but it is challenging. 1) Understand basic concepts such as variables, data types, functions, etc. 2) Master asynchronous programming and implement it through event loops. 3) Use DOM operations and Promise to handle asynchronous requests. 4) Avoid common mistakes and use debugging techniques. 5) Optimize performance and follow best practices.

How to achieve parallax scrolling and element animation effects, like Shiseido's official website?
or:
How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? How to achieve parallax scrolling and element animation effects, like Shiseido's official website? or: How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? Apr 04, 2025 pm 05:36 PM

Discussion on the realization of parallax scrolling and element animation effects in this article will explore how to achieve similar to Shiseido official website (https://www.shiseido.co.jp/sb/wonderland/)...

The difference in console.log output result: Why are the two calls different? The difference in console.log output result: Why are the two calls different? Apr 04, 2025 pm 05:12 PM

In-depth discussion of the root causes of the difference in console.log output. This article will analyze the differences in the output results of console.log function in a piece of code and explain the reasons behind it. �...

How to implement panel drag and drop adjustment function similar to VSCode in front-end development? How to implement panel drag and drop adjustment function similar to VSCode in front-end development? Apr 04, 2025 pm 02:06 PM

Explore the implementation of panel drag and drop adjustment function similar to VSCode in the front-end. In front-end development, how to implement VSCode similar to VSCode...

See all articles