App下載

Springboot如何添加支付接口?實(shí)例過(guò)程詳解

猿友 2021-08-06 09:51:49 瀏覽數(shù) (2456)
反饋

1. 支付寶支付接口(沙箱實(shí)現(xiàn))

1.1 支付寶沙箱賬號(hào)獲取

官網(wǎng)

此處作者已經(jīng)申請(qǐng)了一個(gè)沙箱賬號(hào),申請(qǐng)過(guò)程就不再贅述

如下圖:

2021414114540744

此處可以自行設(shè)置賬戶金額

1.2 下載客戶端(目前好像只支持Android)

2021414114614358

下載完成后根據(jù)官方提供的賬號(hào)以及密碼登錄手機(jī)端支付寶賬號(hào) 如圖(商家賬號(hào)):

2021414114641099

1.3 代碼配置

工具類AlipayConfig

public class AlipayConfig {

//↓↓↓↓↓↓↓↓↓↓請(qǐng)?jiān)谶@里配置您的基本信息↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓

    // 應(yīng)用ID,您的APPID,收款賬號(hào)既是您的APPID對(duì)應(yīng)支付寶賬號(hào)
    public static String app_id = "";

    // 商戶私鑰,您的PKCS8格式RSA2私鑰
    public static String merchant_private_key = "MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQC/HOeQNyultzkc5cUnqxBSTIpYt6BTgJoCHKiLQDYgPhjvSX16r08Qw82qYdQgWEs4hHNy2COGA5ksw1eW+zyY2alcTEvRMo4sqx7Ytdm250f67wZQkuPRFSJN7ywHkTipjGKNcS9z9U0Dp18jRXHow4/A9OF8jOau7pWyG0Tc87WHf5u0/G16uMpRtGRzzyNvim7cHAnyFPNrAJ+5DRBdhBg+PjV7EcpYg5LRaMqaO8qDSis+AUU4e7QOELqMgr7yxBNScQ6KksnWnztcFxz6M9T66dAZJ0dWpiB8qatM6sT/MeHTAXeYLhIbnUaxM9vGJR3AJHbHmvNa9o0ToT0LAgMBAAECggEBAIk1a1szAPc9EJgaru3H9zPfGASR8V2CGxAhGzC+rR2A9830aU5HxvA2Y9ZL3kxKl9a/4VM2smpo8vQcWypevibPPrSxYk2Tilevk7nq9aBHdHp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g2CC0WIAA6MPP3xaezSWO1la39Slam0w3l";

    // 支付寶公鑰,查看地址:https://openhome.alipay.com/platform/keyManage.htm 對(duì)應(yīng)APPID下的支付寶公鑰。
    public static String alipay_public_key = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAvxznkDcrpbc5HOXFJ6sQUkyKWLegU4CaAhyoi0A2ID4Y70l9eq9PEMPNqmHUIFhLOIRzctgjhgOZLMNXlvs8mNmpXb4pu3BwJ8hTzawCfuQ0QXYQYPj41exHKWIOS0WjKmjvKg0orPgFFOHu0DhC6jIK+8sQTUnEOipLJ1p87XBcc+jPU+unQGSdHVqYgfKmrTOrE/zHh0wF3mC4SG51GsTPbxiUdwCR2x5rzWvaNE6E9CwIDAQAB";

    // 服務(wù)器異步通知頁(yè)面路徑  需http://格式的完整路徑,不能加?id=123這類自定義參數(shù),必須外網(wǎng)可以正常訪問(wèn)
    public static String notify_url = "http://localhost:8080/alipay/alipayNotifyNotice.action";

    // 頁(yè)面跳轉(zhuǎn)同步通知頁(yè)面路徑 需http://格式的完整路徑,不能加?id=123這類自定義參數(shù),必須外網(wǎng)可以正常訪問(wèn)
    public static String return_url = "http://localhost:8080/alipay/alipayReturnNotice.action";

    // 簽名方式
    public static String sign_type = "RSA2";

    // 字符編碼格式
    public static String charset = "utf-8";

    // 支付寶網(wǎng)關(guān)
    public static String gatewayUrl = "https://openapi.alipaydev.com/gateway.do";

    // 支付寶網(wǎng)關(guān)
    public static String log_path = "C:\";


//↑↑↑↑↑↑↑↑↑↑請(qǐng)?jiān)谶@里配置您的基本信息↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑

