An overview of

key value
The project name Node wechat official account development
Project description Use node to write the interface and separate the front and back ends to obtain signature data
developers leinov
The release date 2018-11-07
warehouse Making the address

Installation & Use

download
git clone [email protected]:leinov/node-weixin-api.git

npm install
Copy the code
The development of
  • Configure the domain name whitelist in the background of wechat public account
  • inserver/weixin/wx.jsAdd your ownappid secret
  • insrc/index/index.jsIn thewxShareAdd your own share content
  • npm run dev
  • Open the wechat developer tool for debugging
  • npm run build
  • Place the TXT file downloaded during domain configuration in the dist folder
  • Uploading to the server
  • pm2 start www.jsStart the service
  • Open the connection in wechat and share it with your friends for testing
  • Extension: modify/SRC/component/wxconfig jsApiList array of js, want to use WeChat API

architecture

Technology USES

  • Webpack-react-multi-page architecture
  • webpack4
  • react16
  • es6
  • node
  • js-sdk
  • git

Directory structure & Function introduction

| - node - weixin - API / / project | | - dist / / compile production directory - index | -- index. CSS | -- index. Js | -- index. HTML | - XXX. TXT / / WeChat binding domain identification documents | - node_modules | | - server / / node file -- sign. | js/number/public documents provide signature algorithm -- wx. Js / / obtain signature data file | | - SRC / / development directory - index | - Images / | -- js / | - app. Js. | | - b.j s - index SCSS | -- index. | js/js/page entry documents -- template. HTML / / webpack HTML - webpack - plugin plug-in generated HTML templates | -- style. Sass / / public sass | | - webpackConfig / / webpack configuration -- package. Json. | - gitignore | - Webpack. Config. Js / / webpack configuration file | - HTTP: / / www.js / / production start the programCopy the code

WIKI

In the development of wechat web pages, we need to use wechat signature data returned by the back end and configure the front end to use API interfaces such as sharing, image and audio provided by wechat. Here we use the idea of separating the front and back ends, taking sharing to moments as an example, using Node to accomplish this process

The following figure does not use the jS-SDK developed page to share the style in wechat

So let’s do that step by step

Step 1: Bind the domain name

First, log in the wechat public platform, enter the “function setting” of the “public Account Setting”, and fill in the “JS interface security domain name”.

When add the domain name you need to download a TXT file on the server web access to the root directory Such as http://www.leinov.com/xxx.txt access to the root directory of the static, such as the node of the static file Settings is a public document, put under the public

Note: After login, you can check the interface permissions in Developer Center to see whether the user has the permission to share moments

Step 2: Introduce the wechat JS file

Need to call in JS interface pages to introduce the following JS files, support (HTTPS) : res.wx.qq.com/open/js/jwe… You can also download it to a local directory

Step 3: Verify the configuration through the config interface injection permission (Step 6 details)

