获取公众号素材管理列表-教程

思路
1.根据公众号的appid和secret获取到access_token;
2.根据access_token以及相关参数获取素材管理列表数据
直接上传代码,有注释,很简单。

<?php
/*
 * 获取access_token
 *grant_type 获取access_token填写client_credential
 *appid 第三方用户唯一凭证
 *secret 第三方用户唯一凭证密钥,即appsecret
**/
$appid="**";
$secret="**";
$access_token=get_access_token($appid,$secret);
//print "<div>调试凭证".$access_token."</div><br />";
$returnData=get_article_list("news","0","1",$access_token);
print "<div>返回的数据".$returnData."</div><br />";
function get_access_token($appid,$secret)
{
    $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$appid."&secret=".$secret."";
    $response = file_get_contents($url);
    //返回数据格式:{"access_token":"ACCESS_TOKEN","expires_in":7200}
    //expires_in:凭证有效时间
    $res = json_decode($response, true);
    return $res['access_token'];
};
/*
    *获取文章列表
    *type 素材的类型:图片(image)、视频(video)、语音 (voice)、图文(news)
    *offset 从全部素材的该偏移位置开始返回,0表示从第一个素材 返回
    *count 返回素材的数量,取值在1到20之间
    */
 function get_article_list($type, $offset, $count, $access_token)
{
    //https://api.weixin.qq.com/cgi-bin/material/batchget_material?access_token=ACCESS_TOKEN

    $url = "https://api.weixin.qq.com/cgi-bin/material/batchget_material?access_token=".$access_token;
    $data = '{"type":"'.$type.'","offset":"'.$offset.'","count":"'.$count.'"}';
    //返回的数据
    $response =get_response_post($url, $data);
    return $response;

};
 function get_response_post($url, $data)
{
    $curl = curl_init($url);
    curl_setopt($curl, CURLOPT_HEADER, 0);//过滤头部
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);//获取的信息以文件流的形式返回,而不是直接输出。
    curl_setopt($curl,CURLOPT_POST,true); // post传输数据
    curl_setopt($curl,CURLOPT_POSTFIELDS,$data);// post传输数据
    $responseText = curl_exec($curl);
    curl_close($curl);
    return $responseText;
};
?>

猜你喜欢

转载自www.cnblogs.com/bluealine/p/11983356.html