最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Koa2微信公眾號開發(fā)之消息管理

 更新時間:2018年05月16日 16:19:50   作者:流口水流  
這篇文章主要介紹了Koa2微信公眾號開發(fā)之消息管理,這一節(jié)我們就來看看公眾號的消息管理。并實(shí)現(xiàn)一個自動回復(fù)功能,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下

一、簡介

上一節(jié)Koa2微信公眾號開發(fā)(一),我們搭建好了本地調(diào)試環(huán)境并且接入了微信公眾測試號。這一節(jié)我們就來看看公眾號的消息管理。并實(shí)現(xiàn)一個自動回復(fù)功能。

Github源碼: github.com/ogilhinn/ko…

閱讀建議:微信公眾平臺開發(fā)文檔mp.weixin.qq.com/wiki

二、接收消息

當(dāng)普通微信用戶向公眾賬號發(fā)消息時,微信服務(wù)器將POST消息的XML數(shù)據(jù)包到開發(fā)者填寫的URL上。

2.1 接收普通消息數(shù)據(jù)格式

XML的結(jié)構(gòu)基本固定,不同的消息類型略有不同。

用戶發(fā)送文本消息時,微信公眾賬號接收到的XML數(shù)據(jù)格式如下所示:

<xml>
 <ToUserName><![CDATA[toUser]]></ToUserName>
 <FromUserName><![CDATA[fromUser]]></FromUserName>
 <CreateTime>createTime</CreateTime>
 <MsgType><![CDATA[text]]></MsgType>
 <Content><![CDATA[this is a test]]></Content>
 <MsgId>1234567890123456</MsgId>
</xml>

用戶發(fā)送圖片消息時,微信公眾賬號接收到的XML數(shù)據(jù)格式如下所示:

<xml> 
 <ToUserName><![CDATA[toUser]]></ToUserName>
 <FromUserName><![CDATA[fromUser]]></FromUserName>
 <CreateTime>1348831860</CreateTime> 
 <MsgType><![CDATA[image]]></MsgType> 
 <PicUrl><![CDATA[this is a url]]></PicUrl>
 <MediaId><![CDATA[media_id]]></MediaId> 
 <MsgId>1234567890123456</MsgId>
</xml>

其他消息消息類型的結(jié)構(gòu)請查閱【微信公眾平臺開發(fā)文檔】

對于POST請求的處理,koa2沒有封裝獲取參數(shù)的方法,需要通過自己解析上下文context中的原生node.js請求對象request。我們將用到row-body這個模塊來拿到數(shù)據(jù)。

2.2 先來優(yōu)化之前的代碼

這一節(jié)的代碼緊接著上一屆實(shí)現(xiàn)的代碼,在上一屆的基礎(chǔ)上輕微改動了下。

'use strict'

const Koa = require('koa')
const app = new Koa()
const crypto = require('crypto')
// 將配置文件獨(dú)立到config.js
const config = require('./config')

app.use(async ctx => {
 // GET 驗(yàn)證服務(wù)器
 if (ctx.method === 'GET') {
  const { signature, timestamp, nonce, echostr } = ctx.query
  const TOKEN = config.wechat.token
  let hash = crypto.createHash('sha1')
  const arr = [TOKEN, timestamp, nonce].sort()
  hash.update(arr.join(''))
  const shasum = hash.digest('hex')
  if (shasum === signature) {
   return ctx.body = echostr
  }
  ctx.status = 401
  ctx.body = 'Invalid signature'
 } else if (ctx.method === 'POST') { // POST接收數(shù)據(jù)
  // TODO
 }
});

app.listen(7001);

這兒我們在只在GET中驗(yàn)證了簽名值是否合法,實(shí)際上我們在POST中也應(yīng)該驗(yàn)證簽名。

將簽名驗(yàn)證寫成一個函數(shù)

function getSignature (timestamp, nonce, token) {
 let hash = crypto.createHash('sha1')
 const arr = [token, timestamp, nonce].sort()
 hash.update(arr.join(''))
 return hash.digest('hex')
}

優(yōu)化代碼,再POST中也加入驗(yàn)證

...

app.use(async ctx => {
 const { signature, timestamp, nonce, echostr } = ctx.query
 const TOKEN = config.wechat.token
 if (ctx.method === 'GET') {
  if (signature === getSignature(timestamp, nonce, TOKEN)) {
   return ctx.body = echostr
  }
  ctx.status = 401
  ctx.body = 'Invalid signature'
 }else if (ctx.method === 'POST') {
  if (signature !== getSignature(timestamp, nonce, TOKEN)) {
   ctx.status = 401
   return ctx.body = 'Invalid signature'
  }
  // TODO
 }
});
...