All pages that need to use JS-SDK must first inject configuration information, otherwise they will not be called (the same URL only needs to be called once, and SPA Web app can be called every time the URL changes. Currently, Android wechat client does not support pushState H5 new feature. So use pushState to implement the Web

wx.config({
    debug: true// If debug mode is enabled, the return value of all API calls will be displayed in the client side alert. To view the passed parameters, you can open it in the PC side and the parameter information will pass throughlogPrint, print only on PC. appId:' 'Timestamp:, // Mandatory, generated signature's timestamp nonceStr:' ', // mandatory, generate a random string signature:' ',// Required, signed jsApiList: [] // Required, list of JS interfaces to use});Copy the code

Under the premise of introducing WX JS-SDK and config, we will mainly explain how to obtain the config data of wechat signature through Node.

Step 4: Generate signature Config data

Step 3 Use signature calculation to generate the required data. The following describes how to generate signature data

  • 1. Obtain the access_token through the appID and secret of the public account
  • 2. Obtain the ticket based on the access_token
  • 3. Generate the signature algorithm based on the node provided by wechat (ticket and URL parameters are required to return config data

It is important to note that secret must be written to the back end and never exposed to the front end, which is why you need an interface to return data.

Get signed config data complete code server/wx.js
/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * @ file: return WeChat development requires the config data * @ desc: * 1, obtain access_token * 2 via appID and secret. Obtain ticket * based on the access_token. 3. Use SGIN to encrypt the ticket and URL (the accessed page address is transmitted through the interface) and return the config data required by the previous request * @ahthor: leinov * @usedate:2018-11-07 **********************************************************************************/ const request = require("request");
const Base64 = require("js-base64").Base64;
const sign = require("./sign.js"); Const base={appid: const base={appid:"* * * *"// public id secret:"* * * *", // public id secret (important not to expose the front end)"https://api.weixin.qq.com/cgi-bin"}; /** * Obtain access_token */ based on appIDfunction  getAccessToken() {return new Promise((resolve, reject)=>{
		request.get(`${base.wxapi}/token? grant_type=client_credential&appid=${base.appid}&secret=${base.secret}`, function (error, response, body) {
			if(error! ==null){ reject("Failed to obtain access_token check getAccessToken function"); } resolve(JSON.parse(body)); }); }); } /** * Obtain api_ticket ** @param {String} access_token * @ based on access_tokenreturn {Promise}
 */
function getTicket(access_token){
	return new Promise((resolve,reject)=>{
		request.get(`${base.wxapi}/ticket/getticket? access_token=${access_token}&type=jsapi`, function (error, response, body) {
			if(error! ==null){ reject("Failed to obtain api_ticket check getTicket function"); } resolve(JSON.parse(body)); }); }); } /** * return all config data encrypted according to api_ticket and URL ** @param {String} href * @return {Object} configdata
 */
async function getConfigData(href){
	letconfigData; try{ const accessTokenData = await getAccessToken(); const ticketData = await getTicket(accessTokenData.access_token); const decodeHref = Base64.decode(href); configData = sign(ticketData.ticket,decodeHref); configData.appid = base.appid; }catch(err){// Prints error log console.log(err); configData = {}; }return configData;
}

module.exports = getConfigData;
Copy the code

Request is used here to request wechat interface. Sign. js is the Node signature algorithm provided by wechat, which can be downloaded by yourself. The following signature data can be obtained through wechat interface request and Node signature algorithm.

Timestamp:, // Generated signature timestamp nonceStr:' '// Generate a random string signature:' ', / / signatureCopy the code

Step 5: Write the interface to return config data

Now that wx.js has retrieved the data above, we write the interface in Node to return the data. Note the following href, href is returned by the front end to generate the signature, and the domain name of the web address must be whitelisted in the Settings.

var express = require("express");
var app = express();
var getConfigData = require("./server/wx.js");
var port = "3000"; // Get wechat configuration data interface app.get("/wxconfigdata".function(req, res){// Get the configurationlethref = req.query.href; GetConfigData (href). Then ((data)=>{res.send(json.stringify (data)); }); }); var server = http.createServer(app); server.listen(port); server.on("listening", onListening);
Copy the code

Then launched a 3000 port services We can get the data by visiting “http://localhost:3000/wxconfigdata”, but this data is not correct, because locahost with white list of domain name does not match in the set, So we put it into a test server during development.

Step 6: Front-end request to obtain signature data

/********************************************************************************* * @file: SRC /wxconfig.js get wechat config data through the interface * @ahthor: leinov * @usedate:2018-11-07 **********************************************************************************/ import { Base64 } from"js-base64";
const axios = require("axios"); ** @param {Object} obj share the title, description, image, etc. * @param {type} callback
 * @return {type} * /functionwxShare(obj,callback){ const href = Base64.encode(location.href); //base64 The current page address is passed to the back end to generate the signature axios.get('${location.origin}/wxconfigdata? href=${href}`).then((res)=>{
		wx.config({
			debug: false// If debug mode is enabled, the return value of all API calls will be displayed in the client side alert. To view the passed parameters, you can open it in the PC side and the parameter information will pass throughlogPrint, print only on PC. AppId: res.data. appId, // Required, the unique identifier of the public number timestamp: res.data.timestamp, // Required, the timestamp of the generated signature nonceStr: Res.data. nonceStr, // Required, random string to generate signature signature: res.data.signature,// Required, signature, see Appendix 1 jsApiList: ["onMenuShareTimeline"."onMenuShareAppMessage"] // Mandatory, need to use the JS interface list, all JS interface list see the documentation}); shareConfig(obj,callback); }).catch((err)=>{ shareConfig({},callback); }); }function shareConfig(obj,callback){
	wx.ready(functionWx. onMenuShareTimeline({title: obj. timelineTitle? ImgUrl: obj.imgurl? Obj.imgurl: obj.imgurl? obj.imgUrl :""// Share icon success:function () {
				if (typeof callback === "function"){
					callback();
				}
			},
			cancel: function() {// callback function executed after user unshares}}); Wx. onMenuShareAppMessage({title: obj.title, // Share the title desc: obj.desc, // Share the description link: obj.link, // share the link imgUrl: obj.imgUrl ? obj.imgUrl:"",
			success: function () {
				if (typeof callback === "function"){
					callback();
				}
			},
			cancel: function() {// callback function executed after user unshares}}); }); }export default wxShare;

Copy the code

Step 7: Page usage

Let’s say we’re using React and call config in the React package entry js file

import wxShare from ".. /component/wxconfig.js";
wxShare({
	title: "Drive duo Duo - Small program Era of Driving School Management System"// Share caption desc:"Jiaduo driving school management system. To help driving schools in the Internet era, zero threshold to use small program tools, improve enrollment, enhance service capacity, reduce operating costs, is to provide driving schools with people, financial, material and business management of the comprehensive management system.Link: location.href, // imgUrl:"https://***/jiaddwxicon.png", // Share icon});Copy the code
If the configuration is correct, it can be configured to share title descriptions and pictures, and the available interface provided by wechat can be achieved.

tips

  • Debug in wechat developer tools
  • Appid and secret must be correct
  • The domain name must be registered
  • The binding domain name needs to be placed on the server TXT position must be correct

reference

  • Wechat official account development document

Github repository code