1. Alipay payment interface (sandbox implementation)

1.1 Obtaining alipay Sandbox account

website

Here the author has applied for a sandbox account, the application process will not be described

The diagram below:

You can set the account amount by yourself

1.2 Download the client (seems to only support Android at present)

After downloading, log in the mobile Alipay account (merchant account) according to the official account and password as shown in the figure below:

1.3 Code Configuration

Utility class AlipayConfig

public class AlipayConfig {

//↓↓↓↓↓↓ Enter your basic information here

    // Application ID, your APPID, receivables account is your APPID corresponding to alipay account
    public static String app_id = "";

    // Merchant private key, your PKCS8 format RSA2 private key
    public static String merchant_private_key = "MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQC/HOeQNyultzkc5cUnqxBSTIpYt6BTgJoCHKiLQDYgPhjvSX16r08Qw82qYdQgWEs4hHN y2COGA5ksw1eW+zyY2alcTEvRMo4sqx7Ytdm250f67wZQkuPRFSJN7ywHkTipjGKNcS9z9U0Dp18jRXHow4/A9OF8jOau7pWyG0Tc87WHf5u0/G16uMpRtGR zzyNvim7cHAnyFPNrAJ+5DRBdhBg+PjV7EcpYg5LRaMqaO8qDSis+AUU4e7QOELqMgr7yxBNScQ6KksnWnztcFxz6M9T66dAZJ0dWpiB8qatM6sT/MeHTAXe YLhIbnUaxM9vGJR3AJHbHmvNa9o0ToT0LAgMBAAECggEBAIk1a1szAPc9EJgaru3H9zPfGASR8V2CGxAhGzC+rR2A9830aU5HxvA2Y9ZL3kxKl9a/4VM2smp o8vQcWypevibPPrSxYk2Tilevk7nq9aBHdHpIWbRHgaB/F930NRxJuvCfhbIe7P7Hwr84zyk3loySuwbByZHuZ0B4sqjowwwN/wbshl5m/5i4ej6AUp1LVEb xUFpNHNjIZejWVJ0Liq69l8o+1HsFIaGW1Vcrf+fmq20moZzFOLi4EmGfBp/na8JDmo3bE3X+ccAJ375OYictfZVKKYI/UIC/D+7y4XuZatLq3V3lql5ukMn AUJwTJeEapSigkJHDOX38xcSA7iECgYEA5qvIl7PGl8CwDOgTe8LoT8toTUmhAVDFwSF+ROCZD8u9qQeGG7SSCovoTQcVDuzVA3bW8d4Guvb7ZTpnUZZyWHD 2rOqxh66wqHGiVTJRApNTS7XHXt3FERNgM7Y8lSoYHdarsZ7QZaJDGGkcwuGvJM0klwyuqs6LQq5DRsz9qp8CgYEA1BkiCjD5FUE/i48MFh+qYcOSiqsm7Hr j/4zuHj0QODonuUZPH0V6b3p4SIWHeBsjmSxBsqoLh2qFOzWAUeBVU3+muPHp3uglumtjZ5wE0nHCt2+0ZH+QKSk5mm8j+09xfTJ185FMusx0N9RQ4l6Rpzb 7DSLQFelT4M7gvTRjAhUCgYAtUPQwcV4DdBRiBLnHJ4xSGMjd3igmRQMEpRrUVzdathEFgvfiu3+xWLkDYO/PJdHXQ2KI07CIzHqo8WdYzPCb1V1wrQ7BdB0 6ilB04lSt59mGVyjax0Cu0RqmLhgKyeFBA2ppk6SnQtBhnEzNMF8jILYegpxR7A/JwshuwVjYSwKBgQCTxfMGgLp6iZxZgs/b9jICrX1DKh4Tc0e5PBqHbOo JEtOsbYUg94pncz+s34PUNaxmwwP/FCS2M4wiBZOi+Bba9zxU7Q+R49KtgLagcH6XlPUiUyyvPIVXeEaPB9Jc/SvIG8k8a0a3e02ZvE6G1hETQj2GGZv0ENi SpRQKBgC8qOk7TMndVDi3vlgGky3BmxSpycwGnI0tcBZnzAyzcLPH3RL3nLvUoZ1w550be7mPDt30/WkCMKV8uKRnNVSrp1LSbT0Z6oJxsaHaCxv3C2UFzlq KWsTtiKNKhYEhjsMYj6l2nRg2CC0WIAA6MPP3xaezSWO1la39Slam0w3l";