到這兒我們都沒有開始實(shí)現(xiàn)接受XML數(shù)據(jù)包的功能,而是在修改之前的代碼。這是為了演示在實(shí)際開發(fā)中的過程,寫任何代碼都不是一步到位的,好的代碼都是改出來的。

2.3 接收公眾號普通消息的XML數(shù)據(jù)包

現(xiàn)在開始進(jìn)入本節(jié)的重點(diǎn),接受XML數(shù)據(jù)包并轉(zhuǎn)為JSON

$ npm install raw-body --save
...
const getRawBody = require('raw-body')
...

// TODO
// 取原始數(shù)據(jù)
const xml = await getRawBody(ctx.req, {
 length: ctx.request.length,
 limit: '1mb',
 encoding: ctx.request.charset || 'utf-8'
});
console.log(xml)
return ctx.body = 'success' // 直接回復(fù)success,微信服務(wù)器不會對此作任何處理

給你的測試號發(fā)送文本消息,你可以在命令行看見打印出如下數(shù)據(jù)

<xml>
 <ToUserName><![CDATA[gh_9d2d49e7e006]]></ToUserName>
 <FromUserName><![CDATA[oBp2T0wK8lM4vIkmMTJfFpk6Owlo]]></FromUserName>
 <CreateTime>1516940059</CreateTime>
 <MsgType><![CDATA[text]]></MsgType>
 <Content><![CDATA[JavaScript之禪]]></Content>
 <MsgId>6515207943908059832</MsgId>
</xml>

恭喜,到此你已經(jīng)可以接收到XML數(shù)據(jù)了。😯 但是我們還需要將XML轉(zhuǎn)為JSON方便我們的使用,我們將用到xml2js這個包

$ npm install xml2js --save

我們需要寫一個解析XML的異步函數(shù),返回一個Promise對象

function parseXML(xml) {
 return new Promise((resolve, reject) => {
  xml2js.parseString(xml, { trim: true, explicitArray: false, ignoreAttrs: true }, function (err, result) {
   if (err) {
    return reject(err)
   }
   resolve(result.xml)
  })
 })
}

接著調(diào)用parseXML方法,并打印出結(jié)果

...
const formatted = await parseXML(xml)
console.log(formatted)
return ctx.body = 'success'

一切正常的話*(實(shí)際開發(fā)中你可能會遇到各種問題)*,命令行將打印出如下JSON數(shù)據(jù)

{ ToUserName: 'gh_9d2d49e7e006',
 FromUserName: 'oBp2T0wK8lM4vIkmMTJfFpk6Owlo',
 CreateTime: '1516941086',
 MsgType: 'text',
 Content: 'JavaScript之禪',
 MsgId: '6515212354839473910' }

到此,我們就能處理微信接收到的消息了,你可以自己測試關(guān)注、取消關(guān)注、發(fā)送各種類型的消息看看這個類型的消息所對應(yīng)的XML數(shù)據(jù)格式都是怎么樣的

三、回復(fù)消息

當(dāng)用戶發(fā)送消息給公眾號時(或某些特定的用戶操作引發(fā)的事件推送時),會產(chǎn)生一個POST請求,開發(fā)者可以在響應(yīng)包(Get)中返回特定XML結(jié)構(gòu),來對該消息進(jìn)行響應(yīng)(現(xiàn)支持回復(fù)文本、圖片、圖文、語音、視頻、音樂)。嚴(yán)格來說,發(fā)送被動響應(yīng)消息其實(shí)并不是一種接口,而是對微信服務(wù)器發(fā)過來消息的一次回復(fù)。

3.1 被動回復(fù)用戶消息數(shù)據(jù)格式

前面說了交互的數(shù)據(jù)格式為XML,接收消息是XML的,我們回復(fù)回去也應(yīng)該是XML。

微信公眾賬號回復(fù)用戶文本消息時的XML數(shù)據(jù)格式如下所示:

<xml> 
 <ToUserName><![CDATA[toUser]]></ToUserName> 
 <FromUserName><![CDATA[fromUser]]></FromUserName> 
 <CreateTime>12345678</CreateTime> 
 <MsgType><![CDATA[text]]></MsgType> 
 <Content><![CDATA[你好]]></Content> 
