PHP 微信主动推送是指使用 PHP 编写的服务器端代码,通过微信提供的 API 接口,向微信用户发送消息。这通常用于实现微信公众号或小程序的消息推送功能。
以下是一个使用 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);
$accessToken = json_decode($response, true)['access_token'];
// 模板消息数据
$data = [
'touser' => 'user_openid',
'template_id' => 'your_template_id',
'url' => 'http://www.example.com',
'data' => [
'first' => ['value' => '订单确认', 'color' => '#173177'],
'keyword1' => ['value' => '123456', '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);
if ($result === false) {
echo "发送失败";
} else {
echo "发送成功";
}
?>
appId
和 appSecret
正确。touser
是否为有效的用户 openid。template_id
正确且已审核通过。file_get_contents
的超时设置。通过以上步骤和示例代码,您可以实现 PHP 微信主动推送功能,并解决常见的技术问题。
领取专属 10元无门槛券
手把手带您无忧上云