公众号模板消息发送API接口 PHP
刚子 发布于 阅读:262
我们可以通过以下代码来获取Access Token:
function getAccessToken($appId, $appSecret) {
$apiUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" . $appId . "&secret=" . $appSecret;
$response = file_get_contents($apiUrl);
$result = json_decode($response, true);
// Check if access token is valid
if(isset($result['access_token'])) {
return $result['access_token'];
} else {
// Handle error
return false;
}
}
$accessToken = getAccessToken($appId, $appSecret);
二、发送模板消息
获取到Access Token后,我们可以使用该Token发送模板消息。以下是一个示例代码,发送模板消息给用户:
function sendTemplateMessage($accessToken, $openId, $templateId, $data) {
$apiUrl = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" . $accessToken;
$postData = array(
'touser' => $openId,
'template_id' => $templateId,
'data' => $data
);
$jsonData = json_encode($postData);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $apiUrl);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
$response = curl_exec($ch);
curl_close($ch);
// Handle response
return $response;
}
// 要发送的模板消息的数据
$templateData = array(
'first' => array('value' => '您好', 'color' => '#173177'),
'keyword1' => array('value' => '模板消息', 'color' => '#173177'),
'keyword2' => array('value' => '2020-01-01', 'color' => '#173177'),
'remark' => array('value' => '感谢您的使用', 'color' => '#173177')
);
$response = sendTemplateMessage($accessToken, $openId, $templateId, $templateData);
// 处理发送结果
$result = json_decode($response, true);
if($result['errcode'] == 0) {
echo "模板消息发送成功!";
} else {
echo "模板消息发送失败,请稍后重试。错误信息:" . $result['errmsg'];
}