- 开启客服消息
- 开启消息推送 地址
消息加密方式:可以根据自己需要选择,本例选择”兼容模式“。
数据格式: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)