最近在做微信上傳素材,使用tp5做框架,遇到了41005的問題,這裡是解決的方法
阿新 • • 發佈:2018-12-31
//curl_post function curl_post($url,$data = ''){ // 模擬提交資料函式 $curl = curl_init(); // 啟動一個CURL會話 if (class_exists ( '\CURLFile' )) {//php5.5跟php5.6中的CURLOPT_SAFE_UPLOAD的預設值不同,php版本>=5.6後,這種寫法就會導致檔案無法進行上傳到微信伺服器 curl_setopt ( $curl, CURLOPT_SAFE_UPLOAD, true ); } else { if (defined ( 'CURLOPT_SAFE_UPLOAD')) { curl_setopt ( $curl, CURLOPT_SAFE_UPLOAD, false ); } } curl_setopt($curl, CURLOPT_URL, $url); // 要訪問的地址 curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0); // 對認證證書來源的檢查 curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0); // 從證書中檢查SSL加密演算法是否存在 curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); // 模擬使用者使用的瀏覽器 // curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1); // 使用自動跳轉 // curl_setopt($curl, CURLOPT_AUTOREFERER, 1); // 自動設定Referer curl_setopt($curl, CURLOPT_POST, 1); // 傳送一個常規的Post請求 curl_setopt($curl, CURLOPT_POSTFIELDS, $data); // Post提交的資料包 curl_setopt($curl, CURLOPT_TIMEOUT, 30); // 設定超時限制防止死迴圈curl_setopt($curl, CURLOPT_HEADER, 0); // 顯示返回的Header區域內容 curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); // 獲取的資訊以檔案流的形式返回 $tmpInfo['data'] = curl_exec($curl); // 執行操作 $tmpInfo['errno'] = curl_errno($curl);//捕抓異常 curl_close($curl); // 關閉CURL會話 return $tmpInfo; // 返回資料 }
//上傳素材 private function uploadMediaMaterialQifen($aParam){ $sAccessToken = $this->readAcessToken(); if($aParam['type'] == 2){ //圖片 $type = "image"; }else if($aParam['type'] == 3){ //語音 $type = "voice"; }else if($aParam['type'] == 4){ //視訊 $type = "video"; } $url = "https://api.weixin.qq.com/cgi-bin/material/add_material?access_token=".$sAccessToken."&type=".$type; $real_path = "{$_SERVER['DOCUMENT_ROOT']}{$aParam['mediaval']}"; if (class_exists ( '\CURLFile' )) {//關鍵是判斷curlfile,官網推薦php5.5或更高的版本使用curlfile來例項檔案 $real_path = new \CURLFile ( $real_path, $aParam['mediamime'] ); } else { $real_path = '@' . $real_path; } $file_info = array( 'media' => $real_path, 'type' => $type, 'filename' => $aParam['mediaval'], 'filelength' => $aParam['mediasize'], 'content-type' => $aParam['mediamime'] ); //素材 $result = curl_post($url,$file_info); if(!empty($result)){ $userUnionjson = json_decode($result["data"]); if(isset($userUnionjson->{'errcode'})){ $sErrCode = $userUnionjson->{'errcode'}; if ($sErrCode == "40001" || $sErrCode == "41001"|| $sErrCode == "42001"){ $sAccessToken = $this->getAcessToken(); $url = "https://api.weixin.qq.com/cgi-bin/material/add_material?access_token=".$sAccessToken."&type=".$type; $result = curl_post($url,$file_info); } } } return json_decode($result["data"],true); }