Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use cloud function SCF+COS to operate Wechat official account free of charge based on Serverless

2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Servers >

Share

Shulou(Shulou.com)06/01 Report--

This article will explain in detail how to use the cloud function SCF+COS to operate Wechat official account free of charge based on Serverless. The content of the article is of high quality, so the editor shares it for you as a reference. I hope you will have some knowledge about it after reading this article.

Yes, you heard right, this time I will take you directly to operate the official account of Wechat.

Effect display

Operation steps

In the previous tutorial "everything is available to Serverless to quickly develop full-stack applications using SCF+COS"

We use Tencent Cloud serverless cloud function SCF and object storage to implement a back-end cloud function, which can return the corresponding result according to our request.

Now we will try to parse Wechat XML messages on the basis of this cloud function to achieve automatic reply to official account messages, keyword reply, text menu and other functions.

Step 1: add related dependencies

In order to quickly complete the development, here we choose python third-party open source library wechatpy to access the Wechat public platform.

As you can see, when the cloud function times out, the Wechat side will display "the server provided by the official account has failed, please try again later"

This is extremely unfriendly to the user experience, so we need a reply after the function times out.

So how long is the timeout for a Wechat official account background message request? The answer is about 5 seconds. We can get this result from the call log of the cloud function backend.

However, it should be noted that for a user's message request, Wechat may redial the request every 1 second or so until it receives the first response from the server. In addition, more than 3 times should not be redialed, and even if the cloud function is successfully called and the data is returned after 5 seconds timeout, the user will no longer receive the message ~

Therefore, it is necessary for us to limit the running time of our cloud function to less than 5 seconds.

Of course, it is incorrect to configure the SCF to time out, because if you do so, the SCF will be stopped by the system after it times out, and a message will not be returned to Wechat. So I imported the timeout\ _ decorator library from the beginning to limit the running time of the main function and use a timeout reply function to cover it.

In addition, it is worth mentioning that in my original business code, there are some crawlers. These crawlers were originally executed sequentially by single thread. Taking into account the timeout problem, I have all changed to multi-thread running here in Wechat Cloud function version to compress the time, so if you also have some small tasks that are time-consuming, you can also try to compress the running time of cloud functions by multi-threading.

Let's move on to the following:

