WeChat background server development

Be about to go off work, soldier long open mobile phone, see pop up of some WeChat chat robot advertisement then point go in, then have the following story…

Recently the soldier commander saw WeChat when the sudden whim to play some WeChat robot, can be like intelligent voice assistant once and oneself chat

The soldier commander is thinking, this robot is how to do, we are to do server development, we use GO language to achieve a quick play for their own, to achieve a customized chat robot

Fat Sir Heard the soldier commander soliloquize of unknown so, then walked forward and said, I began to play chat, not to canyon swim?

Last time I took you, I intended to take you to become Winer, but I did not expect that every hand is loser. I plan to stop my hand recently, control my emotions, and find a robot to comfort my heart

You mean WeChat chatbot? They are all the same

Can you get a custom one then? Get my mood right. I’ll take you to a big fight

~~ (chuckles), young man, fortunately I left a hand, I first tell you about WeChat background server how to initially develop a simple you ask me to answer function, teach people to fish, not as good as teach people to fish

The development of a WeChat background server as a passive response robot is roughly divided into the following steps:

  • Open the public number, register WeChat public number development platform, here can be registeredSubscribe to the no.I will tell you the details later
  • Configure permissions, configure WeChat background developer permissions
  • The process is introduced
  • Connect to WeChat background
  • Function implementation
  • The soldier commander took the fat Sir To fly

Open an official account

Register WeChat public number development platform, here can be registered subscription number, according to the prompts for registration input information, I believe you will see

Registered address: https://mp.weixin.qq.com/cgi-bin/registermidpage?action=index&lang=zh_CN&token=

I’ve put together a table to explain the difference between a subscription number and a server number, so you can get a sense of the difference first, and you can figure it out later

Subscribe to the no. Service no.
use The main purpose for everyone to disseminate advice; Like newspapers, magazines, personal output Preferred corporate or organizational interactions, such as banks, shopping malls, restaurants, etc. A self-service service number used by a business
Mass number It can be sent once a day; All the push messages of the subscription number will be integrated into the column of the subscription number Send four mass messages a month
Show the location All included in the subscription number in the information bar Display in friends’ message list; Following a service number is the equivalent of adding a friend
WeChat pay The payment function cannot be opened WeChat payment function can be opened after authentication
Custom menu Relatively simple Relatively advanced, WeChat has an interface, you can develop their own

Configure permissions

Configure WeChat background developer permissions

  • Enter the official account management page, pull down the left side, enter the basic configuration

  1. URL: Fill in your own external serverURLIf you can’t buy a cloud server, it’s still cheap to buy a cloud server
  2. Token: customToken“Is used to make a signature, which is very important and needs to be kept secret
  3. EncodingAESKey: Random generation
  4. Message encryption and decryption: For the sake of illustration, we use plaintext mode here
  • WeChat public number background interface authority

Ordinary users only need to receive messages and auto-reply message permissions

The process is introduced

Developing an introduction to the passive response message process, in a nutshell, could look something like this

Function realization essential knowledge points

  • The HTTP servicecommunicate
  • Token mechanism
  • WeChat background developmentxmlData serialization of

The HTTP service

To do the above function of passive reply message, here only need the back-end server to implement GET method and POST method

  • The get method

    It is mainly used for when we set token in WeChat background, WeChat background will send GET request to our server to judge whether our service has correct data

  • Post method

    It is mainly used for fans to send messages to our WeChat background server in the way of POST

Token mechanism

parameter describe
signature The WeChat signature combines the token parameter filled by the developer with the timestamp parameter and the nonce parameter in the request.
timestamp The time stamp
nonce The random number
echostr Random string

The developer validates the request by verifying Signature (check below). If it is confirmed that the GET request came from the WeChat server, please return the echostr parameter content as before, then the access will take effect and become successful for the developer; otherwise, the access will fail. The encryption/verification process is as follows:

1) Sort token, timestamp, and nonce in lexicographical order

2) The three parameter strings are concatenated into one string for SHA1 encryption

3) The encrypted string obtained by the developer can be compared with Signature to indicate that the request originated from WeChat

Token algorithm flowchart

Verification method (GET)

  • 1. The server side obtains the list composed of Token, Nonce, and Timestamp
  • 2. Put your list in lexicographical order
  • 3. Summarize the ordered elements
  • 4. Synchronize Signature
  • 5. Responseechostr

Reference WeChat backstage development documentation link: https://developers.weixin.qq.com/doc/offiaccount/Getting_Started/Getting_Started_Guide.html

XML data parsing

Sergeant, I don’t know if you’ve ever serialized data with XML, but I’m sure you’re asking, why XML, not JSON, not ProtoBuf

Let me give you a brief introduction to XML:

XML is an Extensible Markup Language (XML), in which markup refers to the symbols of information that can be understood by computers. Computers can deal with resources containing all kinds of information through markup, and we can carry out markup through a general markup language