    / / alipay public key, check the address: https://openhome.alipay.com/platform/keyManage.htm under the corresponding APPID alipay public key.
    public static String alipay_public_key = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAvxznkDcrpbc5HOXFJ6sQUkyKWLegU4CaAhyoi0A2ID4Y70l9eq9PEMPNqmHUIFhLOIRzctgjhgO ZLMNXlvs8mNmpXb4pu3BwJ8hTzawCfuQ0QXYQYPj41exHKWIOS0WjKmjvKg0orPgFFOHu0DhC6jIK+8sQTUnEOipLJ1p87XBcc+jPU+unQGSdHVqYgfKmrTO rE/zHh0wF3mC4SG51GsTPbxiUdwCR2x5rzWvaNE6E9CwIDAQAB";

    // The server asynchronous notification page path must be in the format of http://. User-defined parameters, such as ID =123, must be accessible from the Internet
    public static String notify_url = "http://localhost:8080/alipay/alipayNotifyNotice.action";

    The page path is in the format of http://and cannot be added with?. User-defined parameters, such as ID =123, must be accessible from the Internet
    public static String return_url = "http://localhost:8080/alipay/alipayReturnNotice.action";

    // Signature mode
    public static String sign_type = "RSA2";

    // Character encoding format
    public static String charset = "utf-8";

    // Alipay gateway
    public static String gatewayUrl = "https://openapi.alipaydev.com/gateway.do";

    // Alipay gateway
    public static String log_path = "C:\\";


// Please configure your basic information here

    /** * Keep a log for testing purposes **@paramSWord The text to be written in the log */
    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();
                }
            }
        }
    }
}
Copy the code

The value can be app_id

Refer to the official document: Key Generation for obtaining merchant private key and Alipay public key

Page jump is the automatic jump after payment interface

To explain how to write an order page:


