日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 前端技术 > javascript >内容正文

javascript

nodeJS 开发微信公众号

發(fā)布時(shí)間:2023/11/29 javascript 39 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。