In human terms, XML is one of the ways to serialize data, and WeChat has decided to serialize data in this way, so we need to develop it, so we also need to follow the rules of WeChat

For example, the text message type behind WeChat request has the following XML format

Text message, WeChat public platform request WeChat background server will take fields: fromuserName, touserName, createTime, msgType, Content, MsgId

The WeChat background server we developed needs to respond according to the following data format: XML with the following fields touserName, fromuserName, createTime, msgType, and Content

To realize the WeChat background server passive reply message service, need to use the above mentioned three points, HTTP service, token mechanism, XML parsing, remember, I want to start code

The specific implementation

main.go

  • Start the HTTP server and start listening on port 80
Package the main import (" FMT "" github.com/wonderivan/logger" ".net/HTTP "" time") const (port = 80 / / backend server port number 80, Port 80 token = "XXXXXXX") // You need to modify the token by yourself, Size to accommodate their public token func main () {logger. SetLogger (". / log. Json ") logger. The Info (" -- -- -- -- -- -- -- -- -- -- -- -- start main -- -- -- -- -- -- -- -- -- -- -- -- ") server := http.Server{Addr: fmt.sprintf (":%d", port); // Set the listener address, IP :port Handler: &HttpHandler {}, // which handler to use to handle readTimeout: 5 * time.Second, // readTimeout: 5 * time.Second 5 * time.Second, MaxHeaderBytes: 0, } logger.Info(fmt.Sprintf("Listen: %d", port)) logger.Fatal(server.ListenAndServe()) }

route.go

  • Routing function, the specific implementation of GET and POST methods
  • Define the implementation of the Handler and ServeHttp interfaces
package main import ( "fmt" "github.com/wonderivan/logger" "io" "net/http" "regexp" "time" "wechat/wx" ) type WebController struct { Function func(http.ResponseWriter, * http.request) Method string Pattern string} var mux []WebController // ^ match input string start position func init() {mux = append(mux, WebController{post, "POST", "^/"}) mux = append(mux, WebController{get, "GET", "^/"})} type HttpHandler struct{} // HttpHandler implements the ServeHttp interface. Func (* HttpHandler) serveHttp (w http.responseWriter, r * http.request) {t := time.now () for _, WebController := range mux {// Route traversal // Match request R.U.L.path-> WebController.pattern if m, _ := regexp.MatchString(webController.Pattern, r.URL.Path); M {// Match URL logger.info (" webcontroller.pattern == ", webcontroller.pattern) logger.info (" R.U.L.path == ", Path) if R.Method == WebController.method {// match Method logger.info (" WebController.method == ", webController.Method) webController.Function(w, R) / / call the corresponding handler d: = time. Now (). The Sub (t) : l = FMT. Sprintf (" [ACCESS] | - 10 s and 40 s | | % % % - 16 s ", r.M ethod, r.U RL. The Path, d.String()) logger.Info(l) return } } } d := time.Now().Sub(t) l := fmt.Sprintf("[ACCESS] | % -10s | % -40s | % -16s", r.Method, r.URL.Path, d.String()) logger.Info(l) io.WriteString(w, "") return} func get(w http.responseWriter, r * http.request) {client, err := wx. newClient (r, w, r) {return return} func get(w http.responseWriter, r * http.request) {client, err := wx. newClient (r, w, token) if err ! = nil {logger.info (err) w.riteHeader (403) return} if Len (client.query.echostr) > 0 {logger.info ("Echostr == ", []byte(client.query.echostr) w.rite ([]byte(client.query.echostr)) // return Echostr return} w.riteHeader (403) return} // The WeChat platform comes in and handles the message, Func post(w http.responseWriter, r * http.request) {client, err := wx. newClient (r, w, token) if err! = nil {logger.info (err) w.riteHeader (403) return} // The signature has been checked by Client.Run() return}

Specific code implementation also has 1 definition structure file and core implementation file:

  • structs.go

    Definition of structure corresponding to XML serialization message, including basic message field, FromUserName, ToUserName, MsgType, CreateTime, as well as text message, picture message, recording message, music message, geo-location message, video message and so on which fields are needed, You can refer to the rules given in the background of WeChat

  • wx.go

    The token + random number + timestamp is arranged in lexicographical order and encrypted with SHA1 to generate signature

    The concrete implementation of newClient

    Text message, picture message processing and passive reply function

If you are interested in the above two core files, you can add my WeChat if you have an idea and expect your own realization

Of course, there are still many functions involved in WeChat background development, what I have shared with you today is just the tip of the iceberg, and the scenery along the way still needs you to feel step by step. You can practice it in the WeChat development document, as shown in the following picture, and you can communicate more if you are interested.

Technology is open, we share technology, mentality should be open, we embrace change, you are willing to continue to explore, you will get what you want.

That’s all for this episode. Stick to originality and practice your own ideas. See you next time

Author: Nezha