1. 程式人生 > >PHP微信公眾平臺開發高階篇--模板訊息介面

PHP微信公眾平臺開發高階篇--模板訊息介面

* 2.不建議用瀏覽器直接請求,會導致推送多次訊息,可設定為事件推送 */ header("Content-type: text/html; charset=utf-8"); $postArr = file_get_contents('php://input'); $postObj = simplexml_load_string($postArr,'SimpleXMLElement', LIBXML_NOCDATA); $accessTokenInfo = file_get_contents("access_token.log"); $tokenArr = json_decode($accessTokenInfo
,true); if($accessTokenInfo && isset($tokenArr['expires_in']) && ($tokenArr['expires_in'] >time())){//保證不過期,做緩衝 //1.獲取全域性access_token $access_token = $tokenArr['access_token']; //2.組裝群發介面資料 array $array = [ 'touser' => 'oL-zT1Hkbx6Zza5Ny4ZZJr3Ze1-U', 'template_id'
=> 'IjJoLC7ZO9Ux5CALOMA1NhEq2g3FnWEITxwJ1W1JuuE', 'url' => 'www.baidu.com', 'data' =>[ 'name' => ['value'=>'Jason','color'=>'#333'],//不能直接使用green,red這種方法 'date' => ['value'=>'2018-07-17','color'=>'#157efb'] ] ]; //3.array===>json
$postJson = json_encode($array); //呼叫curl $url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=".$access_token; $ch = curl_init(); curl_setopt($ch,CURLOPT_URL,$url); curl_setopt($ch,CURLOPT_RETURNTRANSFER,1); curl_setopt($ch,CURLOPT_POST,1); curl_setopt($ch,CURLOPT_POSTFIELDS,$postJson); $output = curl_exec($ch); curl_close($ch); var_dump(json_decode($output,true)); }else{ //重新請求access_token寫入檔案 $ch = curl_init(); $appId = "wxc7991ed87e25dc13"; $appSecret = "3c1be9b400aae7042afb78dbd577f206"; $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$appId."&secret=".$appSecret; curl_setopt($ch,CURLOPT_URL,$url); curl_setopt($ch,CURLOPT_RETURNTRANSFER,1); $outPut = curl_exec($ch); curl_close($ch); $arr = json_decode($outPut,true); $tmp = [ 'access_token' =>$arr['access_token'], 'expires_in' =>time() + ($arr['expires_in'] - 200) ]; file_put_contents("access_token.log",json_encode($tmp)); }