</xml>

微信公眾賬號回復(fù)用戶圖片消息時的XML數(shù)據(jù)格式如下所示:

<xml>
 <ToUserName><![CDATA[toUser]]></ToUserName>
 <FromUserName><![CDATA[fromUser]]></FromUserName>
 <CreateTime>12345678</CreateTime>
 <MsgType><![CDATA[image]]></MsgType>
 <Image><MediaId><![CDATA[media_id]]></MediaId></Image>
</xml>

篇幅所限就不一一列舉了,請查閱【微信公眾平臺開發(fā)文檔】

前面的代碼都是直接回復(fù)success,不做任何處理。先來擼一個自動回復(fù)吧。收到消息后就回復(fù)這兒是JavaScript之禪

// return ctx.body = 'success' // 直接success
ctx.type = 'application/xml'
return ctx.body = `<xml> 
<ToUserName><![CDATA[${formatted.FromUserName}]]></ToUserName> 
<FromUserName><![CDATA[${formatted.ToUserName}]]></FromUserName> 
<CreateTime>${new Date().getTime()}</CreateTime> 
<MsgType><![CDATA[text]]></MsgType> 
<Content><![CDATA[這兒是JavaScript之禪]]></Content> 
</xml>`

3.2 使用ejs模板引擎處理回復(fù)內(nèi)容

從這一小段代碼中可以看出,被動回復(fù)消息就是把你想要回復(fù)的內(nèi)容按照約定的XML格式返回即可。但是一段一段的拼XML那多麻煩。我們來加個模板引擎方便我們處理XML。模板引擎有很多,ejs 是其中一種,它使用起來十分簡單

首先下載并引入ejs

$ npm install ejs --save

如果你之前沒用過現(xiàn)在只需要記住下面這幾個語法,以及ejs.compile()方法

  1. <% code %>:運(yùn)行 JavaScript 代碼,不輸出
  2. <%= code %>:顯示轉(zhuǎn)義后的 HTML內(nèi)容
  3. <%- code %>:顯示原始 HTML 內(nèi)容

可以先看看這個ejs的小demo:

const ejs = require('ejs')
let tpl = `
<xml> 
 <ToUserName><![CDATA[<%-toUsername%>]]></ToUserName> 
 <FromUserName><![CDATA[<%-fromUsername%>]]></FromUserName> 
 <CreateTime><%=createTime%></CreateTime> 
 <MsgType><![CDATA[<%=msgType%>]]></MsgType> 
 <Content><![CDATA[<%-content%>]]></Content> 
</xml>
`
const compiled = ejs.compile(tpl)
let mess = compiled({
 toUsername: '1234',
 fromUsername: '12345',
 createTime: new Date().getTime(),
 msgType: 'text',
 content: 'JavaScript之禪',
})

console.log(mess)

/* 將打印出如下信息 
 *================
<xml>
 <ToUserName><![CDATA[1234]]></ToUserName>
 <FromUserName><![CDATA[12345]]></FromUserName>
 <CreateTime>1517037564494</CreateTime>
 <MsgType><![CDATA[text]]></MsgType>
 <Content><![CDATA[JavaScript之禪]]></Content>
</xml>
*/

現(xiàn)在來編寫被動回復(fù)消息的模板,各種if else,這兒就直接貼代碼了

<xml>
 <ToUserName><![CDATA[<%-toUsername%>]]></ToUserName>
 <FromUserName><![CDATA[<%-fromUsername%>]]></FromUserName>
 <CreateTime><%=createTime%></CreateTime>
 <MsgType><![CDATA[<%=msgType%>]]></MsgType>
 <% if (msgType === 'news') { %>
 <ArticleCount><%=content.length%></ArticleCount>
 <Articles>
 <% content.forEach(function(item){ %>
 <item>
 <Title><![CDATA[<%-item.title%>]]></Title>
 <Description><![CDATA[<%-item.description%>]]></Description>
 <PicUrl><![CDATA[<%-item.picUrl || item.picurl || item.pic || item.thumb_url %>]]></PicUrl>
 <Url><![CDATA[<%-item.url%>]]></Url>
 </item>
 <% }); %>
 </Articles>
 <% } else if (msgType === 'music') { %>
 <Music>
 <Title><![CDATA[<%-content.title%>]]></Title>
 <Description><![CDATA[<%-content.description%>]]></Description>
 <MusicUrl><![CDATA[<%-content.musicUrl || content.url %>]]></MusicUrl>
 <HQMusicUrl><![CDATA[<%-content.hqMusicUrl || content.hqUrl %>]]></HQMusicUrl>
 </Music>
 <% } else if (msgType === 'voice') { %>
 <Voice>
 <MediaId><![CDATA[<%-content.mediaId%>]]></MediaId>
 </Voice>
 <% } else if (msgType === 'image') { %>
 <Image>
 <MediaId><![CDATA[<%-content.mediaId%>]]></MediaId>
 </Image>
 <% } else if (msgType === 'video') { %>
 <Video>
 <MediaId><![CDATA[<%-content.mediaId%>]]></MediaId>
 <Title><![CDATA[<%-content.title%>]]></Title>
 <Description><![CDATA[<%-content.description%>]]></Description>
 </Video>
 <% } else { %>
 <Content><![CDATA[<%-content%>]]></Content>
 <% } %>
