天天看點

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

公衆号經常有需要用到一些臨時性的多媒體素材的場景,例如在使用接口特别是發送消息時,對多媒體檔案、多媒體消息的擷取和調用等操作,是通過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"}(此錯誤指無效媒體類型錯誤)

完整示例代碼

<?php
/**
* 作者:smalle
* 公衆号: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 = "
​​        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;
• }
• • ?>
​​