🗣 Wd提问: PHP源码微信模板消息
🤖 Ai回答: PHP实现微信模板消息发送源码
微信模板消息是微信平台提供的消息推送服务,允许开发者向用户发送模板化的消息通知。下面提供一个完整的PHP实现方案。
基本原理
微信模板消息发送需要:
1、申请模板ID(在微信公众平台申请)
2、获取access_token(用于调用微信API)
3、构造符合要求的模板消息JSON数据
4、通过POST请求发送给微信API
完整源码
php
<?php
/
* 微信模板消息发送类
*
* 使用前需要:
* 1、申请模板ID(在微信公众平台模板库中申请)
* 2、配置APP_ID和APP_SECRET(在微信公众平台后台获取)
*/
class WechatTemplateMessage {
// 配置参数
private $app_id;
private $app_secret;
private $template_id;
// 缓存
private $access_token;
private $access_token_expire;
/
* 构造函数
* @param string $app_id 公众号/小程序AppID
* @param string $app_secret 公众号/小程序AppSecret
* @param string $template_id 微信模板ID
*/
public function __construct($app_id, $app_secret, $template_id) {
$this-app_id = $app_id;
$this-app_secret = $app_secret;
$this-template_id = $template_id;
// 初始化缓存
$this-access_token = null;
$this-access_token_expire = 0;
}
/
* 获取access_token
* @return string access_token
* @throws Exception 如果获取失败
*/
private function getAccessToken() {
// 如果已有有效access_token,则直接使用
if ($this-access_token && time() < $this-access_token_expire) {
return $this-access_token;
}
// 构造获取access_token的URL
$url = https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid= 、$this-app_id 、&secret= 、$this-app_secret;
// 使用cURL发送请求
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
$response = curl_exec($ch);
// 检查cURL错误
if (curl_errno($ch)) {
throw new Exception(cURL请求失败: 、curl_error($ch));
}
// 检查HTTP状态码
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($httpCode != 200) {
throw new Exception(获取access_token失败,HTTP状态码: 、$httpCode);
}
// 解析JSON响应
$result = json_decode($response, true);
// 检查是否获取成功
if (!isset($result['access_token'])) {
throw new Exception(获取access_token失败: 、$result['errmsg'] 、 ( 、$result['errcode'] 、));
}
// 设置过期时间(access_token有效期2小时)
$this-access_token = $result['access_token'];
$this-access_token_expire = time() + 7200;
return $this-access_token;
}
/
* 发送模板消息
* @param string $openid 用户openid
* @param array $data 消息数据数组
* @param string $color 指定颜色 (默认173177)
* @return array 响应结果
* @throws Exception 如果发送失败
*/
public function send($openid, $data, $color = '173177') {
// 验证参数
if (!is_array($data) empty($data)) {
throw new Exception(模板数据必须是一个非空数组);
}
// 确保所有必填字段都存在
$requiredFields = ['first', 'keyword1', 'keyword2', 'keyword3', 'remark'];
foreach ($requiredFields as $field) {
if (!array_key_exists($field, $data)) {
throw new Exception(模板数据中缺少必填字段: 、$field);
}
}
// 获取access_token
$access_token = $this-getAccessToken();
// 构建模板消息数据
$templateData = [
'touser' = $openid,
'template_id' = $this-template_id,
'data' = $data,
'emphasis_keyword' = 'keyword1.DATA' // 可选,可指定强调的字段
];
// 转换为JSON字符串
$jsonData = json_encode($templateData, JSON_UNESCAPED_UNICODE);
// 发送请求到微信API
$url = https://api.weixin.qq.com/cgi-bin/message/template/send?access_token= 、$access_token;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: application/json; charset=utf-8',
'Accept: application/json'
]);
$response = curl_exec($ch);
// 处理cURL错误
if (curl_errno($ch)) {
throw new Exception(cURL请求失败: 、curl_error($ch));
}
// 检查HTTP状态码
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($httpCode != 200) {
throw new Exception(发送模板消息失败,HTTP状态码: 、$httpCode);
}
// 解析响应
$result = json_decode($response, true);
// 检查微信返回的错误码
if (isset($result['errcode']) && $result['errcode'] != 0) {
throw new Exception(发送模板消息失败: 、$result['errmsg'] 、 ( 、$result['errcode'] 、));
}
return $result;
}
/
* 设置模板消息数据
*
* @param array $data 消息数据
* @return array 返回处理后的消息数据
*/
public function setTemplateData($data) {
// 确保所有数据字段都有value
foreach ($data as $key = $value) {
if (!is_array($value) !isset($value['value'])) {
throw new Exception(数据字段 {$key} 必须包含 'value' 键);
}
}
return $data;
}
/
* 生成安全的模板消息内容
*
* @param string $content 消息内容
* @return string 安全处理后的内容
*/
private function sanitizeContent($content) {
// 过滤特殊字符,防止XSS攻击
return htmlspecialchars($content, ENT_QUOTES, 'UTF-8');
}
}
// 使用示例
try {
// 配置微信参数
$app_id = 'your_app_id';
$app_secret = 'your_app_secret';
$template_id = 'your_template_id';
// 实例化模板消息类
$wechatTemplate = new WechatTemplateMessage($app_id, $app_secret, $template_id);
// 准备消息数据
$templateData = [
'first' = [
'value' = '您有一笔新订单',
'color' = '173177'
],
'keyword1' = [
'value' = '订单号:1234567890',
'color' = '173177'
],
'keyword2' = [
'value' = '2024-05-10',
'color' = '173177'
],
'keyword3' = [
'value' = '已发货',
'color' = '173177'
],
'remark' = [
'value' = '点击查看详情',
'color' = '173177'
]
];
// 发送消息
$result = $wechatTemplate-send('openid_123', $templateData);
if ($result['errcode'] == 0) {
echo 模板消息发送成功!\n;
print_r($result);
} else {
echo 发送失败: 、$result['errmsg'] 、 (错误码: 、$result['errcode'] 、)\n;
}
} catch (Exception $e)
📣 商家广告:





0
IP地址: 183.60.6.105
搜索次数: 0
提问时间: 2025-11-11 04:16:09
🛒 域名购买:
zhansou.cn
53.gold
51.biz
pcks.cn
2226.com.cn
f.cq.cn
w-t.cn
97.gold
990.net.cn
85.com.hk
❓️ 热门提问:
日本空间专业
网店产品托管
哪里有云空间
河南 云主机
关键词SEO split testing
主机云价格
logo搜索引擎
高防服务器网络
PHP二次开发异步处理
机柜如何散热
豌豆Ai站群搜索引擎系统
🌐 域名评估:
zx.cx
SouHuAi.com
s-y.com.cn
d.nx.cn
saweb.cn
t-x.com.cn
vv.ln.cn
vtol.fj.cn
d.hn.cn
r.jx.cn
⛏ 最新挖掘:
凯里酸汤鱼
贵阳烤脑花
都匀毛尖茶
花溪牛肉粉
贵阳烤生蚝
贵阳烤豆腐
贵阳纸包鱼
贵阳特色菜
🖌 热门作画:
🤝 关于我们:
豌豆Ai
域名
建站
站群
留痕
推广
评估
源码
开发Ai
工具
日记
价格
加盟
广告
流量
留言
联系
🗨 加入群聊:
🔗 友情链接:
贵州软件开发
平塘县综合福利院
ai提问
🧰 站长工具:
Ai工具 whois查询 搜索
📢 温馨提示:本站所有问答由Ai自动创作,内容仅供参考,若有误差请用“联系”里面信息通知我们人工修改或删除。
👉 技术支持:本站由豌豆Ai提供技术支持,使用的最新版:《豌豆Ai站群搜索引擎系统 V.25.10.25》搭建本站。