当前位置: 首页 > news >正文

微信小程序结合后端php发送模版消息

前端:

<view class="container"><button bindtap="requestSubscribeMessage">订阅消息</button>
</view>
// index.js
Page({data: {tmplIds: ['UTgCUfsjHVESf5FjOzls0I9i_FVS1N620G2VQCg1LZ0'] // 使用你的模板ID},requestSubscribeMessage() {const tmplIds = this.data.tmplIds;if (wx.requestSubscribeMessage) {// 使用基础库 2.4.4 及以上版本wx.requestSubscribeMessage({tmplIds: tmplIds,success: (res) => {// 处理订阅消息成功的结果console.log('Subscribe message success:', res);// 遍历结果,检查用户是否同意订阅for (let tmplId of tmplIds) {if (res[tmplId] === 'accept') {console.log(`Template ID ${tmplId} subscription accepted.`);} else {console.log(`Template ID ${tmplId} subscription denied or filtered.`);}}},fail: (err) => {// 处理订阅消息失败的结果console.error('Subscribe message failed:', err);},complete: () => {// 接口调用结束console.log('RequestSubscribeMessage complete');}});} else {// 兼容低版本wx.showModal({title: '提示',content: '当前微信版本过低,无法使用该功能,请升级到最新微信版本后重试。'});}},onLoad() {// 页面加载时的逻辑}
});

后端:php7.4

/*function getWeChatToken($appid, $secret) {$url = "https://api.weixin.qq.com/cgi-bin/token";$params = http_build_query(['grant_type' => 'client_credential','appid' => $appid,'secret' => $secret,]);$ch = curl_init();curl_setopt($ch, CURLOPT_URL, $url . '?' . $params);curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true); // 忽略 SSL 证书验证curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, true); // 忽略 SSL 证书验证$response = curl_exec($ch);if (curl_errno($ch)) {echo 'cURL Error: ' . curl_error($ch);return null;}curl_close($ch);return json_decode($response, true);
}// 替换为你的 AppID 和 AppSecret
$appid = '';
$secret = '';$tokenInfo = getWeChatToken($appid, $secret);if ($tokenInfo && isset($tokenInfo['access_token'])) {echo 'Access Token: ' . $tokenInfo['access_token'];$accessToken = $tokenInfo['access_token'];
} else {echo 'Failed to get access token. Response: ' . json_encode($tokenInfo);
}*/function sendSubscribeMessage($accessToken, $templateId, $touser, $data, $page = '', $miniprogramState = 'formal', $lang = 'zh_CN') {$url = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=$accessToken";$postData = json_encode(['touser' => $touser,'template_id' => $templateId,'page' => $page,'data' => $data,'miniprogram_state' => $miniprogramState,'lang' => $lang,]);$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, $postData);curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 忽略 SSL 证书验证curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); // 忽略 SSL 证书验证$response = curl_exec($ch);if (curl_errno($ch)) {echo 'cURL Error: ' . curl_error($ch);return null;}curl_close($ch);return json_decode($response, true);
}// 替换为你的 AccessToken, TemplateID, Touser, 和 Data
$accessToken = 'your_access_token_here'; // 请替换为实际的 access token
$templateId = 'UTgCUfsjHVESf5FjOzls0I9i_FVS1N620G2VQCg1LZ0';
$touser = 'oCmkd7cO3vjwvHhLUtjDJwklvLOE';
$data = ['time1' => ['value' => '2024-7-25 12:23:25'],'amount2' => ['value' => '128'],'thing3' => ['value' => '黑金卡'],'thing4' => ['value' => '24小时内发货'],'character_string5' => ['value' => '202407251236962365']
];
$page = 'index?foo=bar'; // 可选
$miniprogramState = 'formal'; // 可选,默认 'formal'
$lang = 'zh_CN'; // 可选,默认 'zh_CN'$response = sendSubscribeMessage($accessToken, $templateId, $touser, $data, $page, $miniprogramState, $lang);if ($response && isset($response['errcode'])) {if ($response['errcode'] == 0) {echo 'Message sent successfully!';} else {echo 'Failed to send message. Error code: ' . $response['errcode'] . ', Error message: ' . $response['errmsg'];// 根据错误码提供解决方案switch ($response['errcode']) {case 40001:echo ' - 获取 access_token 时 AppSecret 错误,或者 access_token 无效。请开发者认真比对 AppSecret 的正确性,或查看是否正在为恰当的公众号调用接口。';break;case 40003:echo ' - 不合法的 OpenID ,请开发者确认 OpenID (该用户)是否已关注公众号,或是否是其他公众号的 OpenID。';break;case 40014:echo ' - 不合法的 access_token ,请开发者认真比对 access_token 的有效性(如是否过期),或查看是否正在为恰当的公众号调用接口。';break;case 40037:echo ' - 不合法的 template_id。';break;case 43101:echo ' - 用户未订阅消息。检查订阅弹窗回调结果或事件推送确认是否订阅成功,检查是否一次性订阅的次数之前已下发完。';break;case 43107:echo ' - 订阅消息能力封禁。检查账号是否被封禁订阅消息能力,检查模板id对应的模板是否被封禁。';break;case 43108:echo ' - 并发下发消息给同一个粉丝。检查是否有同时下发多个消息给同一粉丝的情况。';break;case 45168:echo ' - 命中敏感词。检查下发消息中是否带有敏感词。';break;case 47003:echo ' - 参数错误。根据wiki文档检查data结构格式是否正确,检查各个关键词是否满足对应规则。';break;default:echo ' - 未知错误,请参考微信公众平台文档。';break;}}
} else {echo 'Failed to send message. Invalid response.';
}

