Recently follow the big handsome make small program opened after the main flow, thinking of giving the public drainage, will be able to pay attention to the public from the small program. But the mechanism of the small program we understand, can not directly jump to the public number oh, that can only find customer service to reply to a TWO-DIMENSIONAL code picture!!
Configure your
Unicloud configuration
- Add cloud functions by right clicking in the cloud functions folder under project uniCloud
- Create a new cloud function in the pop-up layer called Contact (whatever name you want)
- Once created, right-click on the Contact cloud function folder to upload the cloud function
- The cloud function code is as follows:
- Temporarily do not write the cloud function code, first go to unicloud background to configure the URL data required by the small program
- After finding the list of cloud functions-functions in the right directory, find
contact
Cloud function, click the details button
- find
Cloud function URl-based module
, click Edit
- Enter in the input box
/contact
Note: the name must start with a /
- After clicking OK, click the copy PATH button next to PATH
At this point, uniCloud is configured, and the applets can be configured
Applets configuration
- Log in your mini program account on wechat public platform
- On the left menu bar, find Development-Development Management
- After entering Development Management, switch TAB to Development Settings
- Find the news feed and click Enable
- After jumping to the message push configuration page, configure the message push according to the picture
If you click submit, you will be prompted that the Token verification fails. Please check and confirm, do not panic, it is just not written in the cloud function. This time can go to write the cloud function code ~~
Let’s start writing the cloud function
If the source requirement is not high, or do not consider security, can be directly in the cloud function returns event. QueryStringParameters. Echostr
The cloud function code is as follows:
'use strict'; Exports. main = async (event, context) => {//event for the client upload argument console.log('event: ', the event) / / return data to the client return event. QueryStringParameters. Echostr; };Copy the code
It’s also easy to verify security
1. Sort the token, timestamp, and nonce parameters lexicographically
2. Concatenate the three parameter strings into a string for SHA1 encryption
3. The encrypted string obtained by the developer can be compared with signature to indicate that the request is from wechat
The cloud function code is as follows:
'use strict'; //npm install sha1 const sha1 = require("sha1"); const token = "123qweASD"; function verifyMSGSender(params){ const mysignature = sha1([token,params.timestamp,params.nonce].sort().join("")); console.log(mysignature===params.signature?" ":" verification failed "); if(mysignature===params.signature)return true; else return false; } exports.main = async (event, context) => {//event is the client upload parameter if(! VerifyMSGSender (event. QueryStringParameters)) return "source calibration failure"; / / check passed, this return echostr line of code commented out else return event. QueryStringParameters. Echostr; // Return data to the client; };Copy the code
Note: The token must be the same as the token on the message configuration page
Now you can go to message configuration and click the Save button!!
After the configuration is complete, it looks like this
After verification, the echostr code in the code can be commented out
/ / check passed, this return echostr line of code commented out else return event. QueryStringParameters. Echostr;Copy the code
After sending a message to customer service, you can see the return result in the cloud function log
But the result is a string, and we need to convert the string to JSON
Const receiveMsg = json.parse (event.body);Copy the code
Packet return format
Depending on the message sent by the user, the following formats are available
{// Text message return packet "ToUserName": "toUser", "FromUserName": "fromUser",// customer service message originator openID "CreateTime": 1482048670, "MsgType": "Text ",// The message type "Content": "this is a test", "MsgId": 1234567890123456}Copy the code
{"ToUserName": "toUser", "FromUserName": "fromUser", "openID "CreateTime": 1482048670, "MsgType": "Image ",// this message type "PicUrl": "this is a url", "MediaId": "media_id",// wechat media resource id" MsgId": 1234567890123456}Copy the code
<button size="mini" type="primary" :plain="true" open-type="contact" :session-from="" </button> </button> </button> </button> "ToUser ", "FromUserName": "fromUser", "MsgType": "Miniprogrampage ",// this message type "MsgId": In 1234567890123456, "Title":" Title",// Applets card Title" AppId":" AppId",// Applets card jump page "ThumbUrl":"",// Applets card thumbnail "ThumbMediaId":"" }Copy the code
{// Customer service message enter session event "ToUserName": "toUser", "FromUserName": "fromUser",// customer service message initiator openID "CreateTime": 1482048670, "MsgType": "Event",// The message type "event" : "user_enter_tempSession ", "SessionFrom": "SessionFrom" // the session-from attribute set by the developer on the customer service session button}Copy the code
Reply to customer service message
Wechat customer service message document
First getaccess_token
Wechat obtains the access_token file
Note: APPID and APPSECRET are obtained from wechat Public Platform development management
const tokenUrl = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=' + APPID + '&secret=' + APPSECRET; / / uniCloud httpclient initiating const res1 = await uniCloud. Httpclient. Request (tokenUrl, {method: 'GET', dataType:"json" }); // Return data to client const access_token = res1.data.access_token;Copy the code
Start replying to messages
const access_token = res1.data.access_token const res2 = await uniCloud.httpclient.request("https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token="+access_token,{ method:"POST", headers:{ "Content-Type":"application/json" }, dataType:"json", Data :{touser:touser,// OpenID msgType :"text",// the type of this message text:{content:" text",}}});Copy the code
There are many kinds of reply messages, text text message, IMG picture message, link link message, miniprogramPage small program card message. Reply to picture messages (this is not covered in most of the tutorial, you can search for others on the nuggets)
Before the automatic reply of picture message, according to the description of wechat document, the picture needs to be uploaded to the temporary file server now, and the validity period of the picture is only three days
Uploading picture information
Wechat customer service uploads temporary picture documents
As you can see in the request parameters, we need to pass onemedia
And isFormData
Type, but we won’t add an input box to the applet to upload images, so we’ll use nodeJS ‘form-data module
Note: In wechat applet, you cannot write new FormData() directly in the code, you need to install the module by yourself
- Firstly, upload the required image to unicloud cloud storage and obtain the corresponding URL
Const img_url = 'https:// cloud storage path.jpg '
- Convert image links to buffers
const url = await uniCloud.httpclient.request(img_url)
let buff = new Buffer(url.data);
Copy the code
- Pass the buff to formData
// NPM install form-data let form = new FormData() // create FormData Form.append ('media', buff, {filename: '${date.now ()}.jpg ', contentType: 'image/jpeg' })Copy the code
- request
Upload temporary customer service files
Interface, upload formData information, get tomedia_id
// Request wechat server API to upload formData information, Get media_id const imgRes = await uniCloud.httpclient.request("https://api.weixin.qq.com/cgi-bin/media/upload?access_token=" + access_token + '&type=image', { method: "POST", headers: form.getHeaders(), dataType: 'json', content: form.getBuffer() }); return imgRes.data.media_idCopy the code
- Judge the message sent by the user and reply to the picture
Note: WHAT I judge here is that after the user sends 2, the reply message
If (receivemsg. Content === '2'){// Call the media_id method // since the method is a Promise, Let media_id = await uploadTempImg(URL, Access_token) if(media_id){// Send message const res2 = await uniCloud.httpclient.request("https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=" + access_token, { method: "POST", headers: { "Content-Type": "application/json" }, dataType: "json", data: { touser: Receivemsg. FromUserName, // OpenID msgtype: "image", // Message type image: {media_id: media_id}}}); }}Copy the code
There’s the little robot that responds automatically
The complete code
'use strict'; NPM install sha1 NPM install sha1 NPM install sha1 NPM install sha1 Const sha1 = require("sha1"); const FormData = require("form-data"); const token = "123qweASD"; const db = uniCloud.database(); function verifyMSGSender(params) { const mysignature = sha1([token, params.timestamp, params.nonce].sort().join("")); console.log(mysignature === params.signature ? "Verification passed" : "verification failed "); if (mysignature === params.signature) return true; else return false; } async function uploadTempImg(img_url, Access_token) {/ / will now image links to buffer const url = await uniCloud. Httpclient. Request (img_url) let buff = new buffer (url. Data); // NPM install form-data let form = new FormData() // create FormData Form.append ('media', buff, {filename: '${date.now ()}.jpg ', contentType: 'image/jpeg'}) // Request wechat server API to upload formData information, Get media_id const imgRes = await uniCloud. Httpclient. Request ( "https://api.weixin.qq.com/cgi-bin/media/upload?access_token=" + access_token + '&type=image', { method: "POST", headers: form.getHeaders(), dataType: 'json', content: form.getBuffer() }); return imgRes.data.media_id } exports.main = async (event, Context) => {// get appID and appSecret from config let appID = await db.collection('wx_config') where({'key': 'wxId' }).get() let appSecret = await db.collection('wx_config').where({ 'key': 'wxSecret' }).get() const APPID = appId.data[0].val const APPSECRET = appSecret.data[0].val const tokenUrl = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=' + APPID + '&secret=' + APPSECRET; / / uniCloud httpclient initiating const res1 = await uniCloud. Httpclient. Request (tokenUrl, {method: 'GET', dataType:"json" }); // Return data to client const access_token = res1.data.access_token; //event is the parameter uploaded by the client if (! VerifyMSGSender (event. QueryStringParameters)) return "source calibration failure"; / / check passed, this return echostr line of code commented out / / else return event. QueryStringParameters. Echostr; Const receiveMsg = json.parse (event.body); const url = 'https://vkceyugu.cdn.bspapp.com/VKCEYUGU-a8a16cef-f2b9-4644-b216-3b95bcb12602/eed2e97a-be28-4e6d-beb3-ca338d195858.jpg' If (receivemsg. Content === '2'){// Call the media_id method // since the method is a Promise, Let media_id = await uploadTempImg(URL, Access_token) if (media_id) {/ / send a message const res2 = await uniCloud. Httpclient. Request ( "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=" + access_token, { method: "POST", headers: { "Content-Type": "application/json" }, dataType: "json", data: { touser: Receivemsg. FromUserName, // OpenID msgtype: "image", // Message type image: {media_id: media_id}}}); }} // Return data to the client; };Copy the code