Skip to content

Commit

Permalink
🆕 #1868 【微信支付】增加通用上传图片接口,支持传入流和文件名参数
Browse files Browse the repository at this point in the history
  • Loading branch information
f00lish authored Nov 13, 2020
1 parent c605330 commit 30aca49
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 4 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@

import java.io.File;
import java.io.IOException;
import java.io.InputStream;

/**
* <pre>
Expand All @@ -27,5 +28,19 @@ public interface MerchantMediaService {
*/
ImageUploadResult imageUploadV3(File imageFile) throws WxPayException, IOException;

/**
* <pre>
* 通用接口-图片上传API
* 文档详见: https://pay.weixin.qq.com/wiki/doc/apiv3/wxpay/tool/chapter3_1.shtml
* 接口链接:https://api.mch.weixin.qq.com/v3/merchant/media/upload
* </pre>
*
* @param inputStream 需要上传的图片文件流
* @param fileName 需要上传的图片文件名
* @return ImageUploadResult 微信返回的媒体文件标识Id。示例值:6uqyGjGrCf2GtyXP8bxrbuH9-aAoTjH-rKeSl3Lf4_So6kdkQu4w8BYVP3bzLtvR38lxt4PjtCDXsQpzqge_hQEovHzOhsLleGFQVRF-U_0
* @throws WxPayException the wx pay exception
*/
ImageUploadResult imageUploadV3(InputStream inputStream, String fileName) throws WxPayException, IOException;


}
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,7 @@
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.*;
import java.net.URI;

/**
Expand Down Expand Up @@ -41,4 +38,24 @@ public ImageUploadResult imageUploadV3(File imageFile) throws WxPayException,IOE
}
}

@Override
public ImageUploadResult imageUploadV3(InputStream inputStream, String fileName) throws WxPayException, IOException {
String url = String.format("%s/v3/merchant/media/upload", this.payService.getPayBaseUrl());
try(ByteArrayOutputStream bos = new ByteArrayOutputStream()) {
byte[] buffer = new byte[2048];
int len;
while ((len = inputStream.read(buffer)) > -1) {
bos.write(buffer, 0, len);
}
bos.flush();
byte[] data = bos.toByteArray();
String sha256 = DigestUtils.sha256Hex(data);
WechatPayUploadHttpPost request = new WechatPayUploadHttpPost.Builder(URI.create(url))
.withImage(fileName, sha256, new ByteArrayInputStream(data))
.build();
String result = this.payService.postV3(url, request);
return ImageUploadResult.fromJson(result);
}
}

}

0 comments on commit 30aca49

Please sign in to comment.