Skip to content

Commit 30aca49

Browse files
authored
🆕 #1868 【微信支付】增加通用上传图片接口,支持传入流和文件名参数
1 parent c605330 commit 30aca49

File tree

2 files changed

+36
-4
lines changed

2 files changed

+36
-4
lines changed

weixin-java-pay/src/main/java/com/github/binarywang/wxpay/service/MerchantMediaService.java

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55

66
import java.io.File;
77
import java.io.IOException;
8+
import java.io.InputStream;
89

910
/**
1011
* <pre>
@@ -27,5 +28,19 @@ public interface MerchantMediaService {
2728
*/
2829
ImageUploadResult imageUploadV3(File imageFile) throws WxPayException, IOException;
2930

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

3146
}

weixin-java-pay/src/main/java/com/github/binarywang/wxpay/service/impl/MerchantMediaServiceImpl.java

Lines changed: 21 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -9,10 +9,7 @@
99
import lombok.extern.slf4j.Slf4j;
1010
import org.apache.commons.codec.digest.DigestUtils;
1111

12-
import java.io.File;
13-
import java.io.FileInputStream;
14-
import java.io.IOException;
15-
import java.io.InputStream;
12+
import java.io.*;
1613
import java.net.URI;
1714

1815
/**
@@ -41,4 +38,24 @@ public ImageUploadResult imageUploadV3(File imageFile) throws WxPayException,IOE
4138
}
4239
}
4340

41+
@Override
42+
public ImageUploadResult imageUploadV3(InputStream inputStream, String fileName) throws WxPayException, IOException {
43+
String url = String.format("%s/v3/merchant/media/upload", this.payService.getPayBaseUrl());
44+
try(ByteArrayOutputStream bos = new ByteArrayOutputStream()) {
45+
byte[] buffer = new byte[2048];
46+
int len;
47+
while ((len = inputStream.read(buffer)) > -1) {
48+
bos.write(buffer, 0, len);
49+
}
50+
bos.flush();
51+
byte[] data = bos.toByteArray();
52+
String sha256 = DigestUtils.sha256Hex(data);
53+
WechatPayUploadHttpPost request = new WechatPayUploadHttpPost.Builder(URI.create(url))
54+
.withImage(fileName, sha256, new ByteArrayInputStream(data))
55+
.build();
56+
String result = this.payService.postV3(url, request);
57+
return ImageUploadResult.fromJson(result);
58+
}
59+
}
60+
4461
}

0 commit comments

Comments
 (0)