Def wechat (httpMethod, requestParameters, body=''): if httpMethod = = 'GET': signature = requestParameters [' signature'] timestamp = requestParameters ['timestamp'] nonce = requestParameters [' nonce'] echo_str = requestParameters ['echostr'] try: check_signature (WECHAT_TOKEN, signature, timestamp, nonce) except InvalidSignatureException: echo_str =' error' return apiReply (echo_str, txt=True) Content_type= "text/plain") elif httpMethod = = 'POST': msg_signature = requestParameters [' msg_signature'] timestamp = requestParameters ['timestamp'] nonce = requestParameters [' nonce'] try: decrypted_xml = crypto.decrypt_message (body, msg_signature, timestamp Nonce) except (InvalidAppIdException, InvalidSignatureException): return msg = parse_message (decrypted_xml) if msg.type = = 'text': reply = replyMessage (msg) elif msg.type = =' image': reply = create_reply ('ha ◔ '◔? \ nWhat do you want to send me a picture?', msg) elif msg.type = 'voice': reply = create_reply (' ha ◔ '◔? \ nWhat do you want to send me a voice message, msg) else: reply = create_reply ('ha ◔ '◔? \ nI don't know what you sent me ~', msg) reply = reply.render () print ('return result-- >' + str (reply)) # used to print request log reply = crypto.encrypt_message (reply, nonce, timestamp) return apiReply (reply, txt=True) in Tencent Cloud console Content_type= "application/xml") else: msg = parse_message (body) reply = create_reply (msg) reply = reply.render () print ('return result-- >' + str (reply)) # is used to print request log reply = crypto.encrypt_message (reply, nonce, timestamp) return apiReply (reply, txt=True) on Tencent Cloud console Content_type= "application/xml")

The wechat function here is the parsing process of Wechat messages. First of all, determine whether the request method is GET or POST,GET method is only used when the Wechat backend is bound for the first time. In this case, we will get the parameters signature, timestamp, echostr and nonce from the request parameters pushed by Wechat server.

Check_signature (WECHAT_TOKEN, signature, timestamp, nonce)

We only need to generate a signature based on our official account token and compare it with the signature passed from Wechat server to see if it is consistent. If it is consistent, it means that our message encryption and decryption verification is OK, and then return the echostr as is to access the Wechat official account backend.

After connecting to the official account of Wechat, if a user sends us a message in the background, what the cloud function receives is the POST method.

Elif httpMethod = 'POST': msg_signature = requestParameters [' msg_signature'] timestamp = requestParameters ['timestamp'] nonce = requestParameters [' nonce'] try: decrypted_xml = crypto.decrypt_message (body, msg_signature, timestamp, nonce) except (InvalidAppIdException InvalidSignatureException): return msg = parse_message (decrypted_xml) if msg.type = = 'text': reply = replyMessage (msg) elif msg.type =' image': reply = create_reply ('ha ◔ '◔? \ nWhat do you want to send me a picture?', msg) elif msg.type = 'voice': reply = create_reply (' ha ◔ '◔? \ nWhat do you want to send me a voice message, msg) else: reply = create_reply ('ha ◔ '◔? \ nI don't know what you sent me ~', msg) reply = reply.render () print ('return result-- >' + str (reply)) # used to print request log reply = crypto.encrypt_message (reply, nonce, timestamp) return apiReply (reply, txt=True, content_type= "application/xml") in Tencent Cloud console.

Then we initialize the message encryption and decryption instance and decrypt the message sent by the user according to the id,token and aes encryption key obtained at the backend of Wechat official account.

# Wechat official account docks wecaht_id = 'xxxxxxxxxxxxxxx'WECHAT_TOKEN =' xxxxxxxxxxxxxxxxxxx'encoding_aes_key = 'xxxxxxxxxxxxxxxxxxxxxx'crypto = WeChatCrypto (WECHAT_TOKEN, encoding_aes_key, wecaht_id)

Then judge the message type. Different types of messages can be processed on their own.

Msg = parse_message (decrypted_xml) if msg.type = = 'text': reply = replyMessage (msg) elif msg.type = =' image': reply = create_reply ('ha ◔ '◔? Good end, send me the picture why', msg) elif msg.type = 'voice': reply = create_reply (' ha ◔ '◔? Why are you sending me a voice message? msg) else: reply = create_reply ('ha ◔ '◔? I don't know what you sent me ~', msg)

It is important to note that when a user newly follows his official account, we receive another type of message, that is, the last judgment item above, where you can set the welcome words of the new follower.

Reply = create_reply ('ha ◔ '◔? \ nI don't know what you sent me ~', msg) reply = reply.render () print ('return result-- >' + str (reply)) # used to print request log reply = crypto.encrypt_message (reply, nonce, timestamp) return apiReply (reply, txt=True, content_type= "application/xml") in Tencent Cloud console.

Then we use create\ _ reply to quickly create a text reply and render () to generate the text of the xml reply message. Because I set the security mode in the background before, I also need to re-encrypt the xml through the crypto.encrypt\ _ message method before I can return the encrypted reply message to the Wechat server.

I mentioned in the last article that we cannot return messages directly, but need to return data in a specific format (API gateway needs to enable response integration)

# api gateway response integration def apiReply (reply, txt=False, content_type='application/json', code=200): return {"isBase64Encoded": False, "statusCode": code, "headers": {'Content-Type': content_type}, "body": json.dumps (reply, ensure_ascii=False) if not txt else str (reply)} step 4: launch cloud function, add API gateway trigger, enable response integration

Refer to the previous tutorial, "everything is available to Serverless to quickly develop full-stack applications using SCF+COS."

Step 5: modify the configuration of the backend server on Wechat official account

Finally, it's the last step. If you have released your SCF online, go to the official Wechat account to bind your backend server configuration.

Call ~ the job is done

This is the end of sharing about how to operate Wechat official account free of charge by using cloud function SCF+COS based on Serverless. I hope the above content can be of some help and learn more. If you think the article is good, you can share it for more people to see.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Servers

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report