當前位置:
首頁 >
前端技术
> javascript
>内容正文
javascript
nodeJS 开发微信公众号
生活随笔
收集整理的這篇文章主要介紹了
nodeJS 开发微信公众号
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
準備測試公眾號
mp.weixin.qq.com/debug/cgi-b…
關注,獲取測試公眾號
內網滲透工具
natapp.cn/login 按照教程下載客戶端進行配置
后臺服務接入公眾號
有netapp 生成的映射外網IP => URL
搭建express開發環境
這個網上有教程,自行百度
接口配置和簽名驗證
接入微信平臺
Token:自主設置,這個token與公眾平臺wiki中常提的access_token不是一回事。這個token只用于驗證開發者服務器
mp.weixin.qq.com/wiki?t=reso…
// 認證開發者服務器 function sign(config, req, res, next) {const {signature,timestamp,nonce,echostr,} = req.queryconst conf = config || {}const { token } = conf.wechat// 1. 將token、timestamp、nonce三個參數進行字典序排序const array = [token, timestamp, nonce]array.sort()const str = array.toString().replace(/,/g, '')// 2. 將三個參數字符串拼接成一個字符串進行sha1加密const sha1Code = crypto.createHash('sha1')const code = sha1Code.update(str, 'utf-8').digest('hex')// 3. 開發者獲得加密后的字符串可與signature對比,標識該請求來源于微信if (req.method === 'GET') {if (code === signature) {res.send(echostr)} else {res.send('error')}} else if (req.method === 'POST') {if (code !== signature) {return}next()}} 復制代碼獲取access_token
微信公眾號文檔中已經詳細說明了,access_token是公眾號的全局唯一接口調用憑據,因此每個接口均要加上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/"} } 復制代碼/**微信相關操作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復制代碼// ../routes/index.jsconst express = require('express') const config = require('../config/config') const utils = require('../utils') const wechatApi = require('../wechatApi')const router = express.Router() // 獲取,驗證access_token,存入redis中 // 路由之前,添加token router.use((req, res, next) => {// 根據token從redis中獲取access_tokenutils.get(config.wechat.token).then((data) => {// 獲取到值--往下傳遞if (data) {return Promise.resolve(data)}// 沒獲取到值--從微信服務器端獲取,并往下傳遞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中的數據減少20秒,設置為7180秒過期utils.set(config.wechat.token, `${data.access_token}`, 7180).then((result) => {if (result === 'OK') {req.accessToken = data.access_tokennext()}})}}) }) module.exports = router復制代碼引入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('服務器內部錯誤,請重試')} }))module.exports = router復制代碼開始測試
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)) // 接口配置和簽名驗證 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復制代碼- 開啟開發者服務
- 填寫接口配置信息
- 結果
總結
以上是生活随笔為你收集整理的nodeJS 开发微信公众号的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 梦到老公出轨小三怀孕是怎么回事
- 下一篇: Spring Cloud构建微服务架构-