上传图片

通过微信上传图片换取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 + "\"";//接口URLURL url = new URL("https://api.mch.weixin.qq.com/v3/merchant/media/upload");HttpURLConnection conn = (HttpURLConnection) url.openConnection();// 设置为POSTconn.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);//不需要写完整个文件+尾行后再flushdos.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;}

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

微信支付--上传图片相关推荐

  1. java --微信支付2

    2019独角兽企业重金招聘Python工程师标准>>> 如下是微信支付工具类 package com.readygo.pet.utils;import java.io.Buffere ...

  2. 微信支付来了,微信App来了,微信能力来了

    异常火爆的微信公众平台大会,传达出哪些信息? A-A+ 罗超 2013-11-19 07:07 57 微信腾讯投稿头条 5000人报名,400人参加的微信公众平台合作伙伴大会,异常火爆,连主办方在场外 ...

  3. php官方微信接口大全(微信支付、微信红包、微信摇一摇、微信小店)

    微信入口绑定,微信事件处理,微信API全部操作包含在这些文件中. 内容有:微信摇一摇接口/微信多客服接口/微信支付接口/微信红包接口/微信卡券接口/微信小店接口/JSAPI <?php clas ...

  4. uniapp公众号微信支付

    1.安装jssdk npm install jweixin-module --save 2.调用 <template><viewstyle="width: 100%;hei ...

  5. nodejs微信支付小微商户申请入驻时,如何实现图片上传接口

    微信支付小微商户可以通过小程序<微信买单服务商助手>来进件,也可以通过API接口来进件(详情可查阅小微商户专属接口文档). 通过API接口进件前需要先在商户资料中的身份证照片和门店照片通过 ...

  6. 【Day40】php官方微信接口大全(微信支付、微信红包、微信摇一摇、微信小店)

    微信入口绑定,微信事件处理,微信API全部操作包含在这些文件中. 内容有:微信摇一摇接口/微信多客服接口/微信支付接口/微信红包接口/微信卡券接口/微信小店接口/JSAPI <?phpclass ...

  7. uni-app H5兼容ios问题+微信扫一扫、微信支付等常用api代码封装

    最近公司需要用uni开发一个项目,项目中遇到的问题记录一下,方便下次不采坑 场景:         使用wx自带sdk完成,扫一扫.微信登录.微信支付 引用方式: // index.html引入 &l ...

  8. 个人也能申请微信支付,带回调和分账的那种哦

    1.前言 关于微信电商收付通,之前写过一系列的文章,收录在微信开发-收付通(电商收付通系列⑤,商户进件之二级商户进件申请)模块中,感兴趣的同学可以翻一翻,看一看. 关于合单支付,是怎样一个合单的效果, ...

  9. 千锋Java高级教程+分布式+springcloud+微信支付课程

    课程目录: ├─千锋Java高级教程-cas单点登录(完结-8集) │ 01单点登录介绍 │ 02cas介绍 │ 03tomcat搭建https │ 04cas server搭建 │ 05Cas 配置 ...

最新文章

  1. 活动|跟着微软一起,拥抱开源吧!
  2. redmine 贴图操作
  3. java调度:(二)在项目中调度策略的选择
  4. TypeScript strictness - 严格语法检查
  5. RedHat下JDK1.6安装-利用alternative实现多版本并存(Ubuntu同理)
  6. oracle 全文检索技术
  7. Firefox 使用 Chrome 浏览器的 PDF 和 Flash 插件
  8. 陈冠希宣布代言小野电子烟 罗永浩:实现了长久以来的心愿
  9. 数人云CTO解读Docker 1.12和金融业容器化
  10. 一维搜索斐波那契C语言,斐波那契数列在一维搜索中的应用
  11. ANT发送邮件需要的3个JAR包
  12. java 输入语句_java怎样输入语句
  13. 观看影片《硅谷传奇》
  14. 【零代码工具】15 款企业级零代码开发平台推荐,总有一款是你心仪的
  15. git commit最佳实践:conventional commits
  16. Keil软件简单的使用说明
  17. iOS 仿百度外卖,饿了么-商品列表页
  18. 重磅!谷歌发布《深度学习调优手册》!Hinton转发点赞!
  19. 【读点论文】Masked Autoencoders Are Scalable Vision Learners 完型填空应用到视觉处理上
  20. MM要学会的71个烹饪技巧

热门文章

  1. 用户画像实践:神策标签生产引擎架构
  2. thermal的cpu cool device
  3. 毕业工作大记事【未完待续持续更新。。。。】
  4. 【技术】基于DTEmpower的旋转机械故障诊断
  5. 企业数据的秘密(读后笔记)(大数据)
  6. PR软件+素材+字幕+教程
  7. Win32中调用其他应用程序的方法(函数)winexec,shellexecute ,createprocess
  8. 【基础】开关电源电路图讲解
  9. linux直通卡 盘符漂移_linux盘符漂移问题及解决方案
  10. CAD 启动无法加载配置文件,上次任务中保存的某些配置信 cass主框架程序没有加载