支付寶當面付對接


開發原因及需求見上文:微信native支付對接

支付寶當面付:
支付寶配置類 zfbinfo.properties:
# 支付寶網關名、partnerId和appId
open_api_domain = https://openapi.alipay.com/gateway.do
mcloud_api_domain = http://mcloudmonitor.com/gateway.do
pid = 
appid = 

# RSA私鑰、公鑰和支付寶公鑰
private_key =
public_key = 
#SHA256withRsa對應支付寶公鑰
alipay_public_key = 

# 簽名類型: RSA->SHA1withRsa,RSA2->SHA256withRsa
sign_type = RSA2
# 當面付最大查詢次數和查詢間隔(毫秒)
max_query_retry = 5
query_duration = 5000

# 當面付最大撤銷次數和撤銷間隔(毫秒)
max_cancel_retry = 3
cancel_duration = 2000

# 交易保障線程第一次調度延遲和調度間隔(秒)
heartbeat_delay = 5
heartbeat_duration = 900
支付寶工具類 PayCommonUtil:
package com.joymusic.servlet.utils.aliPay;

import com.alipay.api.response.AlipayTradePrecreateResponse;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.alipay.api.response.AlipayTradeRefundResponse;
import com.alipay.demo.trade.config.Configs;
import com.alipay.demo.trade.model.builder.AlipayTradePrecreateRequestBuilder;
import com.alipay.demo.trade.model.builder.AlipayTradeQueryRequestBuilder;
import com.alipay.demo.trade.model.builder.AlipayTradeRefundRequestBuilder;
import com.alipay.demo.trade.model.result.AlipayF2FPrecreateResult;
import com.alipay.demo.trade.model.result.AlipayF2FQueryResult;
import com.alipay.demo.trade.model.result.AlipayF2FRefundResult;
import com.alipay.demo.trade.service.AlipayMonitorService;
import com.alipay.demo.trade.service.AlipayTradeService;
import com.alipay.demo.trade.service.impl.AlipayMonitorServiceImpl;
import com.alipay.demo.trade.service.impl.AlipayTradeServiceImpl;
import com.alipay.demo.trade.service.impl.AlipayTradeWithHBServiceImpl;
import org.json.JSONException;
import org.json.JSONObject;

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

//支付寶支付工具類
public class PayCommonUtil {
    private static org.apache.log4j.Logger log = org.apache.log4j.Logger.getLogger("mydebug");
    // 支付寶當面付2.0服務
    private static AlipayTradeService tradeService;
    // 支付寶當面付2.0服務(集成了交易保障接口邏輯)
    private static AlipayTradeService tradeWithHBService;
    // 支付寶交易保障接口服務,供測試接口api使用,請先閱讀readme.txt
    private static AlipayMonitorService monitorService;

    static {
        /** 一定要在創建AlipayTradeService之前調用Configs.init()設置默認參數
         *  Configs會讀取classpath下的zfbinfo.properties文件配置信息,如果找不到該文件則確認該文件是否在classpath目錄
         */
        Configs.init("zfbinfo.properties");

        /** 使用Configs提供的默認參數
         *  AlipayTradeService可以使用單例或者為靜態成員對象,不需要反復new
         */
        tradeService = new AlipayTradeServiceImpl.ClientBuilder().build();
        // 支付寶當面付2.0服務(集成了交易保障接口邏輯)
        tradeWithHBService = new AlipayTradeWithHBServiceImpl.ClientBuilder().build();

        /** 如果需要在程序中覆蓋Configs提供的默認參數, 可以使用ClientBuilder類的setXXX方法修改默認參數 否則使用代碼中的默認設置 */
        monitorService = new AlipayMonitorServiceImpl.ClientBuilder()
                .setGatewayUrl("http://mcloudmonitor.com/gateway.do").setCharset("GBK")
                .setFormat("json").build();
    }

