使用微信支付接口生成支付二维码

  1. 下载微信支付提供的SDK, 下载完后打开源码,install 到本地仓库。
    使用微信支付接口生成支付二维码_第1张图片

  2. 使用微信支付 SDK,在 maven 工程中引入依赖

 
 	 	com.github.wxpay 
 	 	wxpay-sdk 
 	 	0.0.3 
  

  1. 主要会用到微信支付 SDK 的以下功能:
    (1) 获取随机字符串
    WXPayUtil.generateNonceStr()
    (2) MAP 转换为 XML 字符串(自动添加签名)
    WXPayUtil.generateSignedXml(param, partnerkey)
    (3) XML 字符串转换为 MAP
    WXPayUtil.xmlToMap(result)

HttpClient 工具类

package 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;


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("?");
				else
					url.append("&");
				url.append(key).append("=").append(param.get(key));
			}
			this.url = url.toString();
		}
		HttpGet http = new HttpGet(url);
		execute(http);
	}


	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;
	}

}

(1) HttpClient 通俗的讲就是模拟了浏览器的行为,如果我们需要在后端向某一地址提交数据获取结果,就可以使用 HttpClient.

(2)HttpClient 工具类使用的步骤

HttpClient client=new HttpClient(请求的url地址); 
client.setHttps(true);//是否是https协议 
client.setXmlParam(xmlParam);//发送的xml数据 
client.post();//执行post请求 
String result = client.getContent(); //获取结果 

工程搭建

引入打包好的SDK依赖 , 和HttpClient

	 
 	 	com.github.wxpay 
 	 	wxpay-sdk 
 	 	0.0.3  	
 	  
 	   
 	    	org.apache.httpcomponents 
 	    	httpclient     	 
 	   

 	//1.调用远程接口
		HttpClient client = new HttpClient("https://api.mch.weixin.qq.com/pay/unifiedorder");
		//设置传输协议
		client.setHttps(true);
		//设置传递的参数
		Map map = new HashMap<>();
		//微信公众账号
		map.put("appid",appid);
		//商户号
		map.put("mch_id",mch_id);
		//微信工具类提供的生成随机字符串
		map.put("nonce_str",WXPayUtil.generateNonceStr());
		//页面显示的名称,自己的公司名
		map.put("body","baidu");
		//加密方式,默认是MD5
		map.put("sign_type","MD5");
		//out_trade_no为自己生成的商品订单号
		map.put("out_trade_no",out_trade_no);
		//微信支付是以分为单位,不能有小数点
		map.put("total_fee",1);
		//IP地址
		map.put("spbill_create_ip","127.0.0.1");
		//回调地址,随便配
		map.put("notify_url","https://www.baidu.com");
		//交易类型
		param.put("trade_type", "NATIVE");
		
		
		//将map转成带有签名的XML,微信工具类提供
		try {
			String xmlParam = WXPayUtil.generateSignedXml(map,partnerkey);
			//发送数据
			System.out.println("发送数据"+xmlParam);
			client.setXmlParam(xmlParam);
			client.post();
			//获取返回结果
			String content = client.getContent();
			System.out.println("返回结果"+content);
			Map resultMap = WXPayUtil.xmlToMap(content);
			
			
			//返回数据生成二维码
			Map codeMap = new HashMap<>();
			// " code_url " 就是微信支付路径
			codeMap.put("code_url",resultMap.get("code_url"));
			codeMap.put("out_trade_no",out_trade_no);
			codeMap.put("total_fee",total_fee);
			//页面接受返回的路径和金额,设置到二维码生成工具中即可
			return codeMap;
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			return new HashMap<>();
		}

你可能感兴趣的:(使用微信支付接口生成支付二维码)