1. 程式人生 > >支付寶h5支付對接

支付寶h5支付對接

不用支付寶的api。太噁心了2M多。
獻給對接支付寶h5支付的小夥伴們

public static void main(String[] args) throws UnsupportedEncodingException {
Map<String, String> requestMap = new TreeMap<String, String>();//涉及到排序用treemap
Map<String, String> bizMap = new TreeMap<String, String>();//這個可用hashmap
requestMap.put("app_id", "");//支付寶分配的商戶;
requestMap.put("method", "alipay.trade.wap.pay");
requestMap.put("return_url","");//前端回撥地址
requestMap.put("charset", "utf-8");
requestMap.put("sign_type", "RSA");//用的rsa rsa2的自行百度 實際差不多
requestMap.put("timestamp", DateUtil.formatDate(new Date(), DateUtil.DATETIME));
requestMap.put("version", "1.0");
requestMap.put("notify_url", "");//後端回撥地址
bizMap.put("body", "");
bizMap.put("subject", "");
bizMap.put("out_trade_no", "");
bizMap.put("total_amount", "0.01");
bizMap.put("product_code", "QUICK_WAP_WAY");
bizMap.put("seller_id", "");
requestMap.put("biz_content", JSONObject.toJSONString(bizMap));
String signParam = map2HttpParams(requestMap);
requestMap.put("sign", sign(signParam, "替換為你的簽名私匙","utf-8"));
for (String key : requestMap.keySet()) {
if ("biz_content".equals(key)) {// 不對biz_content這個json串進行編碼,看清楚喔,少踩坑
requestMap.put(key, requestMap.get(key));
} else {
requestMap.put(key, URLEncoder.encode(requestMap.get(key), "utf-8"));
}
}


String requestParamString=map2HttpParams(requestMap);
System.out.println("支付寶請求url = " + "https://openapi.alipay.com/gateway.do?" +requestParamString);

//查詢驗籤我就不貼出來了 都差不多,但是一定要注意// 我用的net.sf.json,阿里的 fastjson在解析json物件原始碼中會new HashMap 會打亂原本的字串順序。
}


/**
* 將map轉換為 http請求引數串
*/
public static String map2HttpParams(Map<String, String> map) {
if (map == null || map.size()==0) {
return "";
}
StringBuffer sb = new StringBuffer();
for (Map.Entry<String, String> entry : map.entrySet()) {
if (null == entry.getValue() || "".equals(entry.getValue())) {
continue;
}
sb.append(entry.getKey() + "=" + entry.getValue());
sb.append("&");
}
String s = sb.toString();
if (s.endsWith("&")) {
s = StringUtils.substringBeforeLast(s, "&");
}
return s;
}


public static String sign(String content, String privateKey, String input_charset) {
        try {
        PKCS8EncodedKeySpec priPKCS8 = new PKCS8EncodedKeySpec( Base64.decode(privateKey) ); 
        KeyFactory keyf = KeyFactory.getInstance("RSA");
        PrivateKey priKey = keyf.generatePrivate(priPKCS8);
            java.security.Signature signature = java.security.Signature
                .getInstance("SHA1WithRSA");//如果是rsa2對應選擇rsa2的
            signature.initSign(priKey);
            signature.update( content.getBytes(input_charset) );
            byte[] signed = signature.sign();
            return Base64.encode(signed);
        } catch (Exception e) {
        }
        return null;
    }