阿里支付接口的驗證機制和普通接口不同,採用的是證書驗證,使用支付寶開放平臺助手 ---> 生成密鑰獲取csr文件
公司注意些支付對應的支付寶程序所在的公司的名稱。
得到生成好的3個文件
放入對應的文件夾
private String APP_ID = ""; //application private key private String APP_PRIVATE_KEY = "";
//charset private String CHARSET = "utf-8"; //sign type private String SIGN_TYPE = "RSA2";
/** * 支付相關接口採用csr方式驗證 * * @return */ private AlipayClient getClientInstanceByKey() throws AlipayApiException { AlipayClient aplipayClient = aliMap.get("client"); if (aplipayClient == null) { CertAlipayRequest certAlipayRequest = new CertAlipayRequest(); //設置網關地址 certAlipayRequest.setServerUrl("https://openapi.alipay.com/gateway.do"); //設置應用Id certAlipayRequest.setAppId(APP_ID); //設置應用私鑰 certAlipayRequest.setPrivateKey(APP_PRIVATE_KEY); //設置請求格式,固定值json certAlipayRequest.setFormat("json"); //設置字符集 certAlipayRequest.setCharset(CHARSET); //設置簽名類型 certAlipayRequest.setSignType(SIGN_TYPE); //設置應用公鑰證書路徑 certAlipayRequest.setCertPath("/home/crt/appCertPublicKey_xxx.crt"); //設置支付寶公鑰證書路徑 certAlipayRequest.setAlipayPublicCertPath("/home/crt/alipayCertPublicKey_RSA2.crt"); //設置支付寶根證書路徑 certAlipayRequest.setRootCertPath("/home/crt/alipayRootCert.crt"); aplipayClient = new DefaultAlipayClient(certAlipayRequest); aliMap.put("client", aplipayClient); } return aplipayClient; }
/** * 支付寶向用戶轉賬 * * @param bizNo 邏輯單號 * @param amount 轉賬金額 單位元 * @param account 支付寶賬號 * @return */ public RestResult<Integer> alipay2User(String bizNo, String amount, String account) { // 設置請求參數 AlipayFundTransUniTransferRequest alipayRequest = new AlipayFundTransUniTransferRequest(); Map<String, String> map = new HashMap<>(); map.put("out_biz_no", bizNo); map.put("trans_amount", amount); map.put("product_code", "TRANS_ACCOUNT_NO_PWD"); map.put("biz_scene", "DIRECT_TRANSFER"); map.put("order_title", ""); map.put("remark", ""+amount); // 轉賬賬戶 Map<String, String> map2 = new HashMap<>(); map2.put("identity", account); map2.put("identity_type", "ALIPAY_USER_ID"); map2.put("name", ""); map.put("payee_info", JSONObject.toJSONString(map2)); // 轉成json格式放入 String json = JSONObject.toJSONString(map); alipayRequest.setBizContent(json); AlipayFundTransUniTransferResponse response; try { response = getClientInstanceByKey().certificateExecute(alipayRequest); System.out.println(JSON.toJSONString(response)); if (response.isSuccess()) { return RestResult.wrapSuccessResponse(); } else { log.info("支付失敗,bizNo:"+bizNo+",原因:"+response.getBody()); return RestResult.wrapErrorResponse("支付失敗"); } } catch (Exception e) { e.printStackTrace(); log.info("支付失敗,bizNo:"+bizNo+",異常原因:"+e); return RestResult.wrapErrorResponse("支付失敗"); } }
關鍵就是getClientInstanceByKey().certificateExecute(alipayRequest); ,支付相關接口採用證書驗證方式才能通過,支付寶轉賬的demo有點坑