在开发微信小程序的过程中,订阅消息功能是与用户保持互动的重要方式之一。本文将详细介绍如何使用 PHP 语言对接微信小程序的订阅消息发送功能,帮助开发者快速理解和实现这一功能。
微信小程序的订阅消息功能允许开发者在用户主动订阅后,向用户发送模板消息。这可以用于通知用户重要的信息,如订单状态、活动提醒等。订阅消息的发送需要满足以下条件:
appid
和 secret
。cURL
扩展用于 HTTP 请求。微信小程序的 API 接口需要使用 access_token
进行身份验证。access_token
是通过小程序的 appid
和 secret
获取的,有效期为 2 小时。
php复制
class WxHelper
{
public static function getAccessToken($appId, $appSecret)
{
$url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$appId}&secret={$appSecret}";
$response = self::curl($url);
$responseJson = json_decode($response, true);
if (isset($responseJson['errcode'])) {
throw new Exception("获取 Access Token 失败:{$responseJson['errmsg']}");
}
return $responseJson['access_token'];
}
public static function curl($url, $postData = null)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
if ($postData !== null) {
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
}
$response = curl_exec($ch);
curl_close($ch);
return $response;
}
}
订阅消息的发送需要调用微信的 API 接口。我们将这一功能封装到 WxService
类中。
php复制
class WxService
{
private $appId;
private $appSecret;
public function setAppId($appId)
{
$this->appId = $appId;
}
public function setAppSecret($appSecret)
{
$this->appSecret = $appSecret;
}
public function getAccessToken()
{
return WxHelper::getAccessToken($this->appId, $this->appSecret);
}
/**
* 发送订阅消息
* @param array $message
* @throws BusinessException
*/
public function sendSubscribeMessage(array $message)
{
WxHelper::sendSubscribeMessage($this->getAccessToken(), $message);
}
}
在 WxHelper
类中,我们实现具体的发送逻辑。
php复制
class WxHelper
{
public static function sendSubscribeMessage(string $access_token, array $message)
{
// 接口地址
$api = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token={$access_token}";
// 请求接口
$response = self::curl($api, json_encode($message, JSON_UNESCAPED_UNICODE));
// 检查返回内容
if (!$response) {
throw new BusinessException("订阅消息服务接口未响应内容");
}
// 检查响应内容
$responseJson = json_decode($response, true);
if (isset($responseJson['errcode']) && $responseJson['errcode'] !== 0) {
$errStr = "错误码:{$responseJson['errcode']},错误信息:{$responseJson['errmsg']}";
throw new BusinessException("订阅消息服务异常, $errStr");
}
}
}
在业务逻辑中,我们调用封装好的发送功能。例如,发送一条考试报名提醒消息:
php复制
$data = [
'template_id' => 'Pn3wM91L28BIb5_R6dkt1MdBeIcdSVo7NZVDxZiwQjE',
'touser' => 'oPgSR62Qp7G1H8fXdBMb9mCZaxuo',
'data' => [
'thing1' => ['value' => '自学考试'],
'time3' => ['value' => '2025年1月10日'],
'thing4' => ['value' => '报考今日开始,请记得及时报名'],
],
];
$s = new WxService();
$s->setAppId('YOUR_APP_ID');
$s->setAppSecret('YOUR_APP_SECRET');
$s->sendSubscribeMessage($data);
appid
和 secret
是否正确。cURL
的超时时间。原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。