雷达智富

首页 > 内容 > 程序笔记 > 正文

程序笔记

EasyWechat 3.x 小程序客服消息自动回复

2024-09-12 10

1. 小程序消息推送简介


启用小程序的消息推送后小程序收到的消息将推送至开发者的设置的服务器地址

例如:用户关注公众号、用户给小程序的客服会话发送消息

EasyWechat 3.x : https://easywechat.com/docs/3.x/overview

更多内容参考微信官方文档:https://developers.weixin.qq.com/miniprogram/dev/framework/server-ability/message-push.html

2. 开启小程序消息推送


登录小程序管理平台,找到 开发管理-开发设置 中的消息推送

消息加密方式设置为明文模式, 数据格式设置为 JSON

3. 小程序消息推送接入验证


在小程序管理平台设置消息推送配置时,点击 提交 可能会出现: Token校验失败,请检查确认

原因分析:点击提交,微信服务器会请求填写的 URL(服务器地址),并携带一些参数进行接入验证

我们需要接收传递的参数进行加密,然后做签名校验,最后输出 echostr 参数的值,这样才能验证成功

function checkSignature(string $token){    $nonce     = $_GET["nonce"] ?? '';    $signature = $_GET["signature"] ?? '';    $timestamp = $_GET["timestamp"] ?? '';    $tmpArr = array($token, $timestamp, $nonce);    sort($tmpArr, SORT_STRING);    $tmpStr = implode('', $tmpArr);    $tmpStr = trim(sha1($tmpStr));    if (empty($token)) die('未设置消息推送token令牌');    if (empty($signature) || empty($tmpStr) || empty($nonce)) die('非法请求!!!');    if ($tmpStr != $signature) die('签名验证错误');    isset($_GET['echostr']) ? die($_GET['echostr']) : '';}

4. 客服会话自动回复


文本消息

$message = new \EasyWeChat\Message\Text(['content' => '未设置客服二维码']);

图片消息

$image = '';//本地图片绝对路径$result = $app->material_temporary->uploadImage($image);// 上传临时素材$message = new \EasyWeChat\Message\Image(['media_id' => $result['media_id']]);
$token = '';checkSignature($token);$message = json_decode(file_get_contents('php://input'), true);$app = \app\lib\EasyWechat::getInstance()->app;switch ($message['MsgType']) {    case 'miniprogrampage': // 小程序卡片        $openid  = $message['FromUserName'];        // 自动回复图片        $image = getValue('kefu_qrcode');        if ($image) {            // 上传临时素材            $result = $app->material_temporary->uploadImage($image);            $content = new Image(['media_id' => $result['media_id']]);        } else {            $content = new Text(['content' => '未设置客服二维码']);        }        // 发送消息        $app->staff->message($content)->to($openid)->send();        break;}$response = $app->server->serve();$response->send();
更新于:6天前
赞一波!

文章评论

全部评论