小白第一次使用微信支付,刚开始也是比较苦恼,总的来说呢,就是看懂流程,会调用API接口,所以我认为,小白还是看看官方微信支付文档还是有必要的
[ http://kf.qq.com/faq/161222NneAJf161222U7fARv.html ]
微信支付有很多中方式,学习从一点一滴开始,我相信积少成多,总能达到我们想要的效果!
对于不同的支付方式,其实他们所使用的也就是那一套API,只要会调用API,其他的结合业务,有问题,再去解决!
API的调用其实就是, 它(微信服务)需要什么参数,参数是什么格式, 我们就封装好参数格式, 它提供什么借接口URL,我们就调用它的URL,文档中写的也很清除. 我们获取 调用结果,处理我们自己所需要的逻辑即可!
总结: 封装参数 ; 发起请求; 获取结果。
本人是自己搭建了一个maven Demo来实现这些接口的简单调用,
后续会进行代码分享。
下面就开始我们的第一个api,统一下单接口的使用,GO,GO,GO!

1.了解接口使用信息

2. 搭建我们的工程

多的不说,如果想要仔细了解怎么搭建工程,可以去看我篇整合shiro的文章,有很详细的搭建 [ https://blog.csdn.net/qq_34898847/article/details/81983221 ]

# 1. 导入jar包

     <properties><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding><spring.version>4.0.0.RELEASE</spring.version><version.jackson>2.4.4</version.jackson><org.mybatis.vsersion>3.3.0</org.mybatis.vsersion><org.mybatis.spring>1.2.3</org.mybatis.spring><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding><maven.compiler.encoding>UTF-8</maven.compiler.encoding>
</properties>
<dependencies><dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>3.8.1</version><scope>test</scope></dependency><!-- spring的依赖包 --><dependency><groupId>org.springframework</groupId><artifactId>spring-core</artifactId><version>${spring.version}</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-web</artifactId><version>${spring.version}</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-oxm</artifactId><version>${spring.version}</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-tx</artifactId><version>${spring.version}</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-jdbc</artifactId><version>${spring.version}</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-webmvc</artifactId><version>${spring.version}</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-aop</artifactId><version>${spring.version}</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-context-support</artifactId><version>${spring.version}</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-test</artifactId><version>${spring.version}</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-web</artifactId><version>${spring.version}</version></dependency><dependency><groupId>com.google.code.gson</groupId><artifactId>gson</artifactId><version>2.3.1</version></dependency><dependency><groupId>javax.servlet</groupId><artifactId>jstl</artifactId><version>1.2</version></dependency><dependency><groupId>net.sf.json-lib</groupId><artifactId>json-lib</artifactId><version>2.4</version><classifier>jdk15</classifier></dependency><dependency><groupId>com.alibaba</groupId><artifactId>fastjson</artifactId><version>1.2.28</version></dependency><dependency><groupId>javassist</groupId><artifactId>javassist</artifactId><version>3.11.0.GA</version></dependency><dependency><groupId>commons-codec</groupId><artifactId>commons-codec</artifactId><version>1.10</version></dependency><dependency><groupId>javax.servlet</groupId><artifactId>servlet-api</artifactId><version>2.5</version><scope>provided</scope></dependency><dependency><groupId>org.slf4j</groupId><artifactId>slf4j-api</artifactId><version>1.7.25</version></dependency><!-- 微信 --><dependency><groupId>com.github.wxpay</groupId><artifactId>wxpay-sdk</artifactId><version>0.0.3</version></dependency><dependency><groupId>org.apache.httpcomponents</groupId><artifactId>httpcore</artifactId><version>4.4.4</version></dependency><dependency><groupId>org.apache.httpcomponents</groupId><artifactId>httpclient</artifactId><version>4.5.3</version></dependency><dependency><groupId>dom4j</groupId><artifactId>dom4j</artifactId><version>1.6.1</version></dependency><dependency><groupId>xml-apis</groupId><artifactId>xml-apis</artifactId><version>1.4.01</version></dependency></dependencies><build><finalName>WeixinDemo02</finalName><resources><resource><directory>src/main/resources</directory><includes><include>**/*</include></includes><filtering>true</filtering></resource></resources><plugins><plugin><artifactId>maven-compiler-plugin</artifactId><version>3.1</version><configuration><source>1.8</source><target>1.8</target><encoding>UTF-8</encoding><compilerArguments><bootclasspath>${java.home}/lib/rt.jar</bootclasspath></compilerArguments></configuration></plugin></plugins>
</build>

其中包括上使用了微信自己封装的工具jar, 很方便,WXPayUtils ,当然你也可以自己去封装实现, 签名方法,xml与map,map与xml的相互转换.
其实最开始的时候,网上看的好多都是自己封装的什么方法,我也很蒙啊,自己也封装不好.

2. 封装一个发起请求链接的工具类

/*** http请求客户端* * @author Administrator* */
public class HttpClient {private String url;private Map<String, String> param;private int statusCode;private String content;private String xmlParam;private boolean isHttps;public boolean isHttps() {return isHttps;}public void setHttps(boolean isHttps) {this.isHttps = isHttps;}public String getXmlParam() {return xmlParam;}public void setXmlParam(String xmlParam) {this.xmlParam = xmlParam;}public HttpClient(String url, Map<String, String> param) {this.url = url;this.param = param;}public HttpClient(String url) {this.url = url;}public void setParameter(Map<String, String> map) {param = map;}public void addParameter(String key, String value) {if (param == null)param = new HashMap<String, String>();param.put(key, value);}public void post() throws ClientProtocolException, IOException {HttpPost http = new HttpPost(url);setEntity(http);execute(http);}public void put() throws ClientProtocolException, IOException {HttpPut http = new HttpPut(url);setEntity(http);execute(http);}public void get() throws ClientProtocolException, IOException {if (param != null) {StringBuilder url = new StringBuilder(this.url);boolean isFirst = true;for (String key : param.keySet()) {if (isFirst)url.append("?");elseurl.append("&");url.append(key).append("=").append(param.get(key));}this.url = url.toString();}HttpGet http = new HttpGet(url);execute(http);}/*** set http post,put param*/private void setEntity(HttpEntityEnclosingRequestBase http) {if (param != null) {List<NameValuePair> nvps = new LinkedList<NameValuePair>();for (String key : param.keySet())nvps.add(new BasicNameValuePair(key, param.get(key))); // 参数http.setEntity(new UrlEncodedFormEntity(nvps, Consts.UTF_8)); // 设置参数}if (xmlParam != null) {http.setEntity(new StringEntity(xmlParam, Consts.UTF_8));}}private void execute(HttpUriRequest http) throws ClientProtocolException,IOException {CloseableHttpClient httpClient = null;try {if (isHttps) {SSLContext sslContext = new org.apache.http.ssl.SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {// 信任所有public boolean isTrusted(X509Certificate[] chain,String authType)throws CertificateException {return true;}}).build();SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext);httpClient = HttpClients.custom().setSSLSocketFactory(sslsf).build();} else {httpClient = HttpClients.createDefault();}CloseableHttpResponse response = httpClient.execute(http);try {if (response != null) {if (response.getStatusLine() != null)statusCode = response.getStatusLine().getStatusCode();HttpEntity entity = response.getEntity();// 响应内容content = EntityUtils.toString(entity, Consts.UTF_8);}} finally {response.close();}} catch (Exception e) {e.printStackTrace();} finally {httpClient.close();}}public int getStatusCode() {return statusCode;}public String getContent() throws ParseException, IOException {return content;}/*** 获取用户实际ip* @param request* @return*/public static String getIpAddr(HttpServletRequest request){  String ipAddress = request.getHeader("x-forwarded-for");  if(ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {  ipAddress = request.getHeader("Proxy-Client-IP");  }  if(ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {  ipAddress = request.getHeader("WL-Proxy-Client-IP");  }  if(ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {  ipAddress = request.getRemoteAddr();  if(ipAddress.equals("127.0.0.1") || ipAddress.equals("0:0:0:0:0:0:0:1")){  //根据网卡取本机配置的IP  InetAddress inet=null;  try {  inet = InetAddress.getLocalHost();  } catch (UnknownHostException e) {  e.printStackTrace();  }  ipAddress= inet.getHostAddress();  }  }  //对于通过多个代理的情况,第一个IP为客户端真实IP,多个IP按照','分割  if(ipAddress!=null && ipAddress.length()>15){ //"***.***.***.***".length() = 15  if(ipAddress.indexOf(",")>0){  ipAddress = ipAddress.substring(0,ipAddress.indexOf(","));  }  }  return ipAddress;   }}

3. 封装一个需要的参数类,就是申请支付啊,接口地址啊,啥的

 /*** 微信初始化参数的类* @author xzb_l**/public class PayConfig {// 微信号,public static String APP_ID = "申请微信支付后可以获得的";// 应用对应的凭证public static String APP_SECRET = "申请微信支付后可以获得的";// 商户密钥public static String API_KEY = "申请微信支付后可以获得的";// 商业号public static String MCH_ID = "申请微信支付后可以获得的";// 回调地址public static String NOTIFY_URL = "http://127.0.0.1/WeixinDemo02";//微信支付h5 回调地址//public static String NOTIFY_URL_H5 = "http://localhostUrl/resourceManager/xxxxxx?userid=";public static String NOTIFY_URL_H5 = "http://127.0.0.1/WeixinDemo02/H5/payNotify";// 商品名称public static String BODY = "我是测试数据-007 ";// 请求地址public static String UFDODER_URL = "https://api.mch.weixin.qq.com/pay/unifiedorder";// 微信支付V2账单查询接口public static String ORDERQUERY = "https://api.mch.weixin.qq.com/pay/orderquery";// 微信支付场景地址:WAP网站URL地址,可为项目地址public static String WAP_URL = "http://127.0.0.1/WeixinDemo02/";// 关闭订单public static String CLOSEORDER = "https://api.mch.weixin.qq.com/pay/closeorder";}

4. 统一下单接口方法

 /*** 调用统一下单,并获取支付跳转链接* @param total_fee    支付金额* @param out_trade_no 商户订单号* @param ip    客户ip* @return*/public Map<String,String> payH5(String total_fee, String out_trade_no, String ip){// 封装需要的信息Map<String, String> payMap = new HashMap<String, String>();try {// 1. 拼接下单地址参数Map<String,String> param = new HashMap<String,String>();param.put("appid", PayConfig.APP_ID); // 公总号IDparam.put("mch_id", PayConfig.MCH_ID); // 商户号IDparam.put("nonce_str", WXPayUtil.generateNonceStr());  // 随机字符串param.put("body", "我是H5支付测试商品") ;// 商品描述param.put("out_trade_no", out_trade_no); // 商户订单号param.put("total_fee", total_fee);//金额(分)param.put("spbill_create_ip", ip); // 商户终端ipparam.put("notify_url", PayConfig.NOTIFY_URL_H5); // H5微信异步通知回调地址param.put("trade_type", "MWEB"); // H5支付类型String scene_info = "{\"h5_info\":{\"type\":\"Wap\",\"wap_url\":"+PayConfig.WAP_URL+",\"wap_name\": \"APP名字,我没想好\"}}";param.put("scene_info", scene_info); // 需要支付的场景信息;有几种方式,参考文档// 生成签名,官方默认MD5+商户秘钥+参数信息String sign = WXPayUtil.generateSignature(param, PayConfig.API_KEY);param.put("sign", sign);// 将所有参数转换为xml形式String xmlParam = WXPayUtil.mapToXml(param);// 2. 发送请求//String xmlStr = HttpRequest.sendPost(unifiedorder_url, xml);//发送post请求"统一下单接口"HttpClient httpClient = new HttpClient(PayConfig.UFDODER_URL);httpClient.setHttps(true);// https协议httpClient.setXmlParam(xmlParam);httpClient.post();// 获取结果String xmlResult = httpClient.getContent();//以下内容是返回前端页面的json数据String mweb_url = "";//跳转链接if (xmlResult.indexOf("SUCCESS") != -1) {  // 只要执行了下发接口,都会包含SUCCESS的Map<String, String> map = WXPayUtil.xmlToMap(xmlResult);//mweb_url为拉起微信支付收银台的中间页面,可通过访问该url来拉起微信客户端,完成支付,mweb_url的有效期为5分钟。mweb_url = (String) map.get("mweb_url");  //支付完返回浏览器跳转的地址,如跳到查看订单页面String redirect_url = "http://www.zzw777.com/";String redirect_urlEncode =  URLEncoder.encode(redirect_url,"utf-8");//对上面地址urlencodemweb_url = mweb_url + "&redirect_url=" + redirect_urlEncode;//拼接返回地址} else {System.out.println("统一支付接口获取预支付订单出错");payMap.put("msg", "支付失败");return payMap;}payMap.put("mweb_url", mweb_url);payMap.put("out_trade_no", out_trade_no);payMap.put("total_fee", total_fee);} catch (Exception e) {e.printStackTrace();System.out.println("统一支付接口获取预支付订单出错");payMap.put("msg", "系统支付错误");return payMap;}//添加微信支付记录日志等操作payMap.put("msg", "success");return payMap;}

这个方法就是根据封装参数,发起请求,获取结果, 如果你想做其他操作,都可以写自己的业务逻辑代码! 这样基本这个几口就OK啦!!!

微信支付接口调用之统一下单(一)相关推荐

  1. 微信支付报错:统一下单和拉起支付的appid不一致(原创)

    微信支付报错:统一下单和拉起支付的appid不一致 错误码:-2 提示参考: 参考统一下单的API (谦信君原创,转载请注明来源) 原因排查: 我们做的是APP微信支付 客户端向我服务端发请求,获取预 ...

  2. 微信支付常见错误和统一下单错误码详情

    微信支付常见错误和统一下单错误码详情 微信支付常见问题描述及解决方法 微信调用统一下单接口,当result_code=FAIL时,错误代码及错误描述 参考链接: 微信支付常见问题描述及解决方法 序号 ...

  3. 微信小程序PHP 微信支付接口调用

    小程序端  js数据处理 根据官方文档配置好参数,传入服务器. /*** 微信支付接口*/wxPaymoney:function (out_trade_no, true_money){ //out_t ...

  4. 微信统一下单 java_微信支付(java版本)_统一下单

    最近工作接触到微信支付,刚开始解决微信支付很神秘,接触之后发现并没有那么神秘,就是有很多坑,在开发的时候需要注意,整理出来: 1.准备工作 首先需要登录微信支付公众平台阅读接口文档,地址:https: ...

  5. 微信支付接口调用问题(android正常,iphone调不起)

    碰到的问题 :根据微信提供的示例代码(ASP.NET),配置好一切后, 用android微信客户端返回,调起支付接口一切正常, 但使用iphone微信客户端时,点击"立即支付"按钮 ...

  6. 微信支付接口调用之二维码失效时间的设置

    今天解决了测试提交上来的一个bug,说是公司网站调用的二维码接口没有做超时失效处理,这种情况容易导致用户账号登出后,该二维码还是有效的,当用户扫描支付时还是能够支付成功,但是微信支付成功后调用我们配置 ...

  7. 微信支付API3 APP【统一下单 APIV3】

    官方参考资料 签名:签名生成-接口规则 | 微信支付商户平台文档中心 签名生成:签名生成 - WechatPay-API-v3 统一下单接口:微信支付-开发者文档 如何查看证书序列号:证书相关 - W ...

  8. 微信支付接口调用记录

    1. totalmoney 必须是不带小数的,默认单位是分  ,如 你付款0.01元,传到后端要*100单位变为分,然后 强转整数 2. 支付异步回调,做出判断,如果订单已经处理过,就不让执行业务代码 ...

  9. php h5微信公众号支付接口,微信公众号H5支付接口调用方法

    本文实例为大家分享了 微信内h5调用支付接口的具体代码,供大家参考,具体内容如下 官方文档 微信公众号h5接口调用 // 判断微信版本是否在5.0以上 // window.navigator.user ...

  10. 微信支付接口,提示:调用支付jsapi缺少参数: $key0$

    下面是 官方给的 帮助文档. 支付返回签名错误 注意签名参数的大小写,支付密钥key要到商户平台设置,设置的规则是32位数字与字母大小写的组合.以下链接为签名过程. (https://pay.weix ...

最新文章

  1. 利用FreeNas创建iSCSI块级存储
  2. 网站建设中这些图片优化小技巧需掌握
  3. 把2018年所有踩过的坑都记在这里。
  4. ERROR 1205 (HY000): Lock wait timeout exceeded; try restarting transaction
  5. 2016谷歌官方最新eclipse工程导入studio,以前方式全部废弃。不能再使用。
  6. php 正则获取html标签,php正则取嵌套html标签
  7. ffmpeg 使用ffplay 进行 hls 拉流 分析 1
  8. IDEA中Alt + Insert快捷键定制生成类方法
  9. prism项目搭建 wpf_Prism 源码解读1-Bootstrapper和Region的创建
  10. ArcGIS 10.2数字化线状要素时自己主动拼接成一条线
  11. Linux -- ×××服务简绍、配置及应用(2)
  12. oracle 自定义比较函数
  13. Jmeter基础教程
  14. uni-app实现一键登录
  15. 实战linux内核精简
  16. 关于SPING与EJB的胡言乱语
  17. 【我的渲染技术进阶之旅】你可能永远猜不到为什么Filament项目命名为TNT?
  18. 2021届 大疆一面 嵌入式软件
  19. 拉格朗日插值法及应用
  20. KEIL新建STM32F030F工程文件

热门文章

  1. 配眼镜走过的那些坑。
  2. 哈佛邓云天:Cascaded Text Generation with Markov Transformers
  3. movsw 汇编_汇编指令之ADC、SBB、XCHG、MOVS指令
  4. Matlab下载安装详细教程
  5. html图片、背景音乐、滚动文字
  6. 5镜头手机来了!Nokia 9 PureView可能价格是最贵
  7. 奥本大学计算机专业GRE成绩,美国大学GRE分数要求汇总贴,你的目标学校要求多少分?...
  8. 什么是DTU?DTU的作用是什么?
  9. android 状态栏为白色的时候图标不显示的解决方案
  10. html注册cab包,OCX控件打包成CAB并实现数字签名过程