PHP微信公眾平臺開發高階篇--群發介面
阿新 • • 發佈:2018-12-29
<?php
/**
* 群發介面
* PS:群發之前呼叫“預覽介面”進行測試
* PS:通過第三方後臺呼叫微信上傳圖片素材介面,獲取圖片url,如:{"url":"http:\/\/mmbiz.qpic.cn\/mmbiz_jpg\/BdxWN2kspVgJOFpRHJojlWmbl0pMxUaJibxrb33qm8Hkukvr6WTIxFibiccRhf5kibfpnEYMEOqKYSwuIe82w2O2Xg\/0"}
*
* 圖文訊息群發步驟:
* 1.呼叫“新增臨時素材”介面,獲取到media_id:https://api.weixin.qq.com/cgi-bin/media/upload?access_token=ACCESS_TOKEN&type=TYPE(呼叫"新增永久素材"介面,獲取media_id測試可以)
* 2.呼叫"上傳圖文訊息素材"介面,傳入引數thumb_media_id即為上面介面返回的media_id,呼叫成功後會返回一個media_idhttps://api.weixin.qq.com/cgi-bin/media/uploadnews?access_token=ACCESS_TOKEN
* 3.呼叫"預覽介面"傳入引數media_id即為上面返回的media_id,https://api.weixin.qq.com/cgi-bin/message/mass/preview?access_token=ACCESS_TOKEN
* 4.預覽成功後,呼叫"根據標籤進行群發"或者"根據OpenID列表群發"進行群發
*
*
* 呼叫"新增永久素材"介面中的引數"thumb_media_id"是由呼叫"新增其他型別永久素材"介面返回的media_id,https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1444738729
*
*/
header("Content-type: text/html; charset=utf-8");
$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',//openId,oL-zT1MGda2BndEV7x1m6c7NDk4o
// 'text' => [
// 'content' =>urlencode('群發介面測試之文字訊息')
// ],
// 'msgtype' => 'text'//訊息型別--文字
// ];
/*單圖文*/
$array = [
'touser' => 'oL-zT1Hkbx6Zza5Ny4ZZJr3Ze1-U',//openId,
'mpnews' => [
'media_id' =>'QvcxvrH6VnkO-Hxp_RYgo7sb32-bNQkxfm4JlNimVbha5l39llewHBGnW--dbJGL'//z6N0TsCHgLpDG_IOm4cI8OmbiClbDHPL7dKjXUBJsHQ
],
'msgtype' => 'mpnews',//訊息型別--單圖文
'send_ignore_reprint' =>0
];
//3.array===>json
$postJson = urldecode(json_encode($array));
//呼叫curl
$url = "https://api.weixin.qq.com/cgi-bin/message/mass/preview?access_token=".$access_token;
// $url = "https://api.weixin.qq.com/cgi-bin/message/mass/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));
}