以下是一个简单的PHP类,用于发送微信模板消息:
class WechatTemplateMessage
{
private $appId;
private $appSecret;
public function __construct($appId, $appSecret)
{
$this->appId = $appId;
$this->appSecret = $appSecret;
}
public function sendTemplateMessage($openId, $templateId, $data, $url = '')
{
$accessToken = $this->getAccessToken();
$url = 'https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=' . $accessToken;
$postData = array(
'touser' => $openId,
'template_id' => $templateId,
'url' => $url,
'data' => $data
);
$jsonData = json_encode($postData);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$result = curl_exec($ch);
curl_close($ch);
return $result;
}
private function getAccessToken()
{
$url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=' . $this->appId . '&secret=' . $this->appSecret;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$result = curl_exec($ch);
curl_close($ch);
$accessToken = json_decode($result, true)['access_token'];
return $accessToken;
}
}
使用示例:
// 替换为你自己的AppID和AppSecret
$appId = 'your_app_id';
$appSecret = 'your_app_secret';
// 实例化WechatTemplateMessage类
$wechatTemplateMessage = new WechatTemplateMessage($appId, $appSecret);
// 替换为你自己的OpenID和模板ID
$openId = 'your_open_id';
$templateId = 'your_template_id';
// 替换为你自己的模板消息内容
$data = array(
'first' => array(
'value' => '您有新的订单',
'color' => '#173177'
),
'keyword1' => array(
'value' => '订单号123456',
'color' => '#173177'
),
'keyword2' => array(
'value' => '100元',
'color' => '#173177'
),
'remark' => array(
'value' => '请尽快处理',
'color' => '#173177'
)
);
// 发送模板消息
$result = $wechatTemplateMessage->sendTemplateMessage($openId, $templateId, $data);
// 打印发送结果
echo $result;
请注意,上述代码中的your_app_id
,your_app_secret
,your_open_id
和your_template_id
需要替换为你自己的实际值。此外,你还需要在微信公众平台上创建一个模板消息,并将模板ID替换为你自己的实际值。
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站