1. 程式人生 > >基於thinkphp3.2微信公眾號模板訊息介面通知示例

基於thinkphp3.2微信公眾號模板訊息介面通知示例

首先把下面的WxTemple放在\www\ThinkPHP\Library\Vendor下

<?php
class sendMessage {
//獲取accesstoken
function getAccesstoken(){
$ch=curl_init();
$appid="";//公眾號的appid;
$appsecret="";//公眾號的appsecret;
$url="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$appid}&secret={$appsecret}";
//GET方式抓取URL
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
//執行
$outopt=curl_exec($ch);
$outoptarr=json_decode($outopt,TRUE);
return $outoptarr['access_token'];
}
    function http_request($url,$data=array()){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
// 我們在POST資料哦!
curl_setopt($ch, CURLOPT_POST, 1);
// 把post的變數加上
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$output = curl_exec($ch);
curl_close($ch);
return $output;
}
}

然後在控制器裡寫個test方法測試下

//訊息通知函式

public function test(){
Vendor('Weixinpay.WxTemple');
$sendMes = new \sendMessage();
//data的資料根據模板的不同內容不同
$template=array(
'touser'=>'',//接收模板訊息的使用者openid
'template_id'=>"",//模板訊息的id
'url'=>'http://www.baidexuan.com',
'topcolor'=>"#7B68EE",
'data'=>array(
'first'=>array('value'=>urlencode("蝸居配送通知"),'color'=>"#743A3A"),
'Day'=>array('value'=>urlencode(date('Y-m-d H:i:s',time())),'color'=>'#333'),
'orderId'=>array('value'=>urlencode(time()),'color'=>'#333'),
'orderType'=>array('value'=>urlencode("蝸居配送"),'color'=>'#333'),
'customerName'=>array('value'=>urlencode("小蝸"),'color'=>'#333'),
'customerPhone'=>array('value'=>urlencode("17777777777"),'color'=>'#333'),
'remark'=>array('value'=>urlencode('請及時去處理訂單,'),'color'=>'#DD5044'),
)
);
$access_token = $sendMes->getAccesstoken();
$json_template=json_encode($template);
$url="https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=".$access_token;
$res=$sendMes->http_request($url,urldecode($json_template));


if ($res[errcode]==0){
echo 1;
}else{
echo -1;
};

}