diff --git a/weixin-java-pay/src/main/java/com/github/binarywang/wxpay/service/MerchantMediaService.java b/weixin-java-pay/src/main/java/com/github/binarywang/wxpay/service/MerchantMediaService.java index 429ece394d..0e35dbb68b 100644 --- a/weixin-java-pay/src/main/java/com/github/binarywang/wxpay/service/MerchantMediaService.java +++ b/weixin-java-pay/src/main/java/com/github/binarywang/wxpay/service/MerchantMediaService.java @@ -5,6 +5,7 @@ import java.io.File; import java.io.IOException; +import java.io.InputStream; /** *
@@ -27,5 +28,19 @@ public interface MerchantMediaService { */ ImageUploadResult imageUploadV3(File imageFile) throws WxPayException, IOException; + /** + *+ * 通用接口-图片上传API + * 文档详见: https://pay.weixin.qq.com/wiki/doc/apiv3/wxpay/tool/chapter3_1.shtml + * 接口链接:https://api.mch.weixin.qq.com/v3/merchant/media/upload + *+ * + * @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; + } diff --git a/weixin-java-pay/src/main/java/com/github/binarywang/wxpay/service/impl/MerchantMediaServiceImpl.java b/weixin-java-pay/src/main/java/com/github/binarywang/wxpay/service/impl/MerchantMediaServiceImpl.java index 863b706a28..811d61f6b5 100644 --- a/weixin-java-pay/src/main/java/com/github/binarywang/wxpay/service/impl/MerchantMediaServiceImpl.java +++ b/weixin-java-pay/src/main/java/com/github/binarywang/wxpay/service/impl/MerchantMediaServiceImpl.java @@ -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; /** @@ -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); + } + } + }