做微信开发的人都知道微信模版消息的重要性,今天给大家分享一篇使用PHP来发送微信模版消息的demo,废话少说,进入正题。
1、创建一个发送模版消息的类,我这里命名为“templatesMessage.php”,代码如下:
<?php class class_weixin{ var $appid = '请在这里填写你的appid'; var $appsecret = '请在这里填写你的appsecret'; //构造函数,获取Access Token public function __construct($appid = NULL, $appsecret = NULL) { if($appid && $appsecret){ $this->appid = $appid; $this->appsecret = $appsecret; } $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" .$this->appid."&secret=".$this->appsecret; $res = $this->http_request($url); $result = json_decode($res, true); $this->access_token = $result["access_token"]; $this->lasttime = time(); } //发送模版消息 public function send_template_message($data) { $url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" .$this->access_token; $res = $this->http_request($url, $data); return json_decode($res, true); } //https请求(支持GET和POST) protected function http_request($url, $data = null) { $curl = curl_init(); curl_setopt($curl, CURLOPT_URL, $url); curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE); curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE); if (!empty($data)){ curl_setopt($curl, CURLOPT_POST, 1); curl_setopt($curl, CURLOPT_POSTFIELDS, $data); } curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); $output = curl_exec($curl); curl_close($curl); return $output; } } ?>
2、接着在你想要触发模版消息的地方构建消息,并使用代码进行发送:
$data = array('touser' => "接收者openid", 'template_id' => "模版消息id", 'url' => "点击查看详情URL", 'topcolor' => "#7B68EE", 'data' => array( 'first' => array( 'value' => urlencode("您好,您下单已成功"), 'color' => "#743A3A", ), 'OrderSn'=> array( 'value' => urlencode("A123456"), 'color' => "#FF0000", ), 'OrderStatus' => array( 'value' => urlencode("待处理"), 'color' => "#C4C400", ), 'remark' => array( 'value' => urlencode("\\n我们会尽快与您取得联系!"), 'color' => "#008000", ), ) ); require_once('templatesMessage.php'); $weixin = new class_weixin(); var_dump($weixin->send_template_message(urldecode(json_encode($data)))); //打印发送模版消息的结果
最后说明一下,本文代码来自网络,本人亲自调试成功后发出来给大家,最终版权归作者所有。
转载请注明: haoshu发表于浩叔逛逛>>https://www.haoshu888.com/php/812.html