• php利用微信公众号发送模板消息


    1. class wechat
    2. {
    3. //发送模板消息
    4. public function do_send()
    5. {
    6. $appid = 'wx8943797211495ec';
    7. $appsecret = 'f9fd4df00548ce4b08f68a0a52c07';
    8. $access_token_url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=' . $appid . '&secret=' . $appsecret;
    9. //获取access_token
    10. $json_token = $this->curl_post($access_token_url);
    11. $access_token1 = json_decode($json_token, true);
    12. $access_token2 = $access_token1['access_token'];
    13. //模板消息
    14. $json_template = $this->json_tempalte();
    15. $url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" . $access_token2;
    16. $res = $this->curl_post($url, urldecode($json_template));
    17. $res = json_decode($res, true);
    18. if ($res['errcode'] == 0) {
    19. echo '发送成功';
    20. } else {
    21. echo '发送失败';
    22. }
    23. }
    24. //将模板消息json格式化
    25. public function json_tempalte()
    26. {
    27. //模板消息
    28. $template = [
    29. 'touser' => 'oS3TrsvDsvnF77BNNuMTj0FRi9g8', //前面获取的openid
    30. 'template_id' => "Vm8N6Avj-rVlNx1s8GsUBgdTPmX4Q7zYfJNJ2PcXyLA", //前面新增的模板id
    31. 'url' => "http://www.chinaportrait.org/", //点击模板消息会跳转的链接
    32. 'topcolor' => "#7B68EE",
    33. 'data' => array(
    34. //这里在测试号是没法显示的,但是在正式的模板是这样的数据
    35. 'first' => array('value' => urlencode("尊敬的云淡风轻,您好!"), 'color' => "#FF0000"),
    36. 'keyword1' => array('value' => urlencode('2022年'), 'color' => '#FF0000'), //keyword需要与配置的模板消息对应
    37. 'keyword2' => array('value' => urlencode('1000元'), 'color' => '#FF0000'),
    38. 'remark' => array('value' => urlencode('感谢您对中国人像摄影学会工作的支持!'), 'color' => '#FF0000')
    39. )
    40. ];
    41. $json_template = json_encode($template);
    42. return $json_template;
    43. }
    44. //curl请求
    45. function curl_post($url, $data = array())
    46. {
    47. $curl = curl_init();
    48. curl_setopt($curl, CURLOPT_URL, $url);
    49. curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
    50. curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
    51. if (!empty($data)) {
    52. curl_setopt($curl, CURLOPT_POST, 1);
    53. curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
    54. }
    55. curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    56. $output = curl_exec($curl);
    57. curl_close($curl);
    58. return $output;
    59. }
    60. }
    61. $wx=new wechat();
    62. $wx->do_send();

  • 相关阅读:
    【学习笔记16】JavaScript函数封装习题
    trustZone学习
    easyrecovery2023免费版电脑数据恢复软件下载功能介绍
    Java的密码生成和验证库Passay − 快速指南
    鸿蒙Next怎么升级,有便捷的方法?
    基于JAVA砂石矿山管理系统计算机毕业设计源码+系统+mysql数据库+lw文档+部署
    人工神经网络算法的应用,人工神经网络是算法吗
    <C++>文件操作基础详解,快来写出你的第一个文件吧
    硬核解析 MySQL 的 MVCC 实现原理,面试官看了都直呼内行
    【Linux进阶篇】Linux安装MySQL
  • 原文地址:https://blog.csdn.net/quweiie/article/details/126460476