后台代码
//注意公众号的openid和小程序的 openid不是同一个
$this->sendmuban($openid);
public function sendmuban($openid){
// 公众号的
$appId = '**************';
$appSecret = '***************';
// 获取 Access Token
$ch = curl_init("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$appId}&secret={$appSecret}");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
// 处理响应
$result = json_decode($response, true);
if ($result && isset($result['access_token'])) {
$accessToken = $result['access_token'];
// echo "Access Token 获取成功:{$accessToken}";
} else {
echo "Access Token 获取失败:" . json_encode($result);
}
// $openid = '***************'; // 用户的 OpenID
$templateId = '***************************'; // 模板消息 ID
// 构造模板消息数据
$templateData = [
'touser' => $openid,
'template_id' => $templateId,
'data' => [
'thing1' => [
'value' => '*****', // 姓名,对应模板消息中的 {{thing1.DATA}}
],
'time4' => [
'value' => '2023-01-01', // 时间,对应模板消息中的 {{time4.DATA}}
],
'thing5' => [
'value' => '点击查看详情', // 跳转文案,对应模板消息中的 {{thing5.DATA}}
],
],
];
// 发送模板消息
$ch = curl_init("https://api.weixin.qq.com/cgi-bin/message/template/send?access_token={$accessToken}");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($templateData, JSON_UNESCAPED_UNICODE));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
$response = curl_exec($ch);
curl_close($ch);
// 处理响应
$result = json_decode($response, true);
if ($result && $result['errcode'] === 0) {
echo "模板消息发送成功";
} else {
echo "模板消息发送失败:" . json_encode($result, JSON_UNESCAPED_UNICODE);
}
}
注意要跟模板消息的规则对应
标签:openid,ch,发送,案例,json,result,curl,模板 From: https://www.cnblogs.com/79524795-Tian/p/17932751.html