</xml>

現(xiàn)在就可以使用我們寫好的模板回復(fù)XML消息了

...
const formatted = await parseXML(xml)
console.log(formatted)
let info = {}
let type = 'text'
info.msgType = type
info.createTime = new Date().getTime()
info.toUsername = formatted.FromUserName
info.fromUsername = formatted.ToUserName
info.content = 'JavaScript之禪'
return ctx.body = compiled(info)

我們可以把這個回復(fù)消息的功能寫成一個函數(shù)

function reply (content, fromUsername, toUsername) {
 var info = {}
 var type = 'text'
 info.content = content || ''
 // 判斷消息類型
 if (Array.isArray(content)) {
  type = 'news'
 } else if (typeof content === 'object') {
  if (content.hasOwnProperty('type')) {
   type = content.type
   info.content = content.content
  } else {
   type = 'music'
  }
 }
 info.msgType = type
 info.createTime = new Date().getTime()
 info.toUsername = toUsername
 info.fromUsername = fromUsername
 return compiled(info)
}

在回復(fù)消息的時候直接調(diào)用這個方法即可

...
const formatted = await parseXML(xml)
console.log(formatted)
const content = 'JavaScript之禪'
const replyMessageXml = reply(content, formatted.ToUserName, formatted.FromUserName)
return ctx.body = replyMessageXml

現(xiàn)在為了測試我們所寫的這個功能,來實(shí)現(xiàn)一個【學(xué)我說話】的功能:

回復(fù)音樂將返回一個音樂類型的消息,回復(fù)文本圖片,語音,公眾號將返回同樣的內(nèi)容,當(dāng)然了你可以在這個基礎(chǔ)上進(jìn)行各種發(fā)揮。

....
const formatted = await parseXML(xml)
console.log(formatted)
let content = ''
if (formatted.Content === '音樂') {
 content = {
  type: 'music',
  content: {
   title: 'Lemon Tree',
   description: 'Lemon Tree',
   musicUrl: 'http://mp3.com/xx.mp3'
  },
 }
} else if (formatted.MsgType === 'text') {
 content = formatted.Content
} else if (formatted.MsgType === 'image') {
 content = {
  type: 'image',
  content: {
   mediaId: formatted.MediaId
  },
 }
} else if (formatted.MsgType === 'voice') {
 content = {
  type: 'voice',
  content: {
   mediaId: formatted.MediaId
  },
 }
} else {
 content = 'JavaScript之禪'
}
const replyMessageXml = reply(content, formatted.ToUserName, formatted.FromUserName)
console.log(replyMessageXml)
ctx.type = 'application/xml'
return ctx.body = replyMessageXml

nice,到此時我們的測試號已經(jīng)能夠根據(jù)我們的消息做出相應(yīng)的回應(yīng)了

本篇再上一節(jié)的代碼基礎(chǔ)上做了一些優(yōu)化,并重點(diǎn)講解微信公眾號的消息交互,最后實(shí)現(xiàn)了個【學(xué)我說話】的小功能。下一篇,我們將繼續(xù)補(bǔ)充消息管理相關(guān)的知識。最后再說一句:看文檔 😉

參考鏈接

