在項目中,可能會遇到需要引入微信公眾號圖文或消息的地方建钥,這是需要用到微信接口藤韵。
目前來說,微信的官方接口已經(jīng)比較全面熊经,涉及到圖文素材,消息等常用接口欲险。
微信官方文檔地址
調(diào)用自己有權(quán)限的公眾號可以使用如下方式:
* 獲取微信賬號 AppId
* 生成秘鑰 AppSecret
使用官方接口生成 access_token 作為其他接口使用的參數(shù)
access_token 有效生命為7200秒镐依,過期后可再次調(diào)用接口重新獲取。
在做微信公眾號接口中天试,發(fā)送的圖文消息都屬于永久素材槐壳,可以直接調(diào)用官方接口進行操作。包括:添加喜每、編輯务唐、刪除、修改带兜、查詢等基本操作枫笛。需要使用如下參數(shù):
* access_token
* 其他參數(shù)
注意:其他參數(shù)如果為多個參數(shù),參數(shù)格式為 json 字符串刚照,使用 postman 測試可能會遇到問題刑巧,需要在代碼中使用 cURL 進行測試。
代碼示例
獲取 access_token
static public function getAccessToken(){
$AppId = 'AppId';
$AppSecret = 'AppSecret';
$getUrl = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$AppId.'&secret='.$AppSecret;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $getUrl);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
// curl_setopt($ch, CURL_SSLVERSION_SSL, 2);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
$data = curl_exec($ch);
$response = json_decode($data);
return $response->access_token;
}
獲取永久圖文素材
static public function getWeChatNews($length=3)
{
$access_token = self::getAccessToken(); // 獲取 access_token
$customMessageSendUrl = 'https://api.weixin.qq.com/cgi-bin/material/batchget_material?access_token='.$access_token;
$postJosnData = '{"type":"news","offset":0,"count":3}'; // 組合個性參數(shù)
$ch = curl_init($customMessageSendUrl);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postJosnData);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
$data = curl_exec($ch);
}