當(dāng)前位置:
首頁 >
前端技术
> javascript
>内容正文
javascript
nodeJS 开发微信公众号
生活随笔
收集整理的這篇文章主要介紹了
nodeJS 开发微信公众号
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
準(zhǔn)備測(cè)試公眾號(hào)
mp.weixin.qq.com/debug/cgi-b…
關(guān)注,獲取測(cè)試公眾號(hào)
內(nèi)網(wǎng)滲透工具
natapp.cn/login 按照教程下載客戶端進(jìn)行配置
后臺(tái)服務(wù)接入公眾號(hào)
有netapp 生成的映射外網(wǎng)IP => URL
搭建express開發(fā)環(huán)境
這個(gè)網(wǎng)上有教程,自行百度
接口配置和簽名驗(yàn)證
接入微信平臺(tái)
Token:自主設(shè)置,這個(gè)token與公眾平臺(tái)wiki中常提的access_token不是一回事。這個(gè)token只用于驗(yàn)證開發(fā)者服務(wù)器
mp.weixin.qq.com/wiki?t=reso…
// 認(rèn)證開發(fā)者服務(wù)器 function sign(config, req, res, next) {const {signature,timestamp,nonce,echostr,} = req.queryconst conf = config || {}const { token } = conf.wechat// 1. 將token、timestamp、nonce三個(gè)參數(shù)進(jìn)行字典序排序const array = [token, timestamp, nonce]array.sort()const str = array.toString().replace(/,/g, '')// 2. 將三個(gè)參數(shù)字符串拼接成一個(gè)字符串進(jìn)行sha1加密const sha1Code = crypto.createHash('sha1')const code = sha1Code.update(str, 'utf-8').digest('hex')// 3. 開發(fā)者獲得加密后的字符串可與signature對(duì)比,標(biāo)識(shí)該請(qǐng)求來源于微信if (req.method === 'GET') {if (code === signature) {res.send(echostr)} else {res.send('error')}} else if (req.method === 'POST') {if (code !== signature) {return}next()}} 復(fù)制代碼獲取access_token
微信公眾號(hào)文檔中已經(jīng)詳細(xì)說明了,access_token是公眾號(hào)的全局唯一接口調(diào)用憑據(jù),因此每個(gè)接口均要加上access_token mp.weixin.qq.com/wiki?t=reso…
// config.json {"wechat" : {"appID": "","appSecret": "","token": "access_token","prefix": "https://api.weixin.qq.com/cgi-bin/","mpPrefix": "https://mp.weixin.qq.com/cgi-bin/"} } 復(fù)制代碼/**微信相關(guān)操作api*/const config = require('./config/config') const utils = require('./utils')const wechatApi = {} const { appID, appSecret } = config.wechat const api = {accessToken: `${config.wechat.prefix}token?grant_type=client_credential`,upload: `${config.wechat.prefix}media/upload?`, }// 獲取access_token wechatApi.updateAccessToken = function () {const option = {url: `${api.accessToken}&appid=${appID}&secret=${appSecret}`,json: true,}return utils.request(option).then(data => Promise.resolve(data)) }module.exports = wechatApi復(fù)制代碼// ../routes/index.jsconst express = require('express') const config = require('../config/config') const utils = require('../utils') const wechatApi = require('../wechatApi')const router = express.Router() // 獲取,驗(yàn)證access_token,存入redis中 // 路由之前,添加token router.use((req, res, next) => {// 根據(jù)token從redis中獲取access_tokenutils.get(config.wechat.token).then((data) => {// 獲取到值--往下傳遞if (data) {return Promise.resolve(data)}// 沒獲取到值--從微信服務(wù)器端獲取,并往下傳遞return wechatApi.updateAccessToken()}).then((data) => {// console.log(data);// 沒有expire_in值--此data是redis中獲取到的if (!data.expires_in) {// console.log('redis獲取到值');req.accessToken = datanext()} else {// 有expire_in值--此data是微信端獲取到的// console.log('redis中無值');// 保存到redis中,由于微信的access_token是7200秒過期,// 存到redis中的數(shù)據(jù)減少20秒,設(shè)置為7180秒過期utils.set(config.wechat.token, `${data.access_token}`, 7180).then((result) => {if (result === 'OK') {req.accessToken = data.access_tokennext()}})}}) }) module.exports = router復(fù)制代碼引入wechat模塊
// ../routes/wechat.jsconst express = require('express') const wechat = require('wechat') const conf = require('../config/config') const service = require('../service.js')const router = express.Router() router.use(express.query()) const config = {token: conf.wechat.token,appid: conf.wechat.appID,appsecret: conf.wechat.appSecret,encodingAESKey: '', }router.use('/', wechat(config, (req, res) => {const message = req.weixinconst {MsgType,} = messageswitch (MsgType) {case 'text': // 文本service.handleText(res, message.Content)breakdefault:res.reply('服務(wù)器內(nèi)部錯(cuò)誤,請(qǐng)重試')} }))module.exports = router復(fù)制代碼開始測(cè)試
const createError = require('http-errors') const express = require('express') const path = require('path') const cookieParser = require('cookie-parser') const logger = require('morgan') const indexRouter = require('./routes/index') const wechatRouter = require('./routes/wechat') const utils = require('./utils') const config = require('./config/config.json')const app = express()// view engine setup app.set('views', path.join(__dirname, 'views')) app.set('view engine', 'jade') app.use(logger('dev')) app.use(express.json()) app.use(express.urlencoded({ extended: false })) app.use(cookieParser()) app.use(express.static(path.join(__dirname, 'public'))) app.use(utils.sign(config)) // 接口配置和簽名驗(yàn)證 app.use('/', indexRouter) app.use('/wechat', wechatRouter)// catch 404 and forward to error handler app.use((req, res, next) => {next(createError(404)) })// error handler app.use((err, req, res) => {// set locals, only providing error in developmentres.locals.message = err.messageres.locals.error = req.app.get('env') === 'development' ? err : {}// render the error pageres.status(err.status || 500)res.render('error') }) module.exports = app復(fù)制代碼- 開啟開發(fā)者服務(wù)
- 填寫接口配置信息
- 結(jié)果
總結(jié)
以上是生活随笔為你收集整理的nodeJS 开发微信公众号的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 梦到老公出轨小三怀孕是怎么回事
- 下一篇: Spring Cloud构建微服务架构-