The small volume “Uniapp from the Beginning to the advanced” – from the basic to the actual combat, explains in detail all aspects of cross-platform application development, including Uniapp development common knowledge points, basic API, front-end interaction, component packaging, back-end Nodejs development, front and back end joint tuning and tuning deployment, is a very comprehensive comprehensive course.

The early spring of this year is unusual, the virus is rampant, affecting all walks of life, hope to pass as soon as possible, everything will return to normal.

The introduction

Recent company to upgrade the program that I was going to some of the front end is operating and the relatively independent function (backend to change), try to be transferred to the cloud development implementation step by step, to check the information push service, I “reference” the official document, thank you for the official promotion how I want to start work ability, so this article, will probably be divided into the following content:

  • What is cloud development
  • Cloud function customer service message push
  • Realize the function
  • The resources

What is cloud development

The word Serverless has been very popular in recent years, click here if you don’t know. My understanding of Serverless is a kind of architecture, cloud development belongs to one of its implementation.

Cloud development provides developers with complete native cloud support and wechat service support, weakening the concept of back-end and operation and maintenance. Without building a server and accessing SDK, the API provided by the platform can be used for core business development, and fast online and iteration can be realized.

Cloud development provides several basic capabilities to support:

Ability to role instructions
Cloud function No need to build your own server The code running in the cloud, wechat private protocol natural authentication, developers only need to write their own business logic code
The database No need to build your own database A JSON database that can be operated on the front end of an applet and read and write in cloud functions
Cloud storage No need to build your own storage and CDN Upload/download cloud files directly in front of the small program, and manage them visually in the cloud development console
Cloud call Native wechat service integration Cloud function-based authentication The ability to use applets to open interfaces, including server-side invocation and access to open data

On the left side of the developer tool toolbar, click the cloud Development button to open the cloud console, open the cloud development and create the cloud environment as prompted. Two environments can be created under the default quota. Each environment is isolated from each other, and each environment contains independent resources such as database instances, storage space, and cloud function configuration. Each environment is identified by a unique environment ID. The environment created initially automatically becomes the default environment.

Above is the official introduction, but make sure you have cloud development enabled.

Cloud function customer service message push

Small programs that have opened cloud development can use cloud functions to receive message push. Currently, only customer service message push is supported.

Cloud calls use two apis:

  • customerServiceMessage.send
  • customerServiceMessage.uploadTempMedia

customerServiceMessage.send

There are four types of messages that can be pushed

attribute instructions
text Text message, msgtype=”text”
image Image message, msgtype=”image”
link Msgtype =”link”
miniprogrampage Small program card, msgType =” miniprogramPage”

This time, only text and image are used. Link and miniprogrampage are not used temporarily. Image image types have a request: incoming media_id parameters, media to send picture ID, by new material interface (customerServiceMessage. UploadTempMedia) upload the image files.

customerServiceMessage.uploadTempMedia

Upload media files to wechat server. Currently, only images are supported. It is used to send customer service messages or passively reply to user messages, as described below.

Realize the function

Let’s start with our needs:

Users click the popup guide picture, open the customer service message window, and actively push a welcome message with prompt operation. When the user enters ‘1’, the TWO-DIMENSIONAL code picture will be pushed.

At first, we thought it would be difficult to integrate because our company’s small program has existed for a long time and its structure is not easy to adjust. However, we did not expect that simple configuration would be necessary. We added a folder cloudfunctions in the root directory to store cloudfunctions, and the project.config.json file in the root directory. Add the cloudfunctionRoot field to specify cloudfunctions as the local root directory of cloudfunctions.

{
   "cloudfunctionRoot": "cloudfunctions/",}Copy the code

After the designation is completed, the icon of the root directory of the cloud function will become “cloud directory icon”. The first level directory (cloud function directory) under the root directory of the cloud function is the same as the name of the cloud function. If the corresponding online environment has the cloud function, it will be marked with a special “cloud icon” :

Next, right-click on the root directory of the cloud function and choose Create a new Node.js cloud function. We name the cloud function kefumsg, create izumo function directory and entry index.js file locally, and create the corresponding cloud function in the online environment.

A directory represents a function of cloud, are generally of two files, index, js, package. Json, manually add config. Here the json file, used to configure use customerServiceMessage. Send permissions:

{
    "permissions": {
        "openapi": [
            "customerServiceMessage.send"."customerServiceMessage.uploadTempMedia"]}}Copy the code

Here is the directory for the Kefumsg cloud functions:

Node_modules is generated locally by debugging, as I’ll explain later. First upload qr code picture to cloud storage, wechat development tool open cloud development -> Storage -> upload file:

The File ID here will be used next.

Writing cloud functions

Open the index.js file in the directory of the kefumsg cloud function and replace it with the following code:

const cloud = require('wx-server-sdk') cloud.init() <! Download cloud storage image -->let downLoad = async(event, context) => {
    const res = await cloud.downloadFile({
        fileID: 'cloud://kefumsg-n350x.6769-kefumsg-n350x-1302104716/1588064201743.png'.// The File ID of the image
    })
    const buffer = res.fileContent
    console.log(buffer)
    returnbuffer } <! Upload media file to wechat server -->let upload = async(Buffer) => {
    return await cloud.openapi.customerServiceMessage.uploadTempMedia({
        type: 'image'.media: {
            contentType: 'image/png'.value: Buffer
        }
    })
}


exports.main = async(event, context) => {
    const wxContext = cloud.getWXContext()

    if (event.Content == '1') {
        let Buffer = await downLoad()
        let meida = await upload(Buffer)
            // console.log(meida)
        try{<! Send image type message -->const result = await cloud.openapi.customerServiceMessage.send({
                touser: wxContext.OPENID,
                "msgtype": "image"."image": {
                    "media_id": meida.mediaId
                }
            })
            return result
        } catch (err) {
            return err
        }
    } else if (event.Title == 'Custom title') { 
    // Triggered according to the custom card title
        let Buffer = await downLoad()
        let meida = await upload(Buffer)
        try {
            const result = await cloud.openapi.customerServiceMessage.send({
                touser: wxContext.OPENID,
                "msgtype": "image"."image": {
                    "media_id": meida.mediaId
                }
            })
            return result
        } catch (err) {
            return err
        }
    } else {
        try {
            await cloud.openapi.customerServiceMessage.send({
                touser: wxContext.OPENID,
                msgtype: 'text'.text: {
                    content: Hello, glad to be of service. Reply 1, check the qr code of group entry '}});return 'success'
        } catch (err) {
            return err
        }
    }
}

Copy the code

Upload () upload() upload() upload() upload() upload() upload() upload()

  1. First two-dimensional code pictures in the cloud storage, first throughcloud.downloadFileDownload and find the correspondingbufferValue,
  2. thenopenapi.customerServiceMessage.uploadTempMediathemediaType only acceptedBuffer, the upload is successfulmediaIdLogo (the logo will be available within 3 days after the media file is uploaded),
  3. To pass toopenapi.customerServiceMessage.sendtheimagethemedia_idProperties,

This will successfully return the image type message. Let me know if any of you have a good idea.

Upload and deploy

After the cloud function is written, right-click in the directory of the kefumsg cloud function and select Upload and Deploy: All files, push to the cloud with one key and automatically return the message of successful deployment.

Next, go to the Developer Cloud Development Console and choose Settings -> Global Settings -> Add Notification Push to add a configuration, here only select text type:

Sure to save

According to our requirements, users click on the customer service and will automatically push a message, which has been tested and configuredtextIf multiple messages are configured, push can be triggered only when users actively send messages.

Calling the cloud function

First, in the applet app.js header add:

wx.cloud.init()
Copy the code

Open the customer service dialog box in page.wxml:

<! -- Send card, title is important, as trigger key -->
<button open-type="contact" bindcontact="handleContact" show-message-card="true" send-message-title="Custom title" send-message-img="https://s3.pstatp.com/toutiao/static/img/logo.271e845.png"/>
Copy the code

The corresponding.js add:

wx.cloud.callFunction({
    name: 'kefumsg'  // The name corresponds to the cloud function name
}).then(res= > {
    console.log(res)
}).catch(err= > {
    console.error(err)
})
Copy the code

Open the wechat development tool preview scan code, only to see the effect of real machine debugging, if no error, click the button, it will pop up “Hello, happy to serve you. Reply 1, check the qr code of group entry “, reply 1, the qr code window will pop up

Local debugging of cloud functions

Every time the development is finished to submit deployment, once the network speed is slow I hate it. At this point, you can take advantage of the local debugging capabilities of cloud functions. Right-click in the directory of the kefumsg cloud function and select Enable local debugging of the cloud function. Since the NPM package wX-server-sdk is used (the running environment of the cloud function is Node.js, so ensure that node.js is installed when installing dependencies locally), You need to run the terminal command in the directory to install the dependency package YARN Install. Otherwise, an error message is displayed, and the following window is displayed:

Check enable local debugging and click the call button to see the execution:

If there is an error, it can be clear at a glance. After the modification test is completed, it can be pushed to the cloud.

45047 Error code, which means that wechat customer service message can be sent 20 times consecutively when pushed to the customer (not necessarily), if the customer does not reply during the period, or exceeds the limit, will stop sending, unless the customer reply.

The resources

  • Cloud Development Documentation
  • Cloud functions receive message push
  • customerServiceMessage.send
  • Description of conditions for sending customer service messages
  • Why does the front-end care about Serverless?

summary

I am familiar with this type of development mode. It only took about 1 hour to access the customer service message function. Compared with the traditional development mode, cloud development has given me enough confidence and let me focus on business development. I’m going to move more of the actual functionality to cloud development.