这篇文章主要介绍了php如何实现发送微信模板消息,具有一定借鉴价值,感兴趣的朋友可以参考下,希望大家阅读完这篇文章之后大有收获,下面让小编带着大家一起了解一下。
具体如下:
该方法基于thinkphp实现实现,具体OrderPush.class.php文件如下:
<?phpnamespace Org\Weixin;class OrderPush{ protected $appid; protected $secrect; protected $accessToken; function __construct($appid, $secrect) { $this->appid = $appid; $this->secrect = $secrect; $this->accessToken = $this->getToken($appid, $secrect); } /** * 发送post请求 * @param string $url * @param string $param * @return bool|mixed */ function request_post($url = '', $param = '') { if (empty($url) || empty($param)) { return false; } $postUrl = $url; $curlPost = $param; $ch = curl_init(); //初始化curl curl_setopt($ch, CURLOPT_URL, $postUrl); //抓取指定网页 curl_setopt($ch, CURLOPT_HEADER, 0); //设置header curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //要求结果为字符串且输出到屏幕上 curl_setopt($ch, CURLOPT_POST, 1); //post提交方式 curl_setopt($ch, CURLOPT_POSTFIELDS, $curlPost); $data = curl_exec($ch); //运行curl curl_close($ch); return $data; } /** * 发送get请求 * @param string $url * @return bool|mixed */ function request_get($url = '') { if (empty($url)) { return false; } $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); $data = curl_exec($ch); curl_close($ch); return $data; } /** * @param $appid * @param $appsecret * @return mixed * 获取token */ protected function getToken($appid, $appsecret) { if (S($appid)) { $access_token = S($appid); } else { $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" . $appid . "&secret=" . $appsecret; $token = $this->request_get($url); $token = json_decode(stripslashes($token)); $arr = json_decode(json_encode($token), true); $access_token = $arr['access_token']; S($appid, $access_token, 720); } return $access_token; } /** * 发送自定义的模板消息 * @param $touser * @param $template_id * @param $url * @param $data * @param string $topcolor * @return bool */ public function doSend($touser, $template_id, $url, $data, $topcolor = '#7B68EE') { /* * data=>array( 'first'=>array('value'=>urlencode("您好,您已购买成功"),'color'=>"#743A3A"), 'name'=>array('value'=>urlencode("商品信息:微时代电影票"),'color'=>'#EEEEEE'), 'remark'=>array('value'=>urlencode('永久有效!密码为:1231313'),'color'=>'#FFFFFF'), ) */ $template = array( 'touser' => $touser, 'template_id' => $template_id, 'url' => $url, 'topcolor' => $topcolor, 'data' => $data ); $json_template = json_encode($template); $url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" . $this->accessToken; $dataRes = $this->request_post($url, urldecode($json_template)); if ($dataRes['errcode'] == 0) { return true; } else { return false; } }}
感谢你能够认真阅读完这篇文章,希望小编分享的“php如何实现发送微信模板消息”这篇文章对大家有帮助,同时也希望大家多多支持亿速云,关注亿速云行业资讯频道,更多相关知识等着你来学习!
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。