May 22, 2021 Mini Program Cloud Development Advanced
In the previous section, we've set the value of the button component open-type to contact on the small terminal, and click button to get into the customer service message. However, this customer service message is using the official background, can not be customized in depth, we can use cloud development as a background to customize customer service messages to achieve quick reply, add common answers and other functions.
If you are using traditional development methods, you need to fill in information such as server address (URL), token (Token), and message encryption key (EncodingAESKey), then combine the token, timestamp, nonce parameters for dictionary sorting, stitching, and sha1 encryption, and then compare the encrypted string with signalure to verify that the message is indeed from a WeChat server. Then to receive messages and events processing, can be very cumbersome, and the use of cloud development is much simpler.
Use developer tools to create a new cloud function, such as customer, which, in config.json, sets the following permissions and deploys them to the service side.
{
"permissions": {
"openapi": [
"customerServiceMessage.send",
"customerServiceMessage.getTempMedia",
"customerServiceMessage.setTyping",
"customerServiceMessage.uploadTempMedia"
]
}
}
Then open the cloud development console, click on the settings in the upper right corner, select global settings, turn on the cloud function to receive message push, add message push configuration. For learning convenience, we push all message types into the customer cloud function.
There are four types of messages above, but the legal values of the msgtype property of the customer service servicemesage.send that sends customer service messages are text, image, link (image link message), miniprogrampage, which means that we can also send a text link message.
Use the developer tool to create a new page, such as customer, and then enter the following button in customer.wxml.
<button open-type="contact" >进入客服</button>
When the user enters the customer service message through button, replying to the message in the chat interface can trigger the set-up customer cloud function, such as the following example is when the user sends a message (including emoticons) to the customer service message session interface, the cloud function will call cu The stomerServiceMessage.send interface replies to two text messages to the user (you can reply to multiple messages at a time), the content is waiting for you for many hours and welcome to the cloud
欢迎关注云开发技术训练营
training camp, a cloud function can also call the interface multiple times:
等候您多时啦
const cloud = require('wx-server-sdk')
cloud.init({
env: cloud.DYNAMIC_CURRENT_ENV,
})
exports.main = async (event, context) => {
const wxContext = cloud.getWXContext()
try {
const result = await cloud.openapi.customerServiceMessage.send({
touser: wxContext.OPENID,
msgtype: 'text',
text: {
content: '等候您多时啦'
}
})
const result2 = await cloud.openapi.customerServiceMessage.send({
touser: wxContext.OPENID,
msgtype: 'text',
text: {
content: '欢迎关注云开发技术训练营'
}
})
return event
} catch (err) {
console.log(err)
return err
}
}
When sending a text message, we support inserting a text link to the skip program, for example, we change the text message above to the following code:
content: '欢迎浏览<a href="http://www.qq.com" rel="external nofollow" target="_blank" data-miniprogram-appid="你的appid" data-miniprogram-path="pages/index/index">点击跳小程序</a>'
We can also reply to the user link, we can change the customer cloud function to the following code, when the user to WeChat chat dialogue interface to send a message, it will reply to the user a link, this link can be an external link Oh.
const cloud = require('wx-server-sdk')
cloud.init({
env: cloud.DYNAMIC_CURRENT_ENV,
})
exports.main = async (event, context) => {
const wxContext = cloud.getWXContext()
try {
const result = await cloud.openapi.customerServiceMessage.send({
touser: wxContext.OPENID,
msgtype: 'link',
link: {
title: '快来加入云开发技术训练营',
description: '零基础也能在10天内学会开发一个小程序',
url: 'https://cloud.tencent.com/',
thumbUrl: 'https://tcb-1251009918.cos.ap-guangzhou.myqcloud.com/love.png'
}
})
return event
} catch (err) {
console.log(err)
return err
}
}
After the above cloud function is deployed, when the user enters content into the chat session of customer service message, no matter what content the user sends, the cloud function will return to the user the same content, which is a little too rigid, customer service message can reply to the user's different content according to the keywords sent by the user? To do this we need to be able to get what the user is sending.
We can note that as you can see in the cloud function log of the cloud development console, the Content property in the object returned by the customer cloud function records what the user sends to the chat session:
{ "Content":"请问怎么加入云开发训练营",
"CreateTime":1582877109,
"FromUserName":"oUL-mu...XbuEDsn8",
"MsgId":22661351901594052,
"MsgType":"text",
"ToUserName":"gh_b2bbe22535e4",
"userInfo":{"appId":"wxda99ae4531b57046","openId":"oUL-m5FuRmuVmxvbYOGuXbuEDsn8"}}
Since Content is a string, the keyword can be very precise, such as "training camp" or "cloud development boot camp", or very vague "how to join the cloud development training camp", we only need to match the string correctly, for example, when the user as long as the content sent contains "training camp", will receive a link:
const cloud = require('wx-server-sdk')
cloud.init({
env: cloud.DYNAMIC_CURRENT_ENV,
})
exports.main = async (event, context) => {
const wxContext = cloud.getWXContext()
const keyword = event.Content
try {
if(keyword.search(/训练营/i)!=-1){
const result = await cloud.openapi.customerServiceMessage.send({
touser: wxContext.OPENID,
msgtype: 'link',
link: {
title: '快来加入云开发技术训练营',
description: '零基础也能在10天内学会开发一个小程序',
url: 'https://cloud.tencent.com/',
thumbUrl: 'https://tcb-1251009918.cos.ap-guangzhou.myqcloud.com/love.png'
}
})
}
return event
} catch (err) {
console.log(err)
return err
}
}
In the previous case, we all used
touser: wxContext.OPENID,
To trigger the event, we can change the customer.wxml button to the following code, where the session-from is the user enters the customer service message session interface from the button, the developer will receive an event push with this parameter, which can be used to distinguish the source of the user's entry into the customer service session.
<button open-type="contact" bindcontact="onCustomerServiceButtonClick" session-from="文章详情的客服按钮">进入客服</button>
Since we turn on the event type of customer service message, the value of the event type is user_enter_tempsession, and when the user clicks button to enter customer service, the cloud function is triggered, which can be triggered without the user sending a message, and we return the object.
const cloud = require('wx-server-sdk')
cloud.init({
env: cloud.DYNAMIC_CURRENT_ENV,
})
exports.main = async (event, context) => {
const wxContext = cloud.getWXContext()
try {
const result = await cloud.openapi.customerServiceMessage.send({
touser: wxContext.OPENID,
msgtype: 'text',
text: {
content: '欢迎来到等候您多时啦'
}
})
return event
} catch (err) {
console.log(err)
return err
}
}
We can go to the cloud development console to see the returned objects
{ "CreateTime":1582876587,
"Event":"user_enter_tempsession",
"FromUserName":"oUL-m5F...8",
"MsgType":"event",
"SessionFrom":"文章详情的客服按钮",
"ToUserName":"gh_b2bbe22535e4",
"userInfo":{"appId":"wxda9...57046",
"openId":"oUL-m5FuRmuVmx...sn8"}}
On the cloud function side, we are able to pass the event. SessionFrom to get the user exactly click which button to enter the customer service dialogue, can also be based on the user into the customer service session from different sources, to push the user different types, for example, we can give the value of session-from set to "training camp", when the user enters the customer service message session can push the relevant information to the user.
Another point is that bindcontact binds an event handler to the customer service button, here is the onCustomerServiceButtonClick, through which we can do a lot of things on the small terminal, such as recording how many times the user clicked a button with a tag (such as the value set to "training camp") and so on.
In order to reply to the user in the customer service message image, the source of this picture can only be from WeChat server, we need to use customerServiceMessage.uploadTempMedia, upload the picture file to WeChat server, get to mediaId (somewhat similar to WeChat server fileID), before we can use in customer service messages.
Enter the following code in the index .js of the customer cloud function and deploy it online, and we'll get the mediaId using cloud.openapi.customerServiceMessage.send to the user:
const cloud = require('wx-server-sdk')
cloud.init({
env: cloud.DYNAMIC_CURRENT_ENV,
})
exports.main = async (event, context) => {
const wxContext = cloud.getWXContext()
try {
//我们通常会将云存储的图片作为客服消息媒体文件的素材
const fileID = 'cloud://xly-xrlur.786c-xly-xrlur-1300446086/1572315793628-366.png'
//uploadTempMedia的图片类型为Buffer,而从存储下载的图片格式也是Buffer
const res = await cloud.downloadFile({
fileID: fileID,
})
const Buffer = res.fileContent
const result = await cloud.openapi.customerServiceMessage.uploadTempMedia({
type: 'image',
media: {
contentType: 'image/png',
value: Buffer
}
})
console.log(result.mediaId)
const mediaId = result.mediaId
const wxContext = cloud.getWXContext()
const result2 = await cloud.openapi.customerServiceMessage.send({
touser: wxContext.OPENID,
msgtype: 'image',
image: {
mediaId: mediaId
}
})
return event
} catch (err) {
console.log(err)
return err
}
}
Customer service messages can also reply to the user with a small program message card, as well as the customer service's current input status to the user (using the customerServiceMessage.setTyping interface).