This page looks best with JavaScript enabled

Developing a WeChat Official Account Backend with Tencent Cloud Serverless

 ·  ☕ 3 min read

1. Where Serverless Fits

If cloud computing is meant to make resources flow like tap water — turn it on and use it, turn it off and it stops — then Serverless is one of the future directions of cloud computing. Compared with runtimes such as IaaS and Kubernetes, Serverless offers finer-grained resource control while also providing greater elasticity, letting developers ship features quickly.

Common Serverless scenarios include aggregation services, building lightweight services, and massive pay-as-you-go capacity, which covers most needs. In this article we will use Tencent Cloud’s Serverless service to build a backend for a WeChat Official Account.

2. Creating a Function Service on Tencent Cloud Serverless

Currently Tencent Cloud Serverless mainly offers two types:

  • Function service, which provides function execution
  • Serverless application, which provides a runtime for a complete application

The Serverless application type does not currently support compiled applications, nor the Gin framework; it is mainly PHP and Python. But within the function service, Serverless offers an image type that can run the files inside an image directly. So you can build the application image in advance and then use the function service to create the application service.

2.1 Initializing the Image

  • Create a namespace

Open the link https://console.cloud.tencent.com/tke2/registry/user/space , create a new namespace; here I used shaowenchen

  • Create an image

Click [Create], create an empty image, to be used for creating the function service. You need to note down the image address, ccr.ccs.tencentyun.com/shaowenchen/xxx.

2.2 Creating the Function Service

Open the link https://console.cloud.tencent.com/scf/list-create?rid=1&ns=default&createType=empty

Following the screenshot, proceed through the steps below in order:

  1. Choose custom creation
  2. Choose Web function
  3. Choose image deployment, click Select image, and pick the image created in the previous step
  4. Complete Command, entering the startup command of the application service inside the image: /app

Finally click [Finish] to create the service, but the gateway address it provides, https://service-xxx.gz.apigw.tencentcs.com/release/, will not open, because the image is still empty. Next, we create the project and push the image.

3. Creating the Backend Project on Github

3.1 Initializing the Project with Gin

Use Gin to create a backend project; below is the main.go file.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
package main

import (
	"fmt"
	"net/http"

	"github.com/gin-gonic/gin"
	"github.com/yaotian/gowechat"
	"github.com/yaotian/gowechat/mp/message"
	"github.com/yaotian/gowechat/wxcontext"
)

func main() {
	router := gin.Default()

	router.Any("/mp/", hello)
	router.Any("/", func(c *gin.Context) {
		c.String(http.StatusOK, "OK")
	})
	router.Run(":9000")
}

func hello(c *gin.Context) {

	//配置微信参数
	config := wxcontext.Config{
		AppID:          "从公众号管理页获取",
		AppSecret:      "从公众号管理页获取",
		Token:          "从公众号管理页获取",
		EncodingAESKey: "从公众号管理页获取",
	}
	wc := gowechat.NewWechat(config)

	mp, err := wc.MpMgr()
	if err != nil {
		return
	}

	// 传入request和responseWriter
	msgHandler := mp.GetMsgHandler(c.Request, c.Writer)
	//设置接收消息的处理方法
	msgHandler.SetHandleMessageFunc(func(msg message.MixMessage) *message.Reply {

		//回复消息:演示回复用户发送的消息
		text := message.NewText(msg.Content)
		text.Content = "I get a msg : " + text.Content
		return &message.Reply{message.MsgTypeText, text}
	})

	//处理消息接收以及回复
	err = msgHandler.Handle()
	if err != nil {
		fmt.Println(err)
		return
	}
}

What the code achieves is: it responds to the user’s input xxx by returning the message I get a msg : xxx, and the server-side configuration sits on the /mp/ path.

It is particularly important to note that the port must listen on 9000, otherwise Serverless cannot respond

3.2 Adding a Dockerfile

The Dockerfile content is as follows

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
ARG GO_VERSION=1.16

FROM golang:${GO_VERSION}-alpine AS builder

RUN apk update && apk add alpine-sdk git && rm -rf /var/cache/apk/*

RUN mkdir -p /builder
WORKDIR /builder

COPY go.mod .
COPY go.sum .
RUN go mod download

COPY . .
RUN go build -o ./app ./main.go

FROM alpine:latest

RUN apk update && apk add ca-certificates && rm -rf /var/cache/apk/*

WORKDIR /
COPY --from=builder /builder/app .

EXPOSE 9000

A multi-stage build: the code is compiled into the alpine:latest image, the executable is /app, and the exposed port is 9000.

3.3 Adding a Github Action

For convenience of continuous integration, add the file .github/workflows/build.yaml to the repository, with the following content:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
name: Go

on:
  push:
    branches:
      - "main"

jobs:
  build:
    name: Build
    runs-on: ubuntu-latest
    env:
      GO111MODULE: on
    steps:
      - name: Check out code into the Go module directory
        uses: actions/checkout@v2
      - name: Set up Go 1.16
        uses: actions/setup-go@v2
        with:
          go-version: 1.16
      - name: Login Resigtry
        if: github.event_name == 'push'
        run: |
                    echo ${{ secrets.REGISTRY_PASSWORD }} | docker login ccr.ccs.tencentyun.com -u ${{ secrets.REGISTRY_USERNAME }} --password-stdin
      - name: Build
        run: |
          docker build -t ccr.ccs.tencentyun.com/shaowenchen/xxx -f ./Dockerfile . 
          docker push ccr.ccs.tencentyun.com/shaowenchen/xxx:latest          

After you commit the code, Github Action automatically compiles the code and pushes the image to Tencent Cloud’s image registry.

4. Official Account Configuration and Testing

4.1 Enabling the Server Configuration for the Official Account

As shown in the screenshot, on the WeChat Official Account management page, enable the service configuration. You need to note down the following information, which is used by the backend code for authentication:

  • AppID
  • AppSecret
  • Token
  • EncodingAESKey

The server address here is the function service’s gateway address https://service-xxx.gz.apigw.tencentcs.com/release/ + mp/. Since the service has not been updated yet, verification will not pass; you need to stay on this page and save once the service is ready.

4.2 Configuring the Secrets and Updating the Service

Fill the configuration obtained in the previous step into the configuration of the main.go file:

1
2
3
4
5
6
	config := wxcontext.Config{
		AppID:          "从公众号管理页获取",
		AppSecret:      "从公众号管理页获取",
		Token:          "从公众号管理页获取",
		EncodingAESKey: "从公众号管理页获取",
	}

After committing, wait for Github Action to finish and the image push to succeed.

4.3 Updating the Function Service

Although the service image was updated successfully, the function service will not update itself.

As shown in the screenshot, we open the function management page, select the image version, check latest and submit. After a successful submission, the page will indicate that the image is being pulled and the service is being updated; at this point open the access address, and the page responds with OK.

Now go back and submit the Official Account service configuration, and it will succeed.

4.4 Sending a Message to Test

Finally, test the functionality in the WeChat Official Account:

In the Tencent Cloud function service backend, you can also view the related request logs.

5. Summary

This article took WeChat Official Account backend development as its requirement and gave Tencent Cloud Serverless a try. Since Tencent Cloud Serverless currently has a certain free quota, it is enough for small personal projects and Demo projects. This article mainly covers the following:

  • Created a Tencent Cloud Serverless function service
  • Created a Gin continuous integration project using Github Action
  • Configured the WeChat Official Account server side

In the end we implemented a feature that automatically responds to messages users send to the Official Account.


微信公众号
WRITTEN BY
微信公众号