当前位置:网站首页>Alipay payment interface sandbox environment test and integration into an SSM e-commerce project

Alipay payment interface sandbox environment test and integration into an SSM e-commerce project

2022-06-25 23:50:00 Program diary

preparation

  • official demo
  • Alipay account
  • eclipse/idea
  • tomcat

Specific steps

  1. First download the official demo
    https://docs.open.alipay.com/270/106291/
  2. Import to eclipse in
    Be careful : Because of this demo No maven The project has to be configured locally tomcat
     Insert picture description here
  3. Register a developer account on the Alipay open platform , Enter sandbox
     Insert picture description here
  4. Enter the sandbox and you will see a appid And Alipay gateway for testing , This configuration file is used to configure our project , We'll use that later
  5. Generate application key and application public key
     Insert picture description here
    Download the Alipay open platform development assistant according to the steps described , Generate application key and application public key
     Insert picture description here
    And configure and apply the public key in the sandbox environment
     Insert picture description here
    After configuration, there will be a Alipay public key , This also needs to be configured in the configuration file
  6. About demo
    There is a pile of jsp Documents and a config class , Actually jsp It is also written in the document java Code
    config class : Parameters to be configured
    app_id: It's in your sandbox appid, If the application is formal, there will also be one appid
    merchant_private_key: Application of the private key , The application private key just generated
    alipay_public_key: Alipay public key , This is the Alipay public key generated after the application public key just configured in the sandbox is configured , Note that the application public key is not configured here !
    notify_url: This is the path of the asynchronous notification page of the Alipay server , The details of how to handle the code are in notify_url.jsp in
    return_url: This is the path to the synchronization notification page of Alipay server , After the payment is completed, you will be prompted to jump to the merchant page, that is, this page , The specific code can be seen demo Medium return_url.jsp
    gatewayUrl: This is very important , It is the gateway of Alipay , Because we are a sandbox environment, we must configure the gateway for testing
  7. Run the test
    function index.jsp
     Insert picture description here
    Click pay , You will successfully jump to the code scanning page ( If prompted phishing sites , It is recommended to change the browser or close the browser page about Alipay before paying )
     Insert picture description here
    How to pay ?
    At this time, note that the sandbox provides a test account number , You can download the sandbox version of Alipay app Log in to the test account for payment , It's fine too , Click the login account payment on the right to make payment
    Sandbox account :
     Insert picture description here
    After payment
     Insert picture description here
    It also jumps to the synchronization notification page
    The same is true of the basic process .

Integrate to ssm In the project

General train of thought : There is a shopping cart settlement page in the project , Click submit order ,controller In dealing with , View the payment method for this order , If it is online payment, jump to another controller in , This controller That is to say demo Process payment jump in jsp The code in , And one more return_url Used to synchronize page notifications , This configuration is also a controller To handle jump to a success.jsp Page of successful payment , This controller In addition to jumping to the payment success page, you can also process the business logic of changing the order status to paid
First, click submit order , You need to create an order , Then determine the order status , Cash on delivery or online payment

@RequestMapping("/create")
    public String orderCreate(Order order, Model model,HttpServletRequest request){
    
        try {
    
            System.out.println(" The payment method is :"+order.getPaymentType());

            // Get user information , because order The following are intercepted by interceptors , The interceptor stores the user information in the request 
            TbUser user = (TbUser) request.getAttribute("user");
            // Set user information , Complete the user information before submitting the order 
            order.setBuyerNick(user.getUsername());
            order.setUserId(user.getId());
            String orderId = orderService.createOrder(order);
            // After creating the order , If the payment method of the order is 4, On behalf of online payment , We want to jump to the online payment page 
            if(order.getPaymentType() == 4){
    
                return "redirect:/order/goAliPay/"+orderId+".html";
            }
            model.addAttribute("paymentType",order.getPaymentType());
            model.addAttribute("orderId",orderId);
            model.addAttribute("payment",order.getPayment());
            model.addAttribute("date",new DateTime().plusDays(3).toString("yyyy-MM-dd"));
            return "success";
        } catch (Exception e) {
    
            e.printStackTrace();
            model.addAttribute("message"," There's a problem ...");
            return "/error/exception";
        }
    }

Pay online , Jump to another controller, Note that there is a coding setting here , If not set to UTF-8 The signature verification will fail , And the interface css The problem of style disappearing .

@RequestMapping(value = "/goAliPay/{orderId}",produces = "text/html; charset=UTF-8")
    @ResponseBody
    public String goAlipay(@PathVariable String orderId, HttpServletRequest request, HttpServletRequest response) throws Exception {
    

        // according to orderId Get order information 
        Order order = orderService.getOrderByOrderId(orderId);

        // Get initialized AlipayClient
        AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id, AlipayConfig.merchant_private_key, "json", AlipayConfig.charset, AlipayConfig.alipay_public_key, AlipayConfig.sign_type);

        // Set request parameters 
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        alipayRequest.setReturnUrl(AlipayConfig.return_url);
        alipayRequest.setNotifyUrl(AlipayConfig.notify_url);

        // Merchant order number , The unique order number in the order system of the merchant website , Required 
        String out_trade_no = orderId;
        // The payment amount , Required 
        String total_amount = order.getPayment();
        // Name of the order , Required 

        String subject = order.getOrderItems().get(0).getTitle();
        // Commodity Description , Can be empty 
        String body = order.getOrderItems().get(0).getTitle();

        //  Latest payment time allowed for this order , Transaction will be closed if overdue . Value range :1m~15d.m- minute ,h- Hours ,d- God ,1c- same day (1c- In the case of the day , Whenever a transaction is created , All in 0 Point closure ).  Decimal point is not accepted for this parameter value ,  Such as  1.5h, Convertible to  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\"}");

        // request 
        String result = alipayClient.pageExecute(alipayRequest).getBody();

        return result;
    }

Payment success synchronization notification page controller

@RequestMapping("/paySuccess")
    public String paySuccess(HttpServletRequest request, HttpServletResponse response,Model model) throws Exception {
    
        // Access to alipay GET Come and give me feedback 
        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] + ",";
            }
            // The code to solve , This code is used in case of garbled code 
            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); // call SDK Verify the signature 

        if(signVerified) {
    
            // Merchant order number 
            String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"),"UTF-8");

            // Alipay transaction number 
            String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"),"UTF-8");

            // The payment amount 
            String total_amount = new String(request.getParameter("total_amount").getBytes("ISO-8859-1"),"UTF-8");
            Order order = orderService.getOrderByOrderId(out_trade_no);
            order.setStatus(2);
            // Modify order status 
            Integer integer = orderService.changeStatus(order);
            // Return to normal modification success 
            if (integer == 200){
    
                // There is also an additional payment method for the order 
                model.addAttribute("paymentType",order.getPaymentType());
                model.addAttribute("orderId",order.getOrderId());
                model.addAttribute("payment",order.getPayment());
                model.addAttribute("date",new DateTime().plusDays(3).toString("yyyy-MM-dd"));
                return "success";
            }else{
    
                return "/error/exception";
            }
        }else {
    
            System.out.println(" Attestation of failure ");
        }
        return "/error/exception";
    }

This is also copied demo The code in can be slightly modified
The overall integration process is like this , The key to integration is to analyze demo Medium alipay.trade.page.pay.jsp and return_url.jsp and notify_url.jsp, There are very detailed instructions in it !
The integration of payment interface and project is over

原网站

版权声明
本文为[Program diary]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/176/202206252101116170.html