/ * * * *@Title: AlipayController.java
     * @Package com.sihai.controller
     * @Description: pay * gateway to pay treasure to third party Copyright, Copyright (c) 2017 * Company: FURUIBOKE. SCIENCE. AND the 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";

        // Get the 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 the 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 merchant website, mandatory
        String out_trade_no = orderId;
        // Amount of payment, mandatory
        BigDecimal total_amount = order.getTotalPrice();
        // Order name, mandatory
        int subject = order.getOrderId();
        // Product description can be empty
        String body = "Number of goods ordered by user:" + order.getLineItems().size();

        // The latest payment time allowed for this order will close the transaction. Value range: 1 MB to 15 days. M - minutes, H - hours, D - days, 1c- Day (1c- Day case, closes at 0 whenever a trade is created). The value of this parameter does not accept decimal points. For example, 1.5h can be converted 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;
    }
    @RequestMapping(value = "/alipayReturnNotice")
    public ModelAndView alipayReturnNotice(HttpServletRequest request, HttpServletRequest response) throws Exception {



        // GET alipay GET feedback information
        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] +",";
            }
            // This code is used when there is a garble
            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); // Invoke the SDK to verify the signature

        ModelAndView mv = new ModelAndView("alipaySuccess");
        // -- write your program here (the following code is for reference only) --
        if(signVerified) {
            // Merchant order number

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

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

            // Amount of payment
            String total_amount = new String(request.getParameter("total_amount").getBytes("ISO-8859-1"),"UTF-8");

            // Change the status of dingdong to "payment succeeded"; At the same time new payment flow



           /* Orders order = orderService.getOrderById(out_trade_no); Product product = productService.getProductById(order.getProductId()); The info (" * * * * * * * * * * * * * * * * * * * * * * pay success (alipay, synchronous notification) * * * * * * * * * * * * * * * * * * * * * * "); Log.info ("* order number: {}", out_trade_no); Log.info ("* alipay transaction number: {}", trade_no); Log.info ("* paid amount: {}", total_amount); Log.info ("* Buy product: {}", 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(" pay, check failed...") ); * /
        }

        return mv;
    }
    / * * * *@Title: AlipayController.java
     * @Package com.sihai.controller
     * @Description: alipay, asynchronous notification page * Copyright: Copyright (c) 2017 * Company: FURUIBOKE. SCIENCE. AND the TECHNOLOGY * *@author sihai
     * @dateAugust 23, 2017 8:51:13 PM *@versionV1.0 * /
    @RequestMapping(value = "/alipayNotifyNotice")
    @ResponseBody
    public String alipayNotifyNotice(HttpServletRequest request, HttpServletRequest response) throws Exception {



        // Get feedback from Alipay POST
        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] +",";
            }
            // This code is used when there is a garble
// 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); // Invoke the SDK to verify the signature

        // -- write your program here (the following code is for reference only) --

		/* During the actual verification process, merchants are advised to add the following verification: 1. Verify whether out_trade_NO in the notification data is the order number created in the merchant system; 2. Determine whether total_amount is indeed the actual amount of the order (i.e., the amount when the merchant order was created); Verify that seller_id (or seller_email) in the notification is out_trade_no (sometimes a merchant may have multiple seller_id/seller_email). Verify that app_id is the merchant itself. * /

        if(signVerified) {// Verification succeeded
            // 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");

            // Transaction status
            String trade_status = new String(request.getParameter("trade_status").getBytes("ISO-8859-1"),"UTF-8");

            // Amount of payment
            String total_amount = new String(request.getParameter("total_amount").getBytes("ISO-8859-1"),"UTF-8");

            if(trade_status.equals("TRADE_FINISHED")) {// Determine whether the order has already been processed on the merchant's website
                // If no processing has been done, check the details of the order in the order system of the merchant website according to the order number (out_trade_no) and execute the merchant's business procedures
                // If any processing has been done, the merchant's business procedures are not executed

                // Note: there is no refund function for self-study orders. This condition can not be entered, so there is no need to write code here
                // After the refund date exceeds the refundable period (such as three months refundable), alipay system will send the transaction status notification
            }else if (trade_status.equals("TRADE_SUCCESS")) {// Determine whether the order has already been processed on the merchant's website
                // If no processing has been done, check the details of the order in the order system of the merchant website according to the order number (out_trade_no) and execute the merchant's business procedures
                // If any processing has been done, the merchant's business procedures are not executed

                / / note:
                // After the payment is completed, alipay system will send the transaction status notification

                // Change the status of dingdong to "payment succeeded"; At the same time new payment flow
               /* orderService.updateOrderStatus(out_trade_no, trade_no, total_amount); Orders order = orderService.getOrderById(out_trade_no); Product product = productService.getProductById(order.getProductId()); The info (" * * * * * * * * * * * * * * * * * * * * * * pay success (alipay, asynchronous notification) * * * * * * * * * * * * * * * * * * * * * * "); Log.info ("* order number: {}", out_trade_no); Log.info ("* alipay transaction number: {}", trade_no); Log.info ("* paid amount: {}", total_amount); Log.info ("* Buy product: {}", product.getName()); log.info("***************************************************************"); * /
            }
           /* log.info(" payment successful...") ); * /

        }else {// Verification failed
           /* log.info(" pay, check failed...") ); * /
        }

        return "success";
    }

Copy the code

Basically, the back-end data is obtained according to the information of customer orders.