小程序客服 - 发送消息(云开发)

693 阅读2分钟

本文使用云开发的方式实现小程序客服自动回复消息。 目前小程序发送消息的触发条件只有一种,就是用户主动发消息给客服,此时会将消息发送到开发者,开发者利用云函数和相关API自动回复用户消息。

云开发文档 developers.weixin.qq.com/miniprogram…

<!-- 打开客服对话页面方式 -->
<button open-type="contact">联系客服</button>

消息类型 event.MsgType 有4种,需先在云开发控制台中配置触发的消息类型和接收的云函数。 比如配置了消息类型为text时,用户发送了类型为text的消息到客服后,会触发replyMessage这个云函数,此时可以在云函数内做接收到用户消息之后的处理,如回复消息。也可为同一个云函数配置多个消息类型触发条件。

添加消息推送配置

image.png

// 云函数入口文件
const cloud = require('wx-server-sdk')

// 下载云存储图片,用于上传到微信服务器以供发送图片类型消息使用,可提前手动上传到云存储获取fileid。
let downLoad = async (event, context) => {
    const res = await cloud.downloadFile({
        fileID: 'cloud://xxx', // 图片的File ID,提前通过云开发控制台上传的图片fileId
    })
    const buffer = res.fileContent
    return buffer
}

// 发送图片之前,需要将媒体文件上传到微信服务器,得到 media 相关数据
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()

    //event.MsgType 用户发送的消息类型,在此为接受类型

    if (event.MsgType == 'miniprogrampage') {
        // await cloud.openapi.customerServiceMessage.send({
        //   touser: wxContext.OPENID,
        //   msgtype: 'text',
        //   text: {
        //     content: '收到 MsgType=' + event.MsgType + ';content=' + event.Content,
        //   },
        // })
    } else if (event.MsgType == 'text') {
        //发送图片
        if (event.Content == 'app') {
            let Buffer = await downLoad() // 从云存储中下载需要发送到图片
            let meida = await upload(Buffer) // 将图片上传到微信服务器得到 mediaId
            // 此时可使用 mediaId 调用 send 发送图片
            await cloud.openapi.customerServiceMessage.send({
                "touser": wxContext.OPENID, //用户openid, 可使用 wxContext.OPENID 获得
                "msgtype": "image",
                "image": {
                    "media_id": meida.mediaId,// 要发送到图片到 mediaId
                }
            })
        }
    } else {
        // await cloud.openapi.customerServiceMessage.send({
        //   'touser': wxContext.OPENID,
        //   'msgtype': 'link',
        //   'link':{
        //     'title': '标题1',
        //     'url': 'https://www.baidu.com',
        //     'description': '描述',
        //     'thumb_url': 'http://vsource.cn/wp-content/uploads/2019/11/learn_downqr-150x150.png'
        //   }
        // })
    }
    return 'success'
}

发送客服消息API developers.weixin.qq.com/miniprogram…

特别说明:目前能触发开发者云函数的用户动作只有用户主动发送消息,其他如用户进入客服界面就触发等暂不支持。