微信小程序支付

微信支付小程序开发文档

开发q钱需要准备

String appid;//小程序appid   
String partner;//小程序关联的商户号 
String partnerkey;//商户号的秘钥  
String openid;//用户标示
 /**
     *  创建微信预订单信息,发起支付
     * @param outTradeNo//订单号
     * @return java.util.Map
     */
    @Override
    public Map create( String outTradeNo) throws Exception {
        //1.参数封装
        Map param = new HashMap();
        //公众账号ID   小程序appid
        param.put("appid", 小程序appid);//填写小程序appid
        //商户号 小程序关联的商户号
        param.put("mch_id", 小程序关联的商户号);//填写小程序关联的商户号
        //随机字符串
        param.put("nonce_str", WXPayUtil.generateNonceStr());
        param.put("body", 支付描述);
        //交易订单号
        param.put("out_trade_no", outTradeNo);
        //金额(分)
        param.put("total_fee", String.valueOf(orderPay.getAcount().multiply(new BigDecimal(100)).intValue()));
        param.put("spbill_create_ip", "127.0.0.1");
        String requestUrl = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
                + request.getContextPath();
        logger.info("服务器地址" + requestUrl);//用于支付成功微信回调 修改订单信息或其他逻辑 建议https
        param.put("notify_url", requestUrl + "/pay/wechat/notify");
        //交易类型
        param.put("trade_type", "JSAPI");
        //用户标示
        param.put("openid", 小程序openid);

        try {
            String xmlParam = WXPayUtil.generateSignedXml(param, "9581F03F87304CE784C13D2F190E07EE");
            System.out.println("请求的参数:" + xmlParam);

            //2.发送请求
            HttpClient httpClient = new HttpClient("https://api.mch.weixin.qq.com/pay/unifiedorder");
            httpClient.setHttps(true);
            httpClient.setXmlParam(xmlParam);
            httpClient.post();

            //3.获取结果
            String xmlResult = httpClient.getContent();
            Map<String, String> mapResult = WXPayUtil.xmlToMap(xmlResult);
            System.out.println("微信返回结果" + mapResult);
            //返回前端数据
            if (mapResult.get("return_code").equals("SUCCESS")) {
                //返回给APP端的参数,APP端再调起支付接口
                Map<String, String> repData = new HashMap<>();
                repData.put("appId", 小程序appid);//

                String packag = "prepay_id=" + mapResult.get("prepay_id");

                repData.put("package", packag);
                repData.put("signType", "MD5");
                repData.put("nonceStr", WXPayUtil.generateNonceStr());
                repData.put("timeStamp", String.valueOf(System.currentTimeMillis() / 1000));
                repData.put("prepayid", mapResult.get("prepay_id"));
                repData.put("mch_id", 小程序关联的商户号);
                //签名
                String sign = WXPayUtil.generateSignature(repData, 商户号的秘钥);//商户号的秘钥
                repData.put("sign", sign);
                repData.put("timestamp", repData.get("timeStamp"));
                return repData;
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return new HashMap();
    }

所用到的jar包

	<dependency>
			<groupId>com.github.wxpaygroupId>
			<artifactId>wxpay-sdkartifactId>
			<version>0.0.3version>
		dependency>

所用到的工具类HttpClient

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.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.*;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContextBuilder;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import javax.net.ssl.SSLContext;
import java.io.IOException;
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;

/**
 * http请求客户端
 * 
 * @author lgc
 * 
 */
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("?");
				else
					url.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 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;
	}

}

你可能感兴趣的:(微信支付,java)