php8.0及以上版本

function sendSubscribeMessage(string $accessToken,string $templateId,string $touser,array $data,string $page = '',string $miniprogramState = 'formal',string $lang = 'zh_CN'
): ?array {$url = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=$accessToken";$postData = json_encode(['touser' => $touser,'template_id' => $templateId,'page' => $page,'data' => $data,'miniprogram_state' => $miniprogramState,'lang' => $lang,]);$ch = curl_init();curl_setopt($ch, CURLOPT_URL, $url);curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);curl_setopt($ch, CURLOPT_POST, true);curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 忽略 SSL 证书验证curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); // 忽略 SSL 证书验证$response = curl_exec($ch);if (curl_errno($ch)) {echo 'cURL Error: ' . curl_error($ch);return null;}curl_close($ch);return json_decode($response, true);
}// 替换为你的 AccessToken, TemplateID, Touser, 和 Data
$accessToken = 'your_access_token_here'; // 请替换为实际的 access token
$templateId = 'UTgCUfsjHVESf5FjOzls0I9i_FVS1N620G2VQCg1LZ0';
$touser = 'oCmkd7cO3vjwvHhLUtjDJwklvLOE';
$data = ['time1' => ['value' => '2024-7-25 12:23:25'],'amount2' => ['value' => '128'],'thing3' => ['value' => '黑金卡'],'thing4' => ['value' => '24小时内发货'],'character_string5' => ['value' => '202407251236962365']
];
$page = 'index?foo=bar'; // 可选
$miniprogramState = 'formal'; // 可选,默认 'formal'
$lang = 'zh_CN'; // 可选,默认 'zh_CN'$response = sendSubscribeMessage($accessToken, $templateId, $touser, $data, $page, $miniprogramState, $lang);if ($response && isset($response['errcode'])) {if ($response['errcode'] === 0) {echo 'Message sent successfully!';} else {echo 'Failed to send message. Error code: ' . $response['errcode'] . ', Error message: ' . $response['errmsg'];// 根据错误码提供解决方案match ($response['errcode']) {40001 => print(' - 获取 access_token 时 AppSecret 错误,或者 access_token 无效。请开发者认真比对 AppSecret 的正确性,或查看是否正在为恰当的公众号调用接口。'),40003 => print(' - 不合法的 OpenID ,请开发者确认 OpenID (该用户)是否已关注公众号,或是否是其他公众号的 OpenID。'),40014 => print(' - 不合法的 access_token ,请开发者认真比对 access_token 的有效性(如是否过期),或查看是否正在为恰当的公众号调用接口。'),40037 => print(' - 不合法的 template_id。'),43101 => print(' - 用户未订阅消息。检查订阅弹窗回调结果或事件推送确认是否订阅成功,检查是否一次性订阅的次数之前已下发完。'),43107 => print(' - 订阅消息能力封禁。检查账号是否被封禁订阅消息能力,检查模板id对应的模板是否被封禁。'),43108 => print(' - 并发下发消息给同一个粉丝。检查是否有同时下发多个消息给同一粉丝的情况。'),45168 => print(' - 命中敏感词。检查下发消息中是否带有敏感词。'),47003 => print(' - 参数错误。根据wiki文档检查data结构格式是否正确,检查各个关键词是否满足对应规则。'),default => print(' - 未知错误,请参考微信公众平台文档。'),};}
} else {echo 'Failed to send message. Invalid response.';
}

thinkphp8+easywechat6.0 在php8.3下的测试,测试成功

declare (strict_types = 1);namespace app\index\controller;use EasyWeChat\MiniApp\Application;class Msg
{public function index(){$config = ['app_id' => '', // 请填写小程序的appId'secret' => '', // 请填写小程序的appsecret'token' => 'easywechat','aes_key' => '','http' => ['throw'  => true, // 状态码非 200、300 时是否抛出异常,默认为开启'timeout' => 5.0,'retry' => true, // 使用默认重试配置],];$app = new Application($config);$accessToken = $app->getAccessToken();$access_token = $accessToken->getToken(); // string// return $access_token;$api = $app->getClient();$data = ['time1' => ['value' => '2024-7-25 12:23:25'],'amount2' => ['value' => '128'],'thing3' => ['value' => '黑金卡'],'thing4' => ['value' => '24小时内发货'],'character_string5' => ['value' => '202407251236962365']];$response = $api->postJson('/cgi-bin/message/subscribe/send?access_token='.$access_token, ['touser' => 'oCmkd7cO3vjwvHhLUtjDJwklvLOE','template_id' => 'UTgCUfsjHVESf5FjOzls0I9i_FVS1N620G2VQCg1LZ0','data' => $data]);return $response->getContent();}
}

返回的数据为json

{"errcode": 0,"errmsg": "ok","msgid": 3563045918154752007
}

http://www.lryc.cn/news/407274.html

相关文章:

  • sqlalchemy报错sqlalchemy.orm.exc.DetachedInstanceError
  • 华为网络模拟器eNSP安装部署教程
  • 【React】详解样式控制:从基础到进阶应用的全面指南
  • 【ROS2】高级:安全-理解安全密钥库
  • C语言 ——— 数组指针的定义 数组指针的使用
  • opencascade AIS_ManipulatorOwner AIS_MediaPlayer源码学习
  • 如何防止用户通过打印功能复制页面文字
  • Python3网络爬虫开发实战(3)网页数据的解析提取
  • 基于 HTML+ECharts 实现监控平台数据可视化大屏(含源码)
  • 立创梁山派--移植开源的SFUD和FATFS实现SPI-FLASH文件系统
  • MySQL之视图和索引实战
  • 快速参考:用C# Selenium实现浏览器窗口缩放的步骤
  • MyBatis 插件机制、分页插件如何实现的
  • CentOS6.0安装telnet-server启用telnet服务
  • H5+CSS+JS工作性价比计算器
  • Linux:基础命令学习
  • 遇到Websocket就不会测了?别慌,学会这个Jmeter插件轻松解决....
  • 高性能 Java 本地缓存 Caffeine 框架介绍及在 SpringBoot 中的使用
  • Http 和 Https 的区别(图文详解)
  • DP学习——外观模式
  • Vue3 + Vite 打包引入图片错误
  • 搭建NFS、web、dns服务器
  • C++的UI框架和开源项目介绍
  • SpringBoot连接PostgreSQL+MybatisPlus入门案例
  • vue3里将table表格中的数据导出为excel
  • 【算法】分布式共识Paxos
  • 软考:软件设计师 — 5.计算机网络
  • C++ //练习 15.28 定义一个存放Quote对象的vector,将Bulk_quote对象传入其中。计算vector中所有元素总的net_price。
  • Midjourney绘画提示词精选
  • Kylin中的RBAC:为大数据安全加把锁