<?php class Temp { private $appId; private $appSecret; public function __construct($appId, $appSecret) { $this->appId = $appId; $this->appSecret = $appSecret; } public function getAccessToken() { // access_token 应该全局存储与更新,以下代码以写入到文件中做示例 $data = json_decode($this->get_php_file("access_token.php")); if ($data->expire_time < time()) { // 如果是企业号用以下URL获取access_token // $url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=$this->appId&corpsecret=$this->appSecret"; $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$this->appId&secret=$this->appSecret"; $res = json_decode($this->https_request($url)); $access_token = $res->access_token; if ($access_token) { $data->expire_time = time() + 7000; $data->access_token = $access_token; $this->set_php_file("access_token.php", json_encode($data)); } } else { $access_token = $data->access_token; } return $access_token; } private function get_php_file($filename) { return trim(substr(file_get_contents($filename), 15)); } private function set_php_file($filename, $content) { $fp = fopen($filename, "w"); fwrite($fp, "<?php exit();?>" . $content); fclose($fp); } function https_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; } /** * 发送模板消息 * @param type $data * @return type */ public function send_tmplete_message($data) { $url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" . $this->getAccessToken(); $res = $this->https_request($url, $data); return json_decode($res, TRUE); } }
$jssdk = new Temp("wxfb337c1106b89658", "36bdf6bf95ad608c82e613f0b186af24"); //组装模板消息 $templete = array( "touser" => "okPTRs0ewUhSvPa_0ajU0p7mPaoE", "template_id" => "PpAsY7Kq7OU6rm-V1GrDhZWexrFetJOdpDAwwDpO658", "url" => "http://www.baidu.com", "data" => array( "first" => array("value" => "您好,欢迎使用自动售货机购物。"), "product" => array("value" => "可口可乐", "color" => "#173177"), "price" => array("value" => "4", "color" => "#173177"), "time" => array("value" => date("Y年m月d日")), "remark" => array("value" => "祝您购物愉快!") ) ); //发送模板消息 $jssdk->send_tmplete_message(urldecode(json_encode($templete)));