基于PHP实现微信小程序客服消息功能

基于PHP实现微信小程序客服消息功能

Anderyly
2022-02-14 / 0 评论 / 13 阅读 / 正在检测是否收录...
温馨提示:
本文最后更新于2024年02月27日,已超过268天没有更新,若内容或图片失效,请留言反馈。
  1. 开启客服消息
  2. 开启消息推送 地址

消息加密方式:可以根据自己需要选择,本例选择”兼容模式“。

数据格式:json相对于xml来说,从压缩效率及传输效率更具优势,这里我们选json。

示例代码

<?php
/**
 * @author anderyly
 * @email admin@aaayun.cc
 * @link http://blog.aaayun.cc
 * @copyright Copyright (c) 2022
 */
 
use ay\lib\Curl;

class WeChat
{
    public static $token = 'xxx'; // Token(令牌)    
    public static $key = 'xxx'; // EncodingAESKey(消息加密密钥)    
    public static $appid = 'xxx';
    public static $secret = 'xxx';

    public function index()
    {

        // $this->checkSignature(self::$token); // 验证

        $data = file_get_contents('php://input');
        $this->send($data, self::$appid, self::$secret);

    }

    public function checkSignature($token)
    {
        $signature = $_GET["signature"];
        $timestamp = $_GET["timestamp"];
        $nonce = $_GET["nonce"];
    
        $token = $token;
        $tmpArr = array($token, $timestamp, $nonce);
        sort($tmpArr, SORT_STRING);
        $tmpStr = implode( $tmpArr );
        $tmpStr = sha1( $tmpStr );
    
        if ($tmpStr == $signature ) {
            exit($_GET['echostr']);
        }
    }
    
    public function getAccessToken($appid, $secret)
    {
        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" . $appid . "&secret=" . $secret;
        
        $row = Curl::url($url)->get();
        
        $row = json_decode($row, true);
        
        return $row['access_token'] ?? false;
    }
    
    public function send($data, $appid, $secret) 
    {
        $data = json_decode($data, true);
        
        $accessToken = $this->getAccessToken($appid, $secret);
        $url = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=" . $accessToken;
        $r = [
            "touser" =>  $data['FromUserName']
        ];

        $r['msgtype'] = "link";
        
        $r['link'] = [
            "title" =>  "轻风云",
            "description" =>  "云淡风轻,于事安然",
            "url" =>  "http://blog.aaayun.cc",
            "thumb_url" => "http://blog.aaayun.cc/avatar.png"
        ];
        $json = json_encode($r, JSON_UNESCAPED_UNICODE);
        Curl::url($url)->param($json)->post('json');
    }

}
0

评论 (0)

取消