微信小程序实现客服消息自动回复(回复图片消息)

借鉴自微信小程序实现客服消息自动回复(回复图片消息) - 掘金 (juejin.cn)

微信小程序实现客服消息自动回复(回复图片消息)

回复消息的种类有很多,text文本消息,img图片消息,link链接消息,miniprogrampage小程序卡片消息。下面只说回复图片消息(这个在大部分教程里面都没写过,其他的可以自行在掘金上搜索)

在做图片消息自动回复之前,根据微信文档描述,需要现将图片上传到临时文件服务器,而且图片保存时间有效期只有三天

前提

  • 小程序已经开通了“云开发”功能
  • 在微信开发者工具中打开“云开发”,点“设置”,点击“其它设置”,点击“添加消息推送”(添加消息类型为“image”和“event”两种消息推送设置),点击“确定”
  • 目前微信小程序用户使用客服功能,必须通过固定的按钮进行触发,在下文展示
  • 按钮触发后小程序会主动发送客服图片消息

实现

小程序index.wxml文件中实现

需要将 button 组件 open-type 的值设置为 contact,当用户点击后就会进入客服会话,如果用户在会话中点击了小程序消息,则会返回到小程序,开发者可以通过 bindcontact 事件回调获取到用户所点消息的页面路径 path 和对应的参数 query,此外,开发者可以通过设置 session-from 将会话来源透传到客服。

<button open-type="contact" bindcontact="handleContact" session-from="sessionFrom">客服</button>

 云函数config.json配置文件

{
  "permissions": {
    "openapi": [
      "wxacode.get",
      "customerServiceMessage.send",
      "customerServiceMessage.uploadTempMedia"
    ]
  }
}

 小程序云函数入口文件index.js实现

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

cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV }) // 使用当前云环境

// 下载云存储图片
// 讲图片上传到小程序云开发的存储中可以得到文件的fileID
let downLoad = async(event, context) => {
  const res = await cloud.downloadFile({
      fileID: 'cloud://example.png' 
  })
  const buffer = res.fileContent
  return buffer
}

// 把媒体文件上传到微信服务器
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()
  
  await cloud.openapi.customerServiceMessage.send({
    touser: wxContext.OPENID,
    msgtype: 'text',
    text: {
      content: '欢迎来到印象派肖像!我是您的客服,非常高兴为您服务。如果您有任何关于摄影作品、展览或其他方面的问题,都可以随时向我咨询。如果您需要帮助或有任何疑问,请随意问我。您也可以通过搜索下面的微信号添加我为好友,我将随时为您提供帮助和回答问题。期待与您互动,分享摄影的乐趣!祝您在我们的小程序中度过愉快的时光!',
    },
  })
  await cloud.openapi.customerServiceMessage.send({
    touser: wxContext.OPENID,
    msgtype: 'text',
    text: {
      content: 'a1803233552',
    },
  })

  // 客服消息
  let Buffer = await downLoad()
  let meida = await upload(Buffer)
  await cloud.openapi.customerServiceMessage.send({
      touser: wxContext.OPENID,
      msgtype: "image",
      image: {
          "media_id": meida.mediaId
      }
  })
  

  return 'success'
}

效果 

 

 备注

扫描二维码关注公众号,回复: 16535257 查看本文章

customerServiceMessage.uploadTempMedia 的使用: 把媒体文件上传到微信服务器。目前仅支持图片。用于发送客服消息或被动回复用户消息。 云调用是微信云开发提供的在云函数中调用微信开放接口的能力,需要在云函数中通过 wx-server-sdk 使用。 调用实例

// cloud = require('wx-server-sdk')
// ...
// 方法返回 Promise
cloud.openapi.customerServiceMessage.uploadTempMedia({
  type: 'image',
  media: {
    contentType: 'image/png',
    value: Buffer
  }
})

cloud.downloadFile的使用 从云存储空间下载文件 其中下载文件的返回类型为 ArrayBuffer 调用实例

wx.cloud.downloadFile({
  fileID: 'a7xzcb'
}).then(res => {
  console.log(res.data)
}).catch(error => {
  // handle error
})

猜你喜欢

转载自blog.csdn.net/u014288878/article/details/132530395