    /**
     * 寫日志,方便測(cè)試(看網(wǎng)站需求,也可以改成把記錄存入數(shù)據(jù)庫(kù))
     * @param sWord 要寫入日志里的文本內(nèi)容
     */
    public static void logResult(String sWord) {
        FileWriter writer = null;
        try {
            writer = new FileWriter(log_path + "alipay_log_" + System.currentTimeMillis()+".txt");
            writer.write(sWord);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (writer != null) {
                try {
                    writer.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

其中的參數(shù)獲取如下: app_id

2021414114729081

商戶私鑰,以及支付寶公鑰獲取方法參考官方文檔:密鑰生成

頁(yè)面跳轉(zhuǎn)便是支付以后自動(dòng)跳轉(zhuǎn)的界面

接下來(lái)解釋編寫下單頁(yè)面:

/**
     *
     * @Title: AlipayController.java
     * @Package com.sihai.controller
     * @Description: 前往支付寶第三方網(wǎng)關(guān)進(jìn)行支付
     * Copyright: Copyright (c) 2017
     * Company:FURUIBOKE.SCIENCE.AND.TECHNOLOGY
     */
    @RequestMapping(value = "/goAlipay", produces = "text/html; charset=UTF-8")
    @ResponseBody
    public String goAlipay(String orderId, HttpServletRequest request, HttpServletRequest response) throws Exception {

         order = (Order) request.getSession().getAttribute("order");

    orderId="FinchII";

        //獲得初始化的AlipayClient
        AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id, AlipayConfig.merchant_private_key, "json", AlipayConfig.charset, AlipayConfig.alipay_public_key, AlipayConfig.sign_type);

        //設(shè)置請(qǐng)求參數(shù)
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        alipayRequest.setReturnUrl(AlipayConfig.return_url);
        alipayRequest.setNotifyUrl(AlipayConfig.notify_url);

        //商戶訂單號(hào),商戶網(wǎng)站訂單系統(tǒng)中唯一訂單號(hào),必填
        String out_trade_no = orderId;
        //付款金額,必填
        BigDecimal total_amount = order.getTotalPrice();
        //訂單名稱,必填
        int subject = order.getOrderId();
        //商品描述,可空
        String body = "用戶訂購(gòu)商品個(gè)數(shù):" + order.getLineItems().size();

        // 該筆訂單允許的最晚付款時(shí)間,逾期將關(guān)閉交易。取值范圍:1m~15d。m-分鐘,h-小時(shí),d-天,1c-當(dāng)天(1c-當(dāng)天的情況下,無(wú)論交易何時(shí)創(chuàng)建,都在0點(diǎn)關(guān)閉)。 該參數(shù)數(shù)值不接受小數(shù)點(diǎn), 如 1.5h,可轉(zhuǎn)換為 90m。
        String timeout_express = "1c";

        alipayRequest.setBizContent("{"out_trade_no":""+ out_trade_no +"","
                + ""total_amount":""+ total_amount +"","
                + ""subject":""+ subject +"","
                + ""body":""+ body +"","
                + ""timeout_express":""+ timeout_express +"","
                + ""product_code":"FAST_INSTANT_TRADE_PAY"}");

        //請(qǐng)求
        String result = alipayClient.pageExecute(alipayRequest).getBody();

        return result;
    }
    @RequestMapping(value = "/alipayReturnNotice")
    public ModelAndView alipayReturnNotice(HttpServletRequest request, HttpServletRequest response) throws Exception {



        //獲取支付寶GET過(guò)來(lái)反饋信息
        Map<String,String> params = new HashMap<String,String>();
        Map<String,String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //亂碼解決,這段代碼在出現(xiàn)亂碼時(shí)使用
            valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }

        boolean signVerified = AlipaySignature.rsaCheckV1(params, AlipayConfig.alipay_public_key, AlipayConfig.charset, AlipayConfig.sign_type); //調(diào)用SDK驗(yàn)證簽名

        ModelAndView mv = new ModelAndView("alipaySuccess");
        //——請(qǐng)?jiān)谶@里編寫您的程序(以下代碼僅作參考)——
        if(signVerified) {
            //商戶訂單號(hào)

            Order order= (Order) request.getSession().getAttribute("order");
            BigDecimal out_trade_no = order.getTotalPrice();

            //支付寶交易號(hào)
            String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"),"UTF-8");

            //付款金額
            String total_amount = new String(request.getParameter("total_amount").getBytes("ISO-8859-1"),"UTF-8");

            // 修改叮當(dāng)狀態(tài),改為 支付成功,已付款; 同時(shí)新增支付流水



           /* Orders order = orderService.getOrderById(out_trade_no);
            Product product = productService.getProductById(order.getProductId());

            log.info("********************** 支付成功(支付寶同步通知) **********************");
            log.info("* 訂單號(hào): {}", out_trade_no);
            log.info("* 支付寶交易號(hào): {}", trade_no);
            log.info("* 實(shí)付金額: {}", total_amount);
            log.info("* 購(gòu)買產(chǎn)品: {}", product.getName());
            log.info("***************************************************************");*/


            mv.addObject("out_trade_no", out_trade_no);
            mv.addObject("trade_no", trade_no);
            mv.addObject("total_amount", total_amount);
          /*  mv.addObject("productName", product.getName());*/

        }else {
           /* log.info("支付, 驗(yàn)簽失敗...");*/
        }

        return mv;
    }
    /**
     *
     * @Title: AlipayController.java
     * @Package com.sihai.controller
     * @Description: 支付寶異步 通知頁(yè)面
     * Copyright: Copyright (c) 2017
     * Company:FURUIBOKE.SCIENCE.AND.TECHNOLOGY
     *
     * @author sihai
     * @date 2017年8月23日 下午8:51:13
     * @version V1.0
     */
    @RequestMapping(value = "/alipayNotifyNotice")
    @ResponseBody
    public String alipayNotifyNotice(HttpServletRequest request, HttpServletRequest response) throws Exception {



        //獲取支付寶POST過(guò)來(lái)反饋信息
        Map<String,String> params = new HashMap<String,String>();
        Map<String,String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //亂碼解決,這段代碼在出現(xiàn)亂碼時(shí)使用
//			valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }

        boolean signVerified = AlipaySignature.rsaCheckV1(params, AlipayConfig.alipay_public_key, AlipayConfig.charset, AlipayConfig.sign_type); //調(diào)用SDK驗(yàn)證簽名

        //——請(qǐng)?jiān)谶@里編寫您的程序(以下代碼僅作參考)——

		/* 實(shí)際驗(yàn)證過(guò)程建議商戶務(wù)必添加以下校驗(yàn):
		1、需要驗(yàn)證該通知數(shù)據(jù)中的out_trade_no是否為商戶系統(tǒng)中創(chuàng)建的訂單號(hào),
		2、判斷total_amount是否確實(shí)為該訂單的實(shí)際金額(即商戶訂單創(chuàng)建時(shí)的金額),
		3、校驗(yàn)通知中的seller_id(或者seller_email) 是否為out_trade_no這筆單據(jù)的對(duì)應(yīng)的操作方(有的時(shí)候,一個(gè)商戶可能有多個(gè)seller_id/seller_email)
		4、驗(yàn)證app_id是否為該商戶本身。*/

        if(signVerified) {//驗(yàn)證成功
            //商戶訂單號(hào)
            String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"),"UTF-8");

            //支付寶交易號(hào)
            String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"),"UTF-8");

            //交易狀態(tài)
            String trade_status = new String(request.getParameter("trade_status").getBytes("ISO-8859-1"),"UTF-8");

            //付款金額
            String total_amount = new String(request.getParameter("total_amount").getBytes("ISO-8859-1"),"UTF-8");

            if(trade_status.equals("TRADE_FINISHED")){
                //判斷該筆訂單是否在商戶網(wǎng)站中已經(jīng)做過(guò)處理
                //如果沒(méi)有做過(guò)處理,根據(jù)訂單號(hào)(out_trade_no)在商戶網(wǎng)站的訂單系統(tǒng)中查到該筆訂單的詳細(xì),并執(zhí)行商戶的業(yè)務(wù)程序
                //如果有做過(guò)處理,不執(zhí)行商戶的業(yè)務(wù)程序

                //注意: 尚自習(xí)的訂單沒(méi)有退款功能, 這個(gè)條件判斷是進(jìn)不來(lái)的, 所以此處不必寫代碼
                //退款日期超過(guò)可退款期限后(如三個(gè)月可退款),支付寶系統(tǒng)發(fā)送該交易狀態(tài)通知
            }else if (trade_status.equals("TRADE_SUCCESS")){
                //判斷該筆訂單是否在商戶網(wǎng)站中已經(jīng)做過(guò)處理
                //如果沒(méi)有做過(guò)處理,根據(jù)訂單號(hào)(out_trade_no)在商戶網(wǎng)站的訂單系統(tǒng)中查到該筆訂單的詳細(xì),并執(zhí)行商戶的業(yè)務(wù)程序
                //如果有做過(guò)處理,不執(zhí)行商戶的業(yè)務(wù)程序

                //注意:
                //付款完成后,支付寶系統(tǒng)發(fā)送該交易狀態(tài)通知

                // 修改叮當(dāng)狀態(tài),改為 支付成功,已付款; 同時(shí)新增支付流水
               /* orderService.updateOrderStatus(out_trade_no, trade_no, total_amount);

                Orders order = orderService.getOrderById(out_trade_no);
                Product product = productService.getProductById(order.getProductId());

                log.info("********************** 支付成功(支付寶異步通知) **********************");
                log.info("* 訂單號(hào): {}", out_trade_no);
                log.info("* 支付寶交易號(hào): {}", trade_no);
                log.info("* 實(shí)付金額: {}", total_amount);
                log.info("* 購(gòu)買產(chǎn)品: {}", product.getName());
                log.info("***************************************************************");*/
            }
           /* log.info("支付成功...");*/

        }else {//驗(yàn)證失敗
           /* log.info("支付, 驗(yàn)簽失敗...");*/
        }

        return "success";
    }

基本就是根據(jù)客服下單的信息進(jìn)行后端數(shù)據(jù)的獲取。

以上就是關(guān)于Springboot項(xiàng)目中添加支付接口的詳細(xì)內(nèi)容,想要了解更多關(guān)于springboot添加支付接口的資料,請(qǐng)關(guān)注W3Cschool其它相關(guān)文章!也希望大家能夠多多支持我們!

0 人點(diǎn)贊