微信小微商戶圖片上傳介面
阿新 • • 發佈:2018-11-20
先貼上圖片上傳文件地址
https://pay.weixin.qq.com/wiki/doc/api/download/img_upload.pdf
圖片上傳介面返回的media_id在申請入駐介面時有用,所以一開始就得把這個調通,才能繼續往下走申請入駐介面。
下面直接上程式碼看著清楚點
<?php
/**
* uploadMedia.php
*
* Created by PhpStorm.
* author: liuml
* DateTime: 2018/8/24 13:59
*/
namespace App\Wechat\V1\Services\wechat\traits;
use App\Wechat\V1\exception\WxException;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Request;
trait UploadMedia
{
protected $media_addr;
public function uploadImg()
{
$url = self ::WXAPIHOST . 'secapi/mch/uploadmedia';
// 判斷圖片地址是否為空,空的話就呼叫圖片上傳方法,把圖片上傳到伺服器
empty($this->media_addr) && $this->saveImg();
// 判斷圖片是否存在
if (!file_exists($this->media_addr))
throw new WxException(10001);
$data = [
'mch_id' => $this->mch_id,
'media_hash' => md5_file($this->media_addr),
];
$data['sign_type'] = 'HMAC-SHA256';
// 生成簽名
$data['sign'] = $this->makeSign($data, $data['sign_type']);
// CURLFile 類的解釋 http://php.net/manual/zh/class.curlfile.php
$data['media'] = new \CURLFile($this->media_addr);
$header = [
"content-type:multipart/form-data",
];
$res = $this->httpsRequest($url, $data, $header, true);
if ($res[1] == 200) {
$rt = $this->fromXml($res[0]);
if ($rt['return_code'] != 'SUCCESS' && $rt['result_code'] != 'SUCCESS') {
throw new WxException(0, $rt['return_msg']);
}
if ($this->checkSign($rt)) {
return [
'media_id' => $rt['media_id'],
];
}
}
throw new WxException(30002);
}
public function saveImg()
{
$images = Request::file('media'); //1、使用laravel 自帶的request類來獲取一下檔案
if (!$images) {
\Log::info('saveImg' . microtime(true));
throw new WxException(0, '至少上傳一張圖片');
}
$uploadMediaAddr = Config::get('api.wechatConfig.uploadMediaAddr'); //2、定義圖片上傳路徑
$imagesName = $images->getClientOriginalName(); //3、獲取上傳圖片的檔名
$extension = $images->getClientOriginalExtension(); //4、獲取上傳圖片的字尾名
if (in_array($extension, ['jpeg', 'jpg', 'bmp', 'png'])) {
$newImagesName = md5(microtime()) . random_int(10000, 50000) . "." . $extension;//5、重新命名上傳檔名字
$res = $images->move($uploadMediaAddr, $newImagesName); //6、使用move方法移動檔案.
return $this->media_addr = $res->getRealPath();
}
throw new \Exception(10002);
}
}
注:這個介面需要證書,curl設定好,不然返回為空(設定如下圖)