微信公眾平臺開發(fā)文檔:mp.weixin.qq.com/wiki
raw-body:https://github.com/stream-utils/raw-body
xml2js: github.com/Leonidas-fr…
ejs:github.com/mde/ejs
源碼: github.com/ogilhinn/ko…

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

  • Node.js創(chuàng)建子進(jìn)程的幾種實(shí)現(xiàn)方式

    Node.js創(chuàng)建子進(jìn)程的幾種實(shí)現(xiàn)方式

    這篇文章主要介紹了Node.js創(chuàng)建子進(jìn)程的幾種實(shí)現(xiàn)方式,具有很好的參考價(jià)值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
    2023-10-10
  • Node.js API詳解之 net模塊實(shí)例分析

    Node.js API詳解之 net模塊實(shí)例分析

    這篇文章主要介紹了Node.js API詳解之 net模塊,結(jié)合實(shí)例形式分析了Node.js API中net模塊基本函數(shù)、用法與使用技巧,需要的朋友可以參考下
    2020-05-05
  • Node.js環(huán)境下JavaScript實(shí)現(xiàn)單鏈表與雙鏈表結(jié)構(gòu)

    Node.js環(huán)境下JavaScript實(shí)現(xiàn)單鏈表與雙鏈表結(jié)構(gòu)

    Node環(huán)境下通過npm可以獲取list的幾個相關(guān)庫,但是我們這里注重于自己動手實(shí)現(xiàn),接下來就一起來看一下Node.js環(huán)境下JavaScript實(shí)現(xiàn)單鏈表與雙鏈表結(jié)構(gòu)
    2016-06-06
  • 簡單聊一聊Node.js參數(shù)max-old-space-size

    簡單聊一聊Node.js參數(shù)max-old-space-size

    簡單的說Node.js就是運(yùn)行在服務(wù)端的JavaScript,下面這篇文章主要給大家介紹了關(guān)于Node.js參數(shù)max-old-space-size的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),需要的朋友可以參考下
    2023-01-01
  • 淺談Node.js:理解stream

    淺談Node.js:理解stream

    本篇文章主要介紹了Node.js:stream,Stream在node.js中是一個抽象的接口,具有一定的參考價(jià)值,有需要的可以了解一下。
    2016-12-12
  • 詳解nodejs爬蟲程序解決gbk等中文編碼問題

    詳解nodejs爬蟲程序解決gbk等中文編碼問題

    本篇文章主要介紹了nodejs爬蟲程序解決gbk等中文編碼問題,解決了網(wǎng)頁的編碼與nodejs默認(rèn)編碼不一致造成的亂碼問題,有興趣的可以了解一下
    2017-04-04
  • 如何使用nexus3搭建npm私有倉庫

    如何使用nexus3搭建npm私有倉庫

    這篇文章主要介紹了如何使用nexus3搭建npm私有倉庫,包括安裝并運(yùn)行私服的相關(guān)知識,本文結(jié)合實(shí)例代碼給大家介紹的非常詳細(xì),感興趣的朋友跟隨小編一起看看吧
    2024-03-03
  • npm國內(nèi)鏡像 安裝失敗的幾種解決方案

    npm國內(nèi)鏡像 安裝失敗的幾種解決方案

    這篇文章主要給大家總結(jié)了npm國內(nèi)鏡像npm安裝失敗的幾種解決方案,文中介紹的非常詳細(xì),對大家具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下來一起看看吧。
    2017-06-06
  • nodejs的路徑問題的解決

    nodejs的路徑問題的解決

    這篇文章主要介紹了nodejs的路徑問題的解決,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2018-06-06
  • nodejs中Express與Koa2對比分析

    nodejs中Express與Koa2對比分析

    提到Node.js開發(fā),不得不提目前炙手可熱的2大框架express和koa。Express誕生已有時日,是一個簡潔而靈活的web開發(fā)框架,使用簡單而功能強(qiáng)大。Koa相對更為年輕,是Express框架原班人馬基于ES6新特性重新開發(fā)的敏捷開發(fā)框架,現(xiàn)在可謂風(fēng)頭正勁,大有趕超Express之勢。
    2018-02-02

最新評論

富宁县| 元朗区| 荔浦县| 本溪| 桐梓县| 忻城县| 准格尔旗| 河北区| 攀枝花市| 安国市| 曲靖市| 宁明县| 民丰县| 澎湖县| 襄城县| 鄂伦春自治旗| 定结县| 大姚县| 天气| 凤台县| 饶平县| 赞皇县| 博野县| 海门市| 荥经县| 阿拉善右旗| 北票市| 临清市| 澄迈县| 张家口市| 常州市| 丹凤县| 水城县| 海宁市| 闽侯县| 乐都县| 吴堡县| 浠水县| 合川市| 五大连池市| 油尖旺区|