您的位置: 首页 - 站长

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


<?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');
    }
}