微信支付

微信支付上传的图片需要通过提供的API先上传下,然后获取一个Id来使用

https://pay.weixin.qq.com/wiki/doc/apiv3_partner/apis/chapter2_1_1.shtml

image-1679880248662

官方提供的接口Java实现

按照这个代码写,调多久都是不行的,因为这个还要先过下认证,微信接口真是XXXXXX

image-1679880299701

String filePath = "/your/home/hellokitty.png";
URI uri = new URI("https://api.mch.weixin.qq.com/v3/merchant/media/upload");
File file = new File(filePath);

try (FileInputStream ins1 = new FileInputStream(file)) { 
  String sha256 = DigestUtils.sha256Hex(ins1);
  try (InputStream ins2 = new FileInputStream(file)) {
    HttpPost request = new WechatPayUploadHttpPost.Builder(uri)
        .withImage(file.getName(), sha256, ins2)
        .build();
    CloseableHttpResponse response1 = httpClient.execute(request);
  }
}
认证接口

需要先使用微信提供的微信认证接口完成下身份认证

	public static String weChatUploadImage(String imgUrl) throws Exception {

		//首先通过你的参数进行微信认证
		PrivateKey merchantPrivateKey = getPrivateKey("这里是你的商户API私钥地址");
		URIBuilder uriBuilder = new URIBuilder("https://api.mch.weixin.qq.com/v3/certificates");
		HttpGet httpGet = new HttpGet(uriBuilder.build());
		httpGet.addHeader("Accept", "application/json");
		httpGet.addHeader("User-Agent", "https://zh.wikipedia.org/wiki/User_agent");
		CloseableHttpClient httpClient = WechatPayHttpClientBuilder.create()
				.withMerchant("服务商商户号", "服务商API证书序列号", merchantPrivateKey)
				.withValidator(response->true) // NOTE: 设置一个空的应答签名验证器,**不要**用在业务请求
				.build();

		URI uri = new URI("https://api.mch.weixin.qq.com/v3/merchant/media/upload");

		File file = UrltoFile(imgUrl);

		try (FileInputStream ins1 = new FileInputStream(file)) {
			String sha256 = DigestUtils.sha256Hex(ins1);
			try (InputStream ins2 = new FileInputStream(file)) {
				HttpPost request = new WechatPayUploadHttpPost.Builder(uri)
						.withImage(file.getName(), sha256, ins2)
						.build();

				CloseableHttpResponse response1 = httpClient.execute(request);

				String bodyAsString = EntityUtils.toString(response1.getEntity());
				com.alibaba.fastjson.JSONObject jsonObject = JSON.parseObject(bodyAsString);

				return jsonObject.getString("media_id");
			}
		}

	}
    
    	//将Url转换为File,因为微信仅支持file类型作为输入,我这里使用的是网络url这里需要进行转换
	private static File UrltoFile(String url) throws Exception {
		HttpURLConnection httpUrl = (HttpURLConnection) new URL(url).openConnection();
		httpUrl.connect();
		InputStream ins = httpUrl.getInputStream();

		String str = url.substring(url.length() - 10);
		String str1 = str.substring(str.indexOf("."));

		File file = new File(System.getProperty("java.io.tmpdir") + File.separator + "nanwish" + str1);
		if (file.exists()) {
			file.delete();//如果缓存中存在该文件就删除
		}
		OutputStream os = new FileOutputStream(file);
		int bytesRead;
		int len = 8192;
		byte[] buffer = new byte[len];
		while ((bytesRead = ins.read(buffer, 0, len)) != - 1) {
			os.write(buffer, 0, bytesRead);
		}
		os.close();
		ins.close();
		return file;

	}
调用接口获取微信的图片Id

image-1679880128097

获取到返回的微信照片Id

image-1679880197836