微信模板消息是一种允许开发者向用户发送预定义格式消息的功能。它适用于需要向用户发送通知、提醒等场景。模板消息的内容由开发者定义,并通过微信服务器发送给用户。
微信模板消息主要分为两种类型:
以下是一个使用 PHP 发送微信模板消息的示例代码:
<?php
// 微信公众平台 AppID 和 AppSecret
$appId = 'your_app_id';
$appSecret = 'your_app_secret';
// 获取 access_token
$url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$appId}&secret={$appSecret}";
$response = file_get_contents($url);
$result = json_decode($response, true);
$accessToken = $result['access_token'];
// 模板消息数据
$data = [
'touser' => 'user_openid', // 用户的 openid
'template_id' => 'your_template_id', // 模板 ID
'url' => 'http://www.example.com', // 点击模板消息后跳转的链接
'data' => [
'first' => ['value' => 'Hello', 'color' => '#173177'],
'keyword1' => ['value' => '订单号', 'color' => '#173177'],
'keyword2' => ['value' => '2023-04-01 12:00', 'color' => '#173177'],
'remark' => ['value' => '感谢您的购买', 'color' => '#173177']
]
];
// 发送模板消息
$url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token={$accessToken}";
$options = [
'http' => [
'header' => "Content-type: application/json\r\n",
'method' => 'POST',
'content' => json_encode($data)
]
];
$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);
echo $result;
?>
appId
和 appSecret
正确。通过以上步骤和示例代码,你可以实现微信模板消息的发送。如果遇到具体问题,可以根据错误信息进行排查和解决。
领取专属 10元无门槛券
手把手带您无忧上云