微信的新版本接口 v3/merchant/media/upload图片上传在PHP实现图片上传的时候遇到问题一直没找到解决方案,现在刚调试通了,还没有整理,贴一下核心的代码。
$api = 'https://api.mch.weixin.qq.com/v3/merchant/media/upload' ; $boundary = '7derenufded' ; //分割符号 $PSize = filesize ( './Public/images/ok.png' ); $picturedata = fread ( fopen ( './Public/images/ok.png' , "r" ), $PSize ); $sign = hash( 'sha256' , $picturedata ); $strdata = [ 'filename' => 'ok.png' , 'sha256' => $sign , ]; $boundarystr = "--{$boundary}\r\n" ; // $out是post的内容 $out = $boundarystr ; $out .= 'Content-Disposition: form-data; name="meta"' . "\r\n" ; $out .= 'Content-Type: application/json; charset=UTF-8' . "\r\n" ; $out .= "\r\n" ; $filestr = json_encode( $strdata ); $out .= "" . $filestr . "\r\n" ; $out .= $boundarystr ; $out .= 'Content-Disposition: form-data; name="file"; filename="ok.png"' . "\n" ; $out .= 'Content-Type: image/jpeg;' . "\r\n" ; $out .= "\r\n" ; $out .= $picturedata . "\r\n" ; $out .= "--{$boundary}--\r\n" ; // ----- 下面是签名过程 ----------- $url = $api ; $method = 'POST' ; $http_method = $method ; $timestamp = time(); $nonce = randCode(32,3); $mch_private_key = file_get_contents ( $this ->private_key); $merchant_id = $this ->mch_id; $serial_no = $this ->serial_no; $url_parts = parse_url ( $url ); $canonical_url = ( $url_parts [ 'path' ] . (! empty ( $url_parts [ 'query' ]) ? "?${url_parts['query']}" : "" )); $message = $http_method . "\n" . $canonical_url . "\n" . $timestamp . "\n" . $nonce . "\n" . $filestr . "\n" ; openssl_sign( $message , $raw_sign , $mch_private_key , 'sha256WithRSAEncryption' ); $sign = base64_encode ( $raw_sign ); $schema = 'WECHATPAY2-SHA256-RSA2048' ; $token = sprintf( 'mchid="%s",nonce_str="%s",timestamp="%d",serial_no="%s",signature="%s"' , $merchant_id , $nonce , $timestamp , $serial_no , $sign ); // ----- 是请求头部-------- $header = [ 'Authorization: ' . $schema . ' ' . $token , 'Accept: application/json' , "Content-Type: multipart/form-data;boundary=" . $boundary , 'User-Agent: XXXXXXXXX' , ]; // 最后带上头部和POST内容 发送CURL请求吧。 |
上传成功
可能出现的问题
q1:一直报错验签失败。
这个情况可能是微信在没有获取签名的json数据,这里要注意,post的内容是需要\r\n来换行的, 而签名里是用的\n换行,我被这里坑了一天了!!!!
使用微信官方提供的示例 很简单 https://github.com/wechatpay-apiv3/wechatpay-guzzle-middleware, 用 guzzle 请求
https://developers.weixin.qq.com/community/develop/article/doc/000e68bc0289306d74b9b732958c13
我也被坑的要是 不知道到底哪个环接错误了 比对 返回长度 和 我组装长度一致 参数也一致 就是签名不过