微信公衆平臺開發【素材管理】上傳臨時素材

公衆號經常有需要用到一些臨時性的多媒體素材的場景,例如在使用接口特別是發送消息時,對多媒體文件、多媒體消息的獲取和調用等操作,是通過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

  1. <?php  
  2. /** 
  3.   * 作者:smalle 
  4.   * 網址:http://blog.csdn.net/oldinaction 
  5.   * 公衆號:smallelife 
  6.   */  
  7.   
  8. define("AppID","你的AppID");  
  9. define("AppSecret", "你的AppSecret");  
  10.   
  11. /* 新增一個臨時素材 */  
  12. //url 裏面的需要2個參數一個 access_token 一個是 type(值可爲image、voice、video和縮略圖thumb)  
  13. $url = "https://api.weixin.qq.com/cgi-bin/media/upload?access_token=".get_token()."&type=image";  
  14. if (class_exists('\CURLFile')) {  
  15.     $josn = array('media' => new \CURLFile(realpath("smallelife.jpg")));  
  16. } else {  
  17.     $josn = array('media' => '@' . realpath("smallelife.jpg"));  
  18. }  
  19.   
  20. $ret = curl_post($url,$josn);  
  21. $row = json_decode($ret);//對JSON格式的字符串進行編碼  
  22. echo '此素材的唯一標識符media_id爲:'.$row->media_id;//得到上傳素材後,此素材的唯一標識符media_id  
  23.   
  24. //獲取access_token  
  25. function get_token(){  
  26.     $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".AppID."&secret=".AppSecret;  
  27.     $data = json_decode(file_get_contents($url),true);  
  28.     if($data['access_token']){  
  29.         return $data['access_token'];  
  30.     }else{  
  31.         echo "Error";  
  32.         exit();  
  33.     }  
  34. }  
  35.   
  36. //curl實現post請求  
  37. function curl_post($url, $data = null)  
  38. {  
  39.     //創建一個新cURL資源  
  40.     $curl = curl_init();  
  41.     //設置URL和相應的選項   
  42.     curl_setopt($curl, CURLOPT_URL, $url);  
  43.     if (!empty($data)){  
  44.         curl_setopt($curl, CURLOPT_POST, 1);  
  45.         curl_setopt($curl, CURLOPT_POSTFIELDS, $data);  
  46.     }  
  47.     curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);  
  48.     //執行curl,抓取URL並把它傳遞給瀏覽器  
  49.     $output = curl_exec($curl);  
  50.     //關閉cURL資源,並且釋放系統資源  
  51.     curl_close($curl);  
  52.     return $output;  
  53. }  
  54.   
  55. ?>  

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章