1. 程式人生 > >基於SDK的支付介面服務端——支付寶,微信

基於SDK的支付介面服務端——支付寶,微信

支付寶

準備:

1.建立應用,配置金鑰(詳見https://docs.open.alipay.com/291/105971);
2.jar包:alipay-sdk-java20170818173712.jar;commons-logging-1.1.1.jar

3.配置資訊:appid;應用私鑰;支付寶公鑰(是支付寶公鑰不是應用公鑰);
4.基本步驟:
(1)獲得初始化的AlipayClient
(2)建立API對應的request類
(3)設定業務引數
(4)通過alipayClient呼叫API,獲得對應的response類
(5)根據response中的結果繼續業務邏輯處理

官方示例

//1.交易查詢
AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do", APP_ID, APP_PRIVATE_KEY, "json", CHARSET, ALIPAY_PUBLIC_KEY, "RSA2"); //獲得初始化的AlipayClient
AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();//建立API對應的request類
request.setBizContent("{"
+ " \"out_trade_no\":\"20150320010101001\"," + " \"trade_no\":\"2014112611001004680073956707\"" + " }");//設定業務引數 AlipayTradeQueryResponse response = alipayClient.execute(request);//通過alipayClient呼叫API,獲得對應的response類 System.out.print(response.getBody()); //根據response中的結果繼續業務邏輯處理

再具體一點的示例

//建立支付寶配置類
public class AlipayConfig {
    public
static String APP_ID_USER = "XXX"; //應用私鑰 public static String PRIVATE_KEY = "XXX"; //支付寶公鑰 public static String ALIPAY_PUBLIC_KEY = "XXX"; public static String CHARSET = "utf-8"; public static String URL = "https://openapi.alipay.com/gateway.do"; public static String FORMAT = "json"; public static String SIGN_TYPE = "RSA2"; }
//申請退款
 public String refundRequest( String tradeNo, int refundMoney) {
   String TimeMillis=String.valueOf(System.currentTimeMillis());
        String responseStr = "退款失敗";
            AlipayClient alipayClient = new DefaultAlipayClient(URL, APP_ID_LAWYER, PRIVATE_KEY, FORMAT, CHARSET, ALIPAY_PUBLIC_KEY, SIGN_TYPE);

            double money = refundMoney;
            money = money / 100;//單位是元
            AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();
            request.setBizContent("{" +
                    "\"trade_no\":\"" + tradeNo + "\"," +
                    "\"out_request_no\":\"" + tradeNo + "\"," +
                    "\"refund_amount\":" + money + "" +
                    "  }");
            AlipayTradeRefundResponse response;
            try {
                response = alipayClient.execute(request);
                if (response.isSuccess()) {
                    responseStr = "退款成功";
                } else if(response != null){
                    responseStr = response.getSubMsg();
                }
            } catch (AlipayApiException e) {
                responseStr = "系統異常";
                }
    return responseStr; }       

沙箱環境

  //沙箱環境
    public static String APP_ID_TEST = "2016081900288218";
    // 應用的私鑰
    public static String PRIVATE_KEY_TEST = "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCEoj5tT+gt0CfUc1hgjZuFVgr8x7fBY4tJfOSfiTO0A3jyxNPjZz16nQ1k4xyTOKSxHmcdZopN5HZRI3J8+4U3a8C7tkTJ8o79qLbStVRqR9LIZA6FA4ToIb/3evoET5h2AH51JHO0ZiJAxsY5frbyqltfjEYVRK1h+HuQ5pXYRjHWfOxk0eOl+CEyV1CLcSoPTDaXRCy98/6BfG9DU5LjvXCep55J11ibwNC8mkbZTnZm5rGBXtS3NKUopfAHBBgga2nYO+duTjMTtLAt1BNhxLnBAH61tdLEafloWBcWwa/nerYnadkgiX0ibqs/eY+yj5rOfhUTTsF6oBZup2WjAgMBAAECggEABRHSgwkf3chsDVHPWflvrVwJlXnoyyqL42YzsulioYnUcKsXUkTa87nXDjkkGXh7yw1Xcac+uBV4dEd/k8llYSXsOwCPhoyP7KArRMiLjnhqVSCF8Y2d4eWQWdxIfCuyryf7rWyUQ5v3yTQP1ZjDU2kxjuhksWFroygFSReXOKoAG8AM7ZxflqYOi91bOX8bnxo2QBVIkQrWo1b1gGoo9q15YOBU5ZY4A79CNIkZlv1Uq3Zv+lVTr9UKcCbhPUF5Yc/y2j7BuI28APGwMOFzEaUqZnXlbf7opCbv+B0fx00NZ1nWWnreUl0IcATOCYP6aiNXcoaK04EuOJ8rjP4O2QKBgQC+HjRp07CMsbL/0cUOsgr6E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utggLB9SxTfJr2Jo5hIgaVejyznf1FlbvGWM7gWdXv8oYWo0h+vK79vLRD3kTvVpuYdKoPAtE4UuRqwnYDUt9QujauXhKOKHQs8SRA0ngWVTVFA8O6C1eJMvP7U0zvrKHyktLekpRjN/JZEHOLuqBP9DzJgL1Nqcv045h2/b58PYsjutYSYfFwSDfcpKpEPVwZhDswIDAQAB";
    // 字元編碼格式 目前支援 gbk 或 utf-8
    public static String CHARSET_TEST  = "utf-8";
    //退款介面url
    public static String URL_TEST = "https://openapi.alipaydev.com/gateway.do";

    public static String FORMAT_TEST="json";
    // 簽名方式
    public static String SIGN_TYPE_TEST  = "RSA2";

微信

準備
1.建立應用,配置祕鑰
2.安裝

<dependency>
    <groupId>com.github.wxpay</groupId>
    <artifactId>wxpay-sdk</artifactId>
    <version>0.0.3</version>
</dependency>

3.需要的資源
appid
商戶號 [微信支付分配的商戶號]
商戶平臺設定的金鑰key
商戶證書 [pkcs12格式(apiclient_cert.p12);微信商戶平臺(pay.weixin.qq.com)–>賬戶中心–>賬戶設定–>API安全–>證書下載 ]
4.基本步驟
(1)建立配置類
(2)放入引數
(3)呼叫介面
(4)根據響應處理業務
官方示例:

//微信支付配置類
import com.github.wxpay.sdk.WXPayConfig;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;

public class WXPayConfigImpl implements WXPayConfig {
    private String appId = "xxx";
    private String  mchId = "xxx";//商戶號
    private String key = "xxx";//金鑰key

    private byte[] certData;
    private static WXPayConfigImpl INSTANCE;

    private WXPayConfigImpl() throws Exception{
        String certPath = "src/resources/apiclient_cert.p12";//證書位置
        File file = new File(certPath);
        InputStream certStream = new FileInputStream(file);
        this.certData = new byte[(int) file.length()];
        certStream.read(this.certData);
        certStream.close();
    }

    public static WXPayConfigImpl getInstance() throws Exception{
        if (INSTANCE == null) {
            synchronized (WXPayConfigImpl.class) {
                if (INSTANCE == null) {
                    INSTANCE = new WXPayConfigImpl();
                }
            }
        }
        return INSTANCE;
    }

    public String getAppID() {
        return appId;
    }

    public String getMchID() {
        return mchId;
    }

    public String getKey() {
        return key;
    }

    public InputStream getCertStream() {
        ByteArrayInputStream certBis;
        certBis = new ByteArrayInputStream(this.certData);
        return certBis;
    }


    public int getHttpConnectTimeoutMs() {
        return 2000;
    }

    public int getHttpReadTimeoutMs() {
        return 10000;
    }
}
//支付測試類;包括下單操作,退款操作,對賬單下載
import com.github.wxpay.sdk.WXPay;
import com.github.wxpay.sdk.WXPayUtil;

import java.util.HashMap;
import java.util.Map;

public class TestWXPay {

    private WXPay wxpay;
    private WXPayConfigImpl config;
    private String out_trade_no;
    private String total_fee;

    public TestWXPay() throws Exception {
        config = WXPayConfigImpl.getInstance();
        wxpay = new WXPay(config);
        total_fee = "1";
        // out_trade_no = "201701017496748980290321";
        out_trade_no = "201613091059590000003433-asd002";
    }

    /**
     * 掃碼支付  下單
     */
    public void doUnifiedOrder() {
        HashMap<String, String> data = new HashMap<String, String>();
        data.put("body", "騰訊充值中心-QQ會員充值");
        data.put("out_trade_no", out_trade_no);
        data.put("device_info", "");
        data.put("fee_type", "CNY");
        data.put("total_fee", "1");
        data.put("spbill_create_ip", "123.12.12.123");
        data.put("notify_url", "http://test.letiantian.me/wxpay/notify");
        data.put("trade_type", "NATIVE");
        data.put("product_id", "12");
        // data.put("time_expire", "20170112104120");

        try {
            Map<String, String> r = wxpay.unifiedOrder(data);
            System.out.println(r);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public void doOrderClose() {
        System.out.println("關閉訂單");
        HashMap<String, String> data = new HashMap<String, String>();
        data.put("out_trade_no", out_trade_no);
        try {
            Map<String, String> r = wxpay.closeOrder(data);
            System.out.println(r);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void doOrderQuery() {
        System.out.println("查詢訂單");
        HashMap<String, String> data = new HashMap<String, String>();
        data.put("out_trade_no", out_trade_no);
//        data.put("transaction_id", "4008852001201608221962061594");
        try {
            Map<String, String> r = wxpay.orderQuery(data);
            System.out.println(r);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void doOrderReverse() {
        System.out.println("撤銷");
        HashMap<String, String> data = new HashMap<String, String>();
        data.put("out_trade_no", out_trade_no);
//        data.put("transaction_id", "4008852001201608221962061594");
        try {
            Map<String, String> r = wxpay.reverse(data);
            System.out.println(r);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }



    /**
     * 長連結轉短連結
     * 測試成功
     */
    public void doShortUrl() {
        String long_url = "weixin://wxpay/bizpayurl?pr=etxB4DY";
        HashMap<String, String> data = new HashMap<String, String>();
        data.put("long_url", long_url);
        try {
            Map<String, String> r = wxpay.shortUrl(data);
            System.out.println(r);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 退款
     * 已測試
     */
    public void doRefund() {
        HashMap<String, String> data = new HashMap<String, String>();
        data.put("out_trade_no", out_trade_no);
        data.put("out_refund_no", out_trade_no);
        data.put("total_fee", total_fee);
        data.put("refund_fee", total_fee);
        data.put("refund_fee_type", "CNY");
        data.put("op_user_id", config.getMchID());

        try {
            Map<String, String> r = wxpay.refund(data);
            System.out.println(r);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * 查詢退款
     * 已經測試
     */
    public void doRefundQuery() {
        HashMap<String, String> data = new HashMap<String, String>();
        data.put("out_refund_no", out_trade_no);
        try {
            Map<String, String> r = wxpay.refundQuery(data);
            System.out.println(r);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 對賬單下載
     * 已測試
     */
    public void doDownloadBill() {
        HashMap<String, String> data = new HashMap<String, String>();
        data.put("bill_date", "20161102");
        data.put("bill_type", "ALL");
        try {
            Map<String, String> r = wxpay.downloadBill(data);
            System.out.println(r);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void doGetSandboxSignKey() throws Exception {
        WXPayConfigImpl config = WXPayConfigImpl.getInstance();
        HashMap<String, String> data = new HashMap<String, String>();
        data.put("mch_id", config.getMchID());
        data.put("nonce_str", WXPayUtil.generateNonceStr());
        String sign = WXPayUtil.generateSignature(data, config.getKey());
        data.put("sign", sign);
        WXPay wxPay = new WXPay(config);
        String result = wxPay.requestWithoutCert("https://api.mch.weixin.qq.com/sandbox/pay/getsignkey", data, 10000, 10000);
        System.out.println(result);
    }

    public static void main(String[] args) throws Exception {

        TestWXPay dodo = new TestWXPay();
        dodo.doOrderQuery();
        dodo.doOrderReverse();
        dodo.doOrderQuery();
        dodo.doOrderReverse();
        dodo.doOrderQuery();
    }
}

開發示例

/**金額單位:分
*/
public String refundRequest(String tradeNo, int refundMoney, int totalMoney) {
        String responseStr = "退款失敗";
try {
                WXPayConfigImpl config = WXPayConfigImpl.getInstance();
                WXPay wxpay = new WXPay(config);
                HashMap<String, String> data = new HashMap<>();
                data.put("transaction_id",""+ tradeNo+"");
                data.put("out_refund_no",""+ TimeMillis+"");
                data.put("total_fee",""+totalMoney+"");
                data.put("refund_fee",""+refundMoney+"");
                data.put("refund_fee_type", "CNY");
                data.put("mch_id", config.getMchID());
                Map<String, String> r = wxpay.refund(data);
                String err_code_des = r.get("err_code_des");
                if(err_code_des == null) {
                    responseStr ="退款成功";
                } else {
                    responseStr = err_code_des;
                }
            } catch (Exception e) {
                responseStr = "系統異常"; 
            }

        return responseStr;
        }