当前位置: 首页 > 工具软件 > Dos.WeChat > 使用案例 >

微信支付--上传图片

孔运良
2023-12-01

上传图片

通过微信上传图片换取media_id

public Map<String, Object> getMediaID(WechatUploadCommand command) throws ServiceException, IOException, URISyntaxException {
        Map<String, Object> mmap = new HashMap<>();
        String partnerPrivateKeyUrl = properties.getCertKeyPath("你的商户id");
        //取  -----BEGIN PRIVATE KEY-----   和  -----END PRIVATE KEY-----  之间的内容
        String partnerPrivateKeyPem = CertHttpUtil.getPrivateKeyToFile("你的私钥文件");
					【
						public static String getPrivateKeyToFile(String filename) throws IOException, ServiceException {
							File file = new File(filename);
							if (!file.exists()) {
								throw new ServiceException(ErrorCode.sys_hold_req_param_error, "商户证书文件不存在");
							}
							String content = new String(Files.readAllBytes(Paths.get(filename)), "utf-8");
							String privateKey = content.replace("-----BEGIN PRIVATE KEY-----", "")
									.replace("-----END PRIVATE KEY-----", "")
									.replaceAll("\\s+", "");
							return privateKey;
						}
					】
        String partnerCertNo = "你的商户证书序列号";
        String merchantId = "你的商户id";
        DataOutputStream dos = null;
        InputStream is = null;
        try {
            // 换行符
            //不能使用System.lineSeparator(),linux环境微信会报验签失败
            String lineSeparator = "\r\n";
            String boundary = "boundary";
            //必须为--
            String beforeBoundary = "--";
            //时间戳
            String timestamp = Long.toString(System.currentTimeMillis() / 1000);
            //随机数
            String nonceStr = UUID.randomUUID().toString().replaceAll("-", "");
            File file = command.getFile();
            //文件名
            String filename = System.currentTimeMillis()+ file.getName().substring(file.getName().lastIndexOf("."),file.getName().length());
            is = new FileInputStream(file);
            //文件sha256值
            String fileSha256 = DigestUtils.sha256Hex(is);
            is.close();
            //拼签名串
            StringBuilder sb = new StringBuilder();
            sb.append("POST").append("\n");
            sb.append("/v3/merchant/media/upload").append("\n");
            sb.append(timestamp).append("\n");
            sb.append(nonceStr).append("\n");
            sb.append("{\"filename\":\"").append(filename).append("\",\"sha256\":\"").append(fileSha256).append("\"}").append("\n");
            byte[] bytes = sb.toString().getBytes("utf-8");
            //计算签名
            String sign = CertHttpUtil.signRSA(sb.toString(), partnerPrivateKeyPem);
            //拼装http头的Authorization内容
            String authorization = "WECHATPAY2-SHA256-RSA2048" + " mchid=\"" + merchantId
                    + "\",nonce_str=\"" + nonceStr
                    + "\",signature=\"" + sign
                    + "\",timestamp=\"" + timestamp
                    + "\",serial_no=\"" + partnerCertNo + "\"";
            //接口URL
            URL url = new URL("https://api.mch.weixin.qq.com/v3/merchant/media/upload");
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            // 设置为POST
            conn.setRequestMethod("POST");
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setUseCaches(false);
            // 设置请求头参数
            conn.setRequestProperty("Charsert", "UTF-8");
            conn.setRequestProperty("Accept", "application/json");
            conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
            conn.setRequestProperty("Authorization", authorization);
            dos = new DataOutputStream(conn.getOutputStream());
            //拼装请求内容第一部分
            String metaPart = beforeBoundary + boundary + lineSeparator +
                    "Content-Disposition: form-data; name=\"meta\";" + lineSeparator +
                    "Content-Type: application/json" + lineSeparator + lineSeparator +
                    "{\"filename\":\"" + filename + "\",\"sha256\":\"" + fileSha256 + "\"}" + lineSeparator;
            dos.writeBytes(metaPart);
            dos.flush();
            //拼装请求内容第二部分
            String filePart = beforeBoundary + boundary + lineSeparator +
                    "Content-Disposition: form-data; name=\"file\"; filename=\"" + filename + "\";" + lineSeparator +
                    "Content-Type: image/jpg" + lineSeparator + lineSeparator;
            dos.writeBytes(filePart);
            dos.flush();
            //文件二进制内容
            byte[] buffer = new byte[1024];
            int len;
            is = new FileInputStream(file);
            while ((len = is.read(buffer)) != -1) {
                dos.write(buffer, 0, len);
                //不需要写完整个文件+尾行后再flush
                dos.flush();
            }
            is.close();
            //拼装请求内容结尾
            String endLine = lineSeparator
                    + beforeBoundary
                    + boundary
                    //必须,标识请求体结束
                    + "--"
                    + lineSeparator;
            dos.writeBytes(endLine);
            dos.flush();
            dos.close();
            FileUtil.del(file);
            //接收返回
            //打印返回头信息
            StringBuilder respHeaders = new StringBuilder();
            Map<String, List<String>> responseHeader = conn.getHeaderFields();
            for (Map.Entry<String, List<String>> entry : responseHeader.entrySet()) {
                respHeaders.append(lineSeparator).append(entry.getKey()).append(":").append(entry.getValue());
            }
            //打印返回内容
            int responseCode = conn.getResponseCode();
            //应答报文主体
            String rescontent;
            if ((responseCode + "").equals("200")) {
                rescontent = new String(CertHttpUtil.InputStreamTOByte(conn.getInputStream()));
                log.info("微信上传图片换取的值{}",rescontent);
                mmap = JSON.parseObject(rescontent);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (is != null) {
                    is.close();
                }
                if (dos != null) {
                    dos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return mmap;
    }

大佬勿喷,欢迎提意见建议评论!!!!

 类似资料: