preface

Recently I have been using uni-App +uniCloud to complete some of my original technical content infrastructure, such as completing a small program called Big Handsome Ape. In the future, it will also be used to interact with readers and host creative gameplay for some products.

The current version is used to host my original technical content videos or articles. In this article, I will share how to use uniCloud cloud development to realize the receiving and sending of small program customer service messages.

The news of the service

<button open-type='contact'<button>Copy the code

We only need the above line of code, you can realize the artificial customer service in the micro channel small program. It’s really convenient, but what if I want to connect with a robot customer service? This requires us to enable message push and forward the messages from users’ customer service sessions to our own server address.

UniCloud cloud function

Here we use uniCloud to do this. Collect its wool!

First we create a cloud function in uni-app that supports uniCloud and enable urlization for it, that is to allow HTTP requests.

We then copy the path and fill in the URL(server address) shown in the figure below

https://e0b75de1-90c7-4c11-9d12-a8bc84c4d081.bspapp.com/http/customerservice
Copy the code

To receive customer service notifications in the cloud

  1. Filling in the Server Configuration
  2. Verify the validity of the server address
  3. Data interface documents implement business logic and receive messages and events

Filling in the Server Configuration

  • Token (Token)Enter as prompted
  • EncodingAESKey Randomly generated
  • encryptionClear pattern
  • The data formatJSON

Verify the validity of the server address

Now, if WE hit Submit, we’re not going to pass, because we haven’t written any code in the cloud yet. In order to pass, let’s write this paragraph

'use strict';
exports.main = async (event, context) => {
	return event.queryStringParameters.echostr;
};
Copy the code

After modifying the cloud function, remember to upload and deploy the cloud function, and then click the submit button in the server configuration, and the verification is passed. Here we are not actually verifying the signature, although it can pass, there is a risk that the message will be forged. We’ll check the signatures later.

Receive messages and events

Then all customer service messages will be submitted to this interface and we can process them in the cloud function accordingly.

When requesting url-enabled cloud functions through HTTP, get request parameters should be obtained through queryStringParameters, and POST request parameters should be obtained through body.

const receiveMsg = event.body?JSON.parse(event.body):null;
Copy the code

Customer service messages have the following message types (MSgTypes)

  • event
  • text
  • image
  • miniprogrampage

For example, when users send text messages in the customer service message dialogue, they will send a POST request to the server URL. The following information can be obtained from the request body

{
  "ToUserName": "toUser"."FromUserName": "fromUser"."CreateTime": 1482048670."MsgType": "text"."Content": "this is a test"."MsgId": 1234567890123456
}
Copy the code

A reply message

Now we just need to get the content, give it to the robot service to get a reply, and then send a reply message, and the user can receive it. In uniCloud we write this

if(receiveMsg.MsgType=="text") {Receivemsg.text. Content is processed
    // After processing
    const access_token = // To call the interface that responds to user messages, you need to obtain the access_token first
    const res = 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: {FromUserName = FromUserName = FromUserName = FromUserName = FromUserName
                    touser: receiveMsg.FromUserName,
                    msgtype: 'text'.text: {
                      content: 'received',}}}); }Copy the code

Easter eggs!

In the small program to show the nuggets of the article is very troublesome, WebView certainly not, because the business domain name can not operate. Get content yourself htmlParser, nuggets in a lot of long, estimate that their parsing is also very troublesome.

So what can we do with this customer service news?

Denver’s two ports

// Get the list of articles
//https://api.juejin.cn/content_api/v1/article/query_list
// Get article details
//https://api.juejin.cn/content_api/v1/article/detail
Copy the code

My approach is this, first through the article list interface, in the front display of the article list, the article list items are loaded with the customer service message component button

Reply to the Link message

<button open-type="contact" :session-from="'jj_'+item.article_id" style="opacity: 0; width: 100%; height: 100%; position: absolute; z-index: 1;">button</button>
Copy the code

The key here is the SessionFrom field, and when the button is clicked to enter the customer service message session, the server URL receives an Event message

if(receiveMsg.Event=="user_enter_tempsession") {var sessionFrom = receiveMsg.SessionFrom;
    if(sessionFrom.indexOf("jj_") > =0) {// Need to display the article jj_ after the article id
            var articleId = sessionFrom.substr(3);
            
            // Get the details of the nuggets article, which can be used to join the reply message
            const articleDetailRes = await uniCloud.httpclient.request("https://api.juejin.cn/content_api/v1/article/detail", {data: {"article_id":articleId
                    },
                    method:"POST".headers: {"Content-Type":"application/json"
                    },
                    dataType:"json"
            })

            const res = await sendCustomerServiceMessage({
                    touser:receiveMsg.FromUserName,
                    msgtype:"link".link: {
                            "title":articleDetailRes.data.data.article_info.title,
                            "description":articleDetailRes.data.data.article_info.brief_content,
                        "url": "https://juejin.cn/post/"+articleId,
                            "thumb_url": articleDetailRes.data.data.article_info.cover_image } }); }}Copy the code

* Tada! * Done!

Afterword.

Next, I will publish a series of original technology sharing based on uniCloud. Those who are interested can follow this new topic.

In addition: the effect described in the paper you can search for “Da Shuai Lao Ape” or scan the small program code to experience