公衆號經常有需要用到一些臨時性的多媒體素材的場景,例如在使用接口特別是發送消息時,對多媒體文件、多媒體消息的獲取和調用等操作,是通過media_id來進行的。
接口開放權限:素材管理接口對所有認證的訂閱號和服務號開放。
接口調用說明
1、http請求方式
POST/FORM,需使用https
2、參數說明
參數 是否必須 說明access_token 是 調用接口憑證type 是 媒體文件類型,分別有圖片(image)、語音(voice)、視頻(video)和縮略圖(thumb)media 是 form-data中媒體文件標識,有filename、filelength、content-type等信息
3、返回數據說明
參數 描述type 媒體文件類型,分別有圖片(image)、語音(voice)、視頻(video)和縮略圖(thumb,主要用於視頻與音樂格式的縮略圖)media_id 媒體文件上傳後,獲取時的唯一標識created_at 媒體文件上傳時間戳
正確情況下的返回JSON數據包結果如:{"type":"TYPE","media_id":"MEDIA_ID","created_at":123456789}
錯誤情況下的返回JSON數據包示例如:{"errcode":40004,"errmsg":"invalid media type"}(此錯誤指無效媒體類型錯誤)
完整示例代碼
1、上傳圖片“smallelife.jpg”到服務器根目錄
2、將以下代碼寫入到index.php文件中,並將此文件上傳到服務器根目錄(記得修改AppID和AppSecret),具體如下:(完整代碼下載)
[php] view plain copy
- <?php
- /**
- * 作者:smalle
- * 網址:http://blog.csdn.net/oldinaction
- * 公衆號:smallelife
- */
- define("AppID","你的AppID");
- define("AppSecret", "你的AppSecret");
- /* 新增一個臨時素材 */
- //url 裏面的需要2個參數一個 access_token 一個是 type(值可爲image、voice、video和縮略圖thumb)
- $url = "https://api.weixin.qq.com/cgi-bin/media/upload?access_token=".get_token()."&type=image";
- if (class_exists('\CURLFile')) {
- $josn = array('media' => new \CURLFile(realpath("smallelife.jpg")));
- } else {
- $josn = array('media' => '@' . realpath("smallelife.jpg"));
- }
- $ret = curl_post($url,$josn);
- $row = json_decode($ret);//對JSON格式的字符串進行編碼
- echo '此素材的唯一標識符media_id爲:'.$row->media_id;//得到上傳素材後,此素材的唯一標識符media_id
- //獲取access_token
- function get_token(){
- $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".AppID."&secret=".AppSecret;
- $data = json_decode(file_get_contents($url),true);
- if($data['access_token']){
- return $data['access_token'];
- }else{
- echo "Error";
- exit();
- }
- }
- //curl實現post請求
- function curl_post($url, $data = null)
- {
- //創建一個新cURL資源
- $curl = curl_init();
- //設置URL和相應的選項
- curl_setopt($curl, CURLOPT_URL, $url);
- if (!empty($data)){
- curl_setopt($curl, CURLOPT_POST, 1);
- curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
- }
- curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
- //執行curl,抓取URL並把它傳遞給瀏覽器
- $output = curl_exec($curl);
- //關閉cURL資源,並且釋放系統資源
- curl_close($curl);
- return $output;
- }
- ?>