一、申请公众号

获取开发者ID(AppID)和开发者密码(AppSecret)

通过AppID和AppSecret获得access_token

二、认证

1、营业执照

2、组织机构代码证 获得高级接口权限

三、绑定域名

1、微信公众平台进入“公众号设置”的“功能设置”里填写“JS接口安全域名”;

2、下载文件MP_verify_NKeyegDEdGHxmnKJ.txt放置在域名根目录下用来验证

3、在安全中心设置开发者IP白名单,否则无法获取access_token.

注:公众平台以access_token为接口调用凭据,access_token在2小时内有效,过期需要重新获取,但1天内获取次数有限,所以需要全局缓存access_token(写入文件中)

四、代码实现

const express = require('express')
const router = express.Router()
const fs = require('fs')
const { APPID, APPSECRET } = require('../config').wx
const axios = require("axios")
const { createTimestamp, createNonceStr, sign } = require('../utils/wxTools')

/**
 * 获取微信config信息
 * @param {*} url 
 */
async function getWxParams(url) {
	let wx = {
		time: +new Date(),
		appid: APPID,
		ticket: '', 
		timestamp: '',
		noncestr: '',
		signature: ''
	}
	// 获取access_token
	let $res = await axios.get(`https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${APPID}&secret=${APPSECRET}`)

	if ($res.status === 200) {
		// 获取jsapi_ticket
		$res = await axios.get(`https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=${$res.data.access_token}&type=jsapi`)
		
		if ($res.status == 200) {
			wx.ticket = $res.data.ticket
			wx.timestamp = createTimestamp()
			wx.noncestr = createNonceStr()
			wx.signature = sign(url, wx)

			return new Promise((reject, resolve) => {
				// 保存文件
				fs.writeFile('./json/wxConfig.json', JSON.stringify(wx), (err) => {
					if (!err) {
						console.log('wxConfig文件写入成功:', new Date(wx.time))
						fs.readFile('./json/wxConfig.json', 'utf-8', (error, data) => {
							resolve(data)
						})
					} else {
						console.log('wxConfig文件写入失败:', err)
						reject(err)
					}
				})
			})
		}
	}
}
/**
 * 前端获取
 */
router.get('/getWxConfig', async (req, res) => {
	let url = req.query.url
	if (url) {
		// 获取本地wxConfigParams文件信息
		fs.readFile('./json/wxConfig.json', 'utf-8', (error, data) => {
			data = JSON.parse(data)
			// 判断是access_token否过期 2个小时过期
			if ((+new Date() - data.time) / 1000 / 3600 >= 1.8) getWxParams(url).then(res => data = res)
			res.send(data)
		})
	} else {
		res.send({message: 'error'})
	}
})

module.exports = router

config.js

module.exports = {
  Mysql: {
    host: '115.29.195.195',
    user: 'db_daxuexi',
    password: 'HKTtHZWGEjTK5ppB',
    database: 'db_daxuexi'
  },
  wx: {
    APPID: 'wx6efcd0a76539948b',
    APPSECRET: 'd4ee418a23edca447dcf2f7418a90153'
  }
}

utils/wxTools.js

var sha1 = require('sha1')

// 拼接字符串
function rawString(args) {
	let keys = Object.keys(args);
	keys = keys.sort() 
	let newArgs = {}
	keys.forEach(function(key) { 
		newArgs[key.toLowerCase()] = args[key]
	})
	let string = '';
	for (let k in newArgs) {
		string += '&' + k + '=' + newArgs[k]
	} 
	return string.substr(1)
}

module.exports = {
	// 时间戳
	createTimestamp() { 
		return parseInt(new Date().getTime() / 1000).toString()
	},

	// 随机字符串
	createNonceStr() { 
	    return Math.random().toString(36).substr(2, 15)
  	},

  	// 签名
  	sign(url, wx) {
		return sha1(rawString({
			jsapi_ticket: wx.ticket,
			nonceStr: wx.noncestr,
			timestamp: wx.timestamp,
			url: url
		}))
	}
}

参考文档:

https://developers.weixin.qq.com/doc/offiaccount/Basic_Information/Get_access_token.html