<?php
class Template_message{
var $appid;
var $appsecret;
public function __construct($appid = null,$appsecert = null){
if($appid && $appsecert){
$this->appid = $appid;
$this->appsecret = $appsecert;
}
$this->lasttime = 1487225773;
//if(time() > ($this->lasttime + 7200)){
$url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$this->appid."&secret=".$this->appsecret;
$res = json_decode($this->http_request($url),true);
$this->access_token = $res['access_token'];
$this->lasttime = time();
//}
}
/**发送模板消息
* @param $openid 用户的openid
* @param $temp_id 模板id
* @param $url 详情地址
* @param $data
* @return mixed
*/
public function send_template_message($openid,$temp_id,$url,$data){
$tem = array (
'touser' => $openid,
'template_id' => $temp_id,
'url' => $url,
'data' => $data
);
$url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=".$this->access_token;
$json_tem = json_encode($tem);
return json_decode($this->http_request($url,$json_tem),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;
}
}
?>
index.php
include_once("template_message_class.php");
include_once("WxPayPubHelper/WxPay.pub.config.php");
/*模板消息推送*/
$tem = new Template_message(WxPayConf_pub::APPID,WxPayConf_pub::APPSECRET);
$data = array (
'first' =>
array (
'value' => '恭喜您拼团成功!!',
'color' => '#173177',
),
'keyword1' =>
array (
'value' => ‘订单编号’,
'color' => '#173177',
),
'keyword2' =>
array (
'value' => ‘产品名字’,
'color' => '#173177',
),
'remark' =>
array (
'value' => “限量热卖中,点击抢购>>",
'color' => '#f30b0b',
),);
$tem_url = '/index.php?m=product&s=detail&id='.$id;
$tem->send_template_message(OPENID,'qCKwU11R0ufEX-JW_XroO267xRj0wCT56ZB4K9KSS-4',$tem_url,$data);