Java微信支付流程後臺代碼

一、微信支付的流程圖如下(微信官網流程如下):


二、支付步驟如下

1、小程序調用wx.login() 獲取 臨時登錄憑證code ,併發送到開發者服務器(後臺代碼)。

2、開發者服務器以code換取 用戶唯一標識openid 和 會話密鑰session_key,通過調用接口來獲取,接口名和參數值如下:

接口地址:

https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET&js_code=JSCODE&grant_type=authorization_code

參數說明:appid 小程序的唯一標識、secret 小程序的app secret、js_code 爲前端傳入的code值、grant_type 填寫值爲authorization_code即可。***注意所有參數都爲必填***

後端代碼如下:

HttpGet httpGet = new HttpGet("https://api.weixin.qq.com/sns/jscode2session?appid="+Configure.getAppID()+"&secret="+Configure.getSecret()+"&js_code="+code+"&grant_type=authorization_code");
        HttpClient httpClient = HttpClients.createDefault();
        HttpResponse res = httpClient.execute(httpGet);
       
        HttpEntity entity = res.getEntity();
        String result = EntityUtils.toString(entity, "UTF-8");

appid、secret等這樣的值一般配置在類中的常量值,方便後續的複用。

3、後臺調用統一下單接口

接口地址:URL地址:https://api.mch.weixin.qq.com/pay/unifiedorder

參數列表如官網所示:



除了必填參數外,其他可選參數根據自己的實際情況添加:

//生成商戶訂單  調用unifiedorder得到 prepay_id 
        JSONObject json = new JSONObject();;
        try {
        	JSONObject json_test = JSONObject.parseObject(result);
        	String openid = json_test.getString("openid");
			OrderInfo order = new OrderInfo();
			order.setAppid(Configure.getAppID());
			order.setMch_id(Configure.getMch_id());
			order.setNonce_str(RandomStringGenerator.getRandomStringByLength(32));
			order.setBody("錦官商城");
			order.setOut_trade_no(RandomStringGenerator.getRandomStringByLength(32));
			order.setTotal_fee(1);
			order.setSpbill_create_ip("111.231.203.XXX");
			order.setNotify_url("www.entomb/payResult");//通知地址
			order.setTrade_type("JSAPI");
			order.setOpenid(openid);
			order.setSign_type("MD5");
			//生成簽名
			String sign = Signature.getSign(order);
			order.setSign(sign);
			
			
			String result1 = HttpRequest.sendPost("https://api.mch.weixin.qq.com/pay/unifiedorder", order);
			System.out.println("result1111: "+result1);
			xStream.alias("xml", OrderReturnInfo.class); 
//			OrderReturnInfo returnInfo = (OrderReturnInfo)xStream.fromXML(result1);
//			result1=result1.toString();
//			OrderReturnInfo returnInfo =XStreamTool.fromXML(result1,xStream);

			int slen=result1.lastIndexOf("<prepay_id><![CDATA[");
			int elen=result1.lastIndexOf("]]></prepay_id>");
			String prepay_id=result1.substring(slen+20, elen);
//			json.put("prepay_id", returnInfo.getPrepay_id());
			json.put("prepay_id", prepay_id);
		} catch (Exception e) {
			e.printStackTrace();
		}

註釋部分可以根據自己的情況選用,因爲我的程序環境問題不能使用該代碼得到prepay_id


示例(官網)根據自己的小程序值修改爲自己相對應的值:

<xml>
   <appid>wx2421b1c4370ec43b</appid>
   <attach>支付測試</attach>
   <body>JSAPI支付測試</body>
   <mch_id>10000100</mch_id>
   <detail><![CDATA[{ "goods_detail":[ { "goods_id":"iphone6s_16G", "wxpay_goods_id":"1001", "goods_name":"iPhone6s 16G", "quantity":1, "price":528800, "goods_category":"123456", "body":"蘋果手機" }, { "goods_id":"iphone6s_32G", "wxpay_goods_id":"1002", "goods_name":"iPhone6s 32G", "quantity":1, "price":608800, "goods_category":"123789", "body":"蘋果手機" } ] }]]></detail>
   <nonce_str>1add1a30ac87aa2db72f57a2375d8fec</nonce_str>
   <notify_url>http://wxpay.wxutil.com/pub_v2/pay/notify.v2.php</notify_url>
   <openid>oUpF8uMuAJO_M2pxb1Q9zNjWeS6o</openid>
   <out_trade_no>1415659990</out_trade_no>
   <spbill_create_ip>14.23.150.211</spbill_create_ip>
   <total_fee>1</total_fee>
   <trade_type>JSAPI</trade_type>
   <sign>0CB01533B8C1EF103065174F50BCA001</sign>

</xml>

***參數的格式爲xml格式,且根節點爲<xml></xml>

調用統一下單接口並傳入需求的參數後成功返回的數據和格式爲:

<xml>
   <return_code><![CDATA[SUCCESS]]></return_code>
   <return_msg><![CDATA[OK]]></return_msg>
   <appid><![CDATA[wx2421b1c4370ec43b]]></appid>
   <mch_id><![CDATA[10000100]]></mch_id>
   <nonce_str><![CDATA[IITRi8Iabbblz1Jc]]></nonce_str>
   <openid><![CDATA[oUpF8uMuAJO_M2pxb1Q9zNjWeS6o]]></openid>
   <sign><![CDATA[7921E432F65EB8ED0CE9755F0E86D72F]]></sign>
   <result_code><![CDATA[SUCCESS]]></result_code>
   <prepay_id><![CDATA[wx201411101639507cbf6ffd8b0779950874]]></prepay_id>
   <trade_type><![CDATA[JSAPI]]></trade_type>

</xml>


4、再次簽名(需要返回的值)

try {
        	System.out.println("Json: "+json);
			String repay_id = json.getString("prepay_id");
			SignInfo signInfo = new SignInfo();
			signInfo.setAppId(Configure.getAppID());
			long time = System.currentTimeMillis()/1000;
			signInfo.setTimeStamp(String.valueOf(time));
			signInfo.setNonceStr(RandomStringGenerator.getRandomStringByLength(32));
			signInfo.setRepay_id("prepay_id="+repay_id);
			signInfo.setSignType("MD5");
			//數據簽名
			String sign = Signature.getSign(signInfo);
			
			JSONObject json1 = new JSONObject();
			json1.put("timeStamp", signInfo.getTimeStamp());
			json1.put("nonceStr", signInfo.getNonceStr());
			json1.put("package", signInfo.getRepay_id());
			json1.put("signType", signInfo.getSignType());
			json1.put("appid", Configure.getAppID());
			json1.put("paySign", sign);
			return json1.toJSONString();
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}

將此部分代碼的返回值傳遞給前端代碼即可調用支付(完)


該程序使用的工具類和相關的代碼如下:

public class SignInfo {
	private String appId;//小程序ID	
	private String timeStamp;//時間戳	
	private String nonceStr;//隨機串	
	@XStreamAlias("package")
	private String repay_id;
	private String signType;//簽名方式
        //省略get set方法
}
public class OrderInfo {
	private String appid;// 小程序ID	
	private String mch_id;// 商戶號
	private String nonce_str;// 隨機字符串
	private String sign_type;//簽名類型
	private String sign;// 簽名
	private String body;// 商品描述
	private String out_trade_no;// 商戶訂單號
	private int total_fee;// 標價金額 ,單位爲分
	private String spbill_create_ip;// 終端IP
	private String notify_url;// 通知地址
	private String trade_type;// 交易類型
	private String openid;//用戶標識	//省略get set方法}
public class XStreamTool {
	public static OrderReturnInfo fromXML(String str,XStream xStream)
	{
		
		OrderReturnInfo returnInfo = (OrderReturnInfo)xStream.fromXML(str);
		return returnInfo;
	}
}
public class OrderReturnInfo {
	@XStreamAlias("return_code")
    private String return_code;
	@XStreamAlias("return_msg")
    private String return_msg;
	@XStreamAlias("appid")
    private String appid;
	@XStreamAlias("mch_id")
    private String mch_id;
	@XStreamAlias("nonce_str")
    private String nonce_str;
	@XStreamAlias("sign")
    private String sign;
	@XStreamAlias("result_code")
    private String result_code;
	@XStreamAlias("prepay_id")
    private String prepay_id;
	@XStreamAlias("trade_type")
    private String trade_type;}
public class Configure {
	private static String key = "10e0cc2e07a41d5c535579360f996fb4";

	//小程序ID	
	private static String appID = "wx85907fdbec00a2f7";
	//商戶號
	private static String mch_id = "1498192602";
	//
	private static String secret = "10e0cc2e07a41d5c535579360f996fb4";
public class HttpRequest {
	//連接超時時間,默認10秒
    private static final int socketTimeout = 10000;

    //傳輸超時時間,默認30秒
    private static final int connectTimeout = 30000;
	/**
	 * post請求
	 * @throws IOException 
	 * @throws ClientProtocolException 
	 * @throws NoSuchAlgorithmException 
	 * @throws KeyStoreException 
	 * @throws KeyManagementException 
	 * @throws UnrecoverableKeyException 
	 */
	public static String sendPost(String url, Object xmlObj) throws ClientProtocolException, IOException, UnrecoverableKeyException, KeyManagementException, KeyStoreException, NoSuchAlgorithmException {
		

        
		HttpPost httpPost = new HttpPost(url);
		//解決XStream對出現雙下劃線的bug
        XStream xStreamForRequestPostData = new XStream(new DomDriver("UTF-8", new XmlFriendlyNameCoder("-_", "_")));
        xStreamForRequestPostData.alias("xml", xmlObj.getClass());
        //將要提交給API的數據對象轉換成XML格式數據Post給API
        String postDataXML = xStreamForRequestPostData.toXML(xmlObj);

        //得指明使用UTF-8編碼,否則到API服務器XML的中文不能被成功識別
        StringEntity postEntity = new StringEntity(postDataXML, "UTF-8");
        httpPost.addHeader("Content-Type", "text/xml");
        httpPost.setEntity(postEntity);

        //設置請求器的配置
        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(socketTimeout).setConnectTimeout(connectTimeout).build();
        httpPost.setConfig(requestConfig);
        
        HttpClient httpClient = HttpClients.createDefault();
        HttpResponse response = httpClient.execute(httpPost);
        HttpEntity entity = response.getEntity();
        String result = EntityUtils.toString(entity, "UTF-8");
        return result;
	}
	/**
	 * 自定義證書管理器,信任所有證書
	 *
	 */
	public static class MyX509TrustManager implements X509TrustManager {
		@Override
		public void checkClientTrusted(
				java.security.cert.X509Certificate[] arg0, String arg1)
				throws java.security.cert.CertificateException {
			
		}
		@Override
		public void checkServerTrusted(
				java.security.cert.X509Certificate[] arg0, String arg1)
				throws java.security.cert.CertificateException {
			
		}
		@Override
		public java.security.cert.X509Certificate[] getAcceptedIssuers() {
			return null;
		}
      }}
package lumber.common;
public class MD5 {
    private final static String[] hexDigits = {"0", "1", "2", "3", "4", "5", "6", "7",
            "8", "9", "a", "b", "c", "d", "e", "f"};

    /**
     * 轉換字節數組爲16進制字串
     * @param b 字節數組
     * @return 16進制字串
     */
    public static String byteArrayToHexString(byte[] b) {
        StringBuilder resultSb = new StringBuilder();
        for (byte aB : b) {
            resultSb.append(byteToHexString(aB));
        }
        return resultSb.toString();
    }

    /**
     * 轉換byte到16進制
     * @param b 要轉換的byte
     * @return 16進制格式
     */
    private static String byteToHexString(byte b) {
        int n = b;
        if (n < 0) {
            n = 256 + n;
        }
        int d1 = n / 16;
        int d2 = n % 16;
        return hexDigits[d1] + hexDigits[d2];
    }

    /**
     * MD5編碼
     * @param origin 原始字符串
     * @return 經過MD5加密之後的結果
     */
    public static String MD5Encode(String origin) {
        String resultString = null;
        try {
            resultString = origin;
            MessageDigest md = MessageDigest.getInstance("MD5");
            resultString = byteArrayToHexString(md.digest(resultString.getBytes()));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return resultString;
    }

}

public class StreamUtil {
	public static String read(InputStream is){
		try {
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			int len = 0;
			byte[] buffer = new byte[512];
			while((len = is.read(buffer)) != -1){
				baos.write(buffer, 0, len);
			}
			return new String(baos.toByteArray(), 0, baos.size(), "utf-8");
		}catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return "";
	}
} 
public class Signature {
	private static final Logger L = Logger.getLogger(Signature.class);
	/**
     * 簽名算法
     * @param o 要參與簽名的數據對象
     * @return 簽名
     * @throws IllegalAccessException
     */
    public static String getSign(Object o) throws IllegalAccessException {
        ArrayList<String> list = new ArrayList<String>();
        Class cls = o.getClass();
        Field[] fields = cls.getDeclaredFields();
        for (Field f : fields) {
            f.setAccessible(true);
            if (f.get(o) != null && f.get(o) != "") {
            	String name = f.getName();
            	XStreamAlias anno = f.getAnnotation(XStreamAlias.class);
            	if(anno != null)
            		name = anno.value();
                list.add(name + "=" + f.get(o) + "&");
            }
        }
        int size = list.size();
        String [] arrayToSort = list.toArray(new String[size]);
        Arrays.sort(arrayToSort, String.CASE_INSENSITIVE_ORDER);
        StringBuilder sb = new StringBuilder();
        for(int i = 0; i < size; i ++) {
            sb.append(arrayToSort[i]);
        }
        String result = sb.toString();
        result += "key=" + Configure.getKey();
        System.out.println("簽名數據:"+result);
        result = MD5.MD5Encode(result).toUpperCase();
        return result;
    }

    public static String getSign(Map<String,Object> map){
        ArrayList<String> list = new ArrayList<String>();
        for(Map.Entry<String,Object> entry:map.entrySet()){
            if(entry.getValue()!=""){
                list.add(entry.getKey() + "=" + entry.getValue() + "&");
            }
        }
        int size = list.size();
        String [] arrayToSort = list.toArray(new String[size]);
        Arrays.sort(arrayToSort, String.CASE_INSENSITIVE_ORDER);
        StringBuilder sb = new StringBuilder();
        for(int i = 0; i < size; i ++) {
            sb.append(arrayToSort[i]);
        }
        String result = sb.toString();
        result += "key=" + Configure.getKey();
        //Util.log("Sign Before MD5:" + result);
        result = MD5.MD5Encode(result).toUpperCase();
        //Util.log("Sign Result:" + result);
        return result;
    }  

}
public class StreamUtil {
	public static String read(InputStream is){
		try {
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			int len = 0;
			byte[] buffer = new byte[512];
			while((len = is.read(buffer)) != -1){
				baos.write(buffer, 0, len);
			}
			return new String(baos.toByteArray(), 0, baos.size(), "utf-8");
		}catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return "";
	}
}





發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章