素材巴巴 > 程序开发 >

微信支付-扫码支付案例

程序开发 2023-09-09 11:54:23

下载网址https://pay.weixin.qq.com/wiki/doc/api/native.php?chapter=11_1

下载得到以下压缩包


解压:获得一个maven项目


将此项目导入maven仓库当成一个jar使用,maven项目pom文件引入如下

com.github.wxpaywxpay-sdk0.0.3
                     

准备微信支付参数    

/*** 微信支付参数*/
 public class PayConfig {//企业方公众号Idpublic static String appid = "wx8397f8696b538317";//财付通平台的商户账号public static String partner = "1473426802";//财付通平台的商户密钥public static String partnerkey = "8A627A4578ACE384017C997F12D68B23";  //回调URLpublic static String notifyurl = "http://a31ef7db.ngrok.io/WeChatPay/WeChatPayNotify";
 }

httpclient工具类

package cn.itcast.utils;import java.io.IOException;
 import java.security.GeneralSecurityException;
 import java.security.cert.CertificateException;
 import java.security.cert.X509Certificate;
 import java.text.ParseException;
 import java.util.HashMap;
 import java.util.LinkedList;
 import java.util.List;
 import java.util.Map;import javax.net.ssl.SSLContext;
 import javax.net.ssl.SSLException;
 import javax.net.ssl.SSLSession;
 import javax.net.ssl.SSLSocket;
 import javax.net.ssl.TrustManager;
 import javax.net.ssl.X509TrustManager;import org.apache.http.Consts;
 import org.apache.http.HttpEntity;
 import org.apache.http.NameValuePair;
 import org.apache.http.client.ClientProtocolException;
 import org.apache.http.client.config.RequestConfig;
 import org.apache.http.client.entity.UrlEncodedFormEntity;
 import org.apache.http.client.methods.CloseableHttpResponse;
 import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;
 import org.apache.http.client.methods.HttpGet;
 import org.apache.http.client.methods.HttpPost;
 import org.apache.http.client.methods.HttpPut;
 import org.apache.http.client.methods.HttpUriRequest;
 import org.apache.http.conn.scheme.Scheme;
 import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
 import org.apache.http.conn.ssl.SSLContextBuilder;
 import org.apache.http.conn.ssl.SSLSocketFactory;
 import org.apache.http.conn.ssl.TrustStrategy;
 import org.apache.http.conn.ssl.X509HostnameVerifier;
 import org.apache.http.entity.StringEntity;
 import org.apache.http.impl.client.CloseableHttpClient;
 import org.apache.http.impl.client.DefaultHttpClient;
 import org.apache.http.impl.client.HttpClients;
 import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
 import org.apache.http.message.BasicNameValuePair;
 import org.apache.http.util.EntityUtils;/*** http请求客户端* * @author Administrator* */
 public class HttpClient {private String url;private Map 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 param) {this.url = url;this.param = param;}public HttpClient(String url) {this.url = url;}public void setParameter(Map map) {param = map;}public void addParameter(String key, String value) {if (param == null)param = new HashMap();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 nvps = new LinkedList();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 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;}}
 

页面使用angularjs发送get请求获取返回的数据生成二维码


 
 
 
 Insert title here
 
 
 
 
 请扫码支付
订单号:{{out_trade_no}}


向微信支付远端接口(url)发送xml 数据(https请求,需要证书);并生成二面二维码

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {//向微信支付远端接口(url)  发送xml 数据(https)//1.创建发送的数据(XML)Map prarm=new HashMap();prarm.put("appid", PayConfig.appid);//公众账号IDprarm.put("mch_id",PayConfig.partner);//商户号prarm.put("nonce_str", WXPayUtil.generateNonceStr() );//随机字符串prarm.put("body", "测试商品");//商品信息prarm.put("out_trade_no", WXPayUtil.getCurrentTimestamp()+"");//订单号(后边查询会用)prarm.put("total_fee", "1");//金额(分)prarm.put("spbill_create_ip", "127.0.0.1");//终端IPprarm.put("notify_url",PayConfig.notifyurl);//回调地址(不起作用,但是必须给)prarm.put("trade_type", "NATIVE");//扫码支付try {String xmlParam = WXPayUtil.generateSignedXml(prarm, PayConfig.partnerkey);System.out.println("----请求的参数----");System.out.println(xmlParam);System.out.println("----------------");//2.通过httpClient向远端发送数据String url="https://api.mch.weixin.qq.com/pay/unifiedorder";HttpClient client=new HttpClient(url);client.setHttps(true);client.setXmlParam(xmlParam);client.post();//发送请求//3.获取返回结果(XML)并解析String xmlResult = client.getContent();//请求的结果(XML)System.out.println("----响应的结果-----");System.out.println(xmlResult);System.out.println("-----------------");Map mapResult = WXPayUtil.xmlToMap(xmlResult);Map map=new HashMap();if(mapResult.get("return_code").equals("SUCCESS")){//如果成功map.put("code_url", mapResult.get("code_url"));//生成二维码的urlmap.put("return_code", "SUCCESS");				}else{map.put("code_url", "");map.put("return_code", "ERROR");	}map.put("out_trade_no", prarm.get("out_trade_no"));//订单号String jsonString = JSON.toJSONString(map);response.getWriter().print(jsonString);} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}}

生成二维码后,页面一直监听付款状态,每3秒监听一次,成功跳转页面

微信查询接口 https://api.mch.weixin.qq.com/pay/orderquery

证书不需要

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {String out_trade_no = request.getParameter("out_trade_no");while(true){Map map = queryOrder(out_trade_no);//调用订单接口查询订单信息if(map==null){//出错map = new HashMap();map.put("trade_state", "ERROR");String jsonString = JSON.toJSONString(map);response.getWriter().print(jsonString);break;}if("SUCCESS".equals(map.get("trade_state"))){//支付成功String jsonString = JSON.toJSONString(map);response.getWriter().print(jsonString);break;}try {Thread.sleep(3000);} catch (InterruptedException e) {e.printStackTrace();}}}//调用订单查询接口private Map queryOrder(String out_trade_no){Map param = new HashMap();param.put("appid", PayConfig.appid);param.put("mch_id", PayConfig.partner);param.put("out_trade_no", out_trade_no);param.put("nonce_str", WXPayUtil.generateNonceStr());try {String xmlParam = WXPayUtil.generateSignedXml(param, PayConfig.partnerkey);HttpClient httpClient = new HttpClient("https://api.mch.weixin.qq.com/pay/orderquery");httpClient.setHttps(true);httpClient.setXmlParam(xmlParam);httpClient.post();String resultMap = httpClient.getContent();Map map = WXPayUtil.xmlToMap(resultMap);System.out.println(map);return map ;} catch (Exception e) {e.printStackTrace();return null;}}



                


标签:

上一篇: python 中的数字循环 下一篇:
素材巴巴 Copyright © 2013-2021 http://www.sucaibaba.com/. Some Rights Reserved. 备案号:备案中。