    //發起當面付2.0生成支付二維碼
    public static String aliPay(String body, String total_amount, String uid, String out_trade_no) throws JSONException {
        String code_url = "";
        String subject = body;
        // 支付超時,定義為120分鍾
        String timeoutExpress = "100m";
        // 賣家支付寶賬號ID,用於支持一個簽約賬號下支持打款到不同的收款賬號,(打款到sellerId對應的支付寶賬號)
        // 如果該字段為空,則默認為與支付寶簽約的商戶的PID,也就是appid對應的PID
        String sellerId = "";
        String storeId = "txhy_joymusic";
        // 創建掃碼支付請求builder,設置請求參數
        AlipayTradePrecreateRequestBuilder builder = new AlipayTradePrecreateRequestBuilder()
                .setSubject(subject).setTotalAmount(total_amount).setBody(body).setOutTradeNo(out_trade_no)
                .setTimeoutExpress(timeoutExpress).setSellerId(sellerId).setTerminalId(uid).setStoreId(storeId);
        AlipayF2FPrecreateResult result = tradeService.tradePrecreate(builder);

        switch (result.getTradeStatus()) {
            case SUCCESS:
                AlipayTradePrecreateResponse response = result.getResponse();
                JSONObject responseJson = new JSONObject(response);
                code_url = responseJson.getString("qrCode");
                break;
            case FAILED:
                log.info("支付寶預下單失敗!!!");
                break;
            case UNKNOWN:
                log.info("系統異常,預下單狀態未知!!!");
                break;
            default:
                log.info("不支持的交易狀態,交易返回異常!!!");
                break;
        }
        return code_url;
    }

    /**
     * 查詢訂單
     *
     * @param outTradeNo 商戶訂單id
     * @return
     * @throws Exception
     */
    public static Map selectOrder(String outTradeNo) throws Exception {

        Map<String, String> selectMap = new HashMap<>();
        // 創建查詢請求builder,設置請求參數
        AlipayTradeQueryRequestBuilder builder = new AlipayTradeQueryRequestBuilder().setOutTradeNo(outTradeNo);
        AlipayF2FQueryResult result = tradeService.queryTradeResult(builder);
        AlipayTradeQueryResponse response = result.getResponse();
        JSONObject jsonObject = new JSONObject(response.getBody());
        JSONObject query_response = jsonObject.getJSONObject("alipay_trade_query_response");
        String resultCode = query_response.getString("code");
        if ("10000".equals(resultCode)){
            String buyer_user_id = query_response.getString("buyer_user_id");//支付寶用戶id
            String trade_no = query_response.getString("trade_no");//支付寶訂單id
            String out_trade_no = query_response.getString("out_trade_no");//商戶訂單id
            String trade_status = query_response.getString("trade_status");//交易狀態
            String amount = query_response.getString("receipt_amount");//實際支付金額
            String send_pay_date = query_response.getString("send_pay_date");//付款時間
            selectMap.put("returnCode","1");
            selectMap.put("trade_status",trade_status);
            selectMap.put("buyer_user_id",buyer_user_id);
            selectMap.put("trade_no",trade_no);
            selectMap.put("out_trade_no",out_trade_no);
            selectMap.put("amount",amount);
            selectMap.put("send_pay_date",send_pay_date);
        }else {
            selectMap.put("returnCode","0");
            log.info("查詢錯誤原因: "+query_response.getString("sub_msg"));
        }
        return selectMap;
    }

    //分轉換為元
    public static String cent2yuan(int orderPrice){
        Double num1 = Double.valueOf(orderPrice);
        Double ratio = num1 / 100;
        return String.format("%.2f", ratio);
    }

    // 測試當面付2.0退款
    public static HashMap<String, String> test_trade_refund(String outTradeNo, String refundAmount, String refundReason) throws JSONException {
        HashMap<String, String> refundMap = new HashMap<>();
        // (必填) 退款金額,該金額必須小於等於訂單的支付金額,單位為元
        refundAmount = "0.01";
        // (必填) 退款原因,可以說明用戶退款原因,方便為商家后台提供統計
        refundReason = "正常退款,用戶買多了";
        // (必填) 商戶門店編號,退款情況下可以為商家后台提供退款權限判定和統計等作用,詳詢支付寶技術支持
        String storeId = "txhy_joymusic";
        // 創建退款請求builder,設置請求參數
        AlipayTradeRefundRequestBuilder builder = new AlipayTradeRefundRequestBuilder()
                .setOutTradeNo(outTradeNo).setRefundAmount(refundAmount).setRefundReason(refundReason).setStoreId(storeId).setStoreId(storeId);

        AlipayF2FRefundResult result = tradeService.tradeRefund(builder);
        AlipayTradeRefundResponse response = result.getResponse();
        JSONObject jsonObject = new JSONObject(response.getBody());
        JSONObject query_response = jsonObject.getJSONObject("alipay_trade_query_response");
        String resultCode = query_response.getString("code");
        if ("10000".equals(resultCode)){
            String buyer_user_id = query_response.getString("buyer_user_id");//支付寶用戶id
            String trade_no = query_response.getString("trade_no");//支付寶訂單id
            String out_trade_no = query_response.getString("out_trade_no");//商戶訂單id
            String trade_status = query_response.getString("trade_status");//交易狀態
            String amount = query_response.getString("receipt_amount");//實際支付金額
            String send_pay_date = query_response.getString("send_pay_date");//付款時間
            refundMap.put("returnCode","1");
            refundMap.put("trade_status",trade_status);
            refundMap.put("buyer_user_id",buyer_user_id);
            refundMap.put("trade_no",trade_no);
            refundMap.put("out_trade_no",out_trade_no);
            refundMap.put("amount",amount);
            refundMap.put("send_pay_date",send_pay_date);
        }else {
            refundMap.put("returnCode","0");
            log.info("查詢錯誤原因: "+query_response.getString("sub_msg"));
        }
        return refundMap;
    }
}
調用及實現:
//支付
String ip = "192.168.0.1";//發起支付ip
String body = "XX訂購";//訂單標題
String orderPrice = "1";//支付金額(分)
String userId = "test010101";//設備id 可當做用戶id
String out_trade_no = userId.substring(0,5)+"_"+ PayCommonUtil.getCurrTime() + PayCommonUtil.buildRandom(4);//商戶訂單id
//數據庫記錄發起訂購記錄(自定義)
setInitPay(ip, userId,orderPrice,body,"86",songId,platform,out_trade_no,payType);
String total_amount = cent2yuan(orderPrice);
String aliQRcode = aliPay.PayCommonUtil.aliPay(body, total_amount, userId, out_trade_no);

//查詢
//訂單狀態 :0: 用戶支付中 1: 支付成功 3:未支付 4:已關閉
Map orderSelectMap = aliPay.PayCommonUtil.selectOrder(out_trade_no);
String aliReturnCode = orderSelectMap.get("returnCode").toString();
String trade_state = orderSelectMap.get("trade_status").toString();
if("1".equals(aliReturnCode)){
    String myOrderNumber = orderSelectMap.get("out_trade_no").toString();
    if ("TRADE_SUCCESS".equals(trade_state)){//記錄數據庫
        //更新數據庫(自定義)        
        setPayResult(ip, userId, "86", songId, platform, orderPrice+"", validTime, expireTime, "0", aliOderNumber, payType, myOrderNumber, openid, 0);
        orderResult = "0";
    }else if("WAIT_BUYER_PAY".equals(trade_state)){//正在支付中時
        if ("1".equals(isLast)) {
            updateInfoPay(userId,myOrderNumber,"3");
        }else {
            isKeep = "1";
        }
    }else if("TRADE_CLOSED".equals(trade_state)){//訂單關閉
        updateInfoPay(userId,myOrderNumber,"3");
    }else if("TRADE_FINISHED".equals(trade_state)){
        updateInfoPay(userId,myOrderNumber,"4");
    }
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM