SpringBoot+Alipay: realize the whole process of sandbox payment

1. Introduce required dependencies

 <!--Payment dependency-->
        <dependency>
            <groupId>com.alipay.sdk</groupId>
            <artifactId>alipay-sdk-java</artifactId>
            <version>4.22.113.ALL</version>
        </dependency>

2. Log in to the Alipay open platform and enter the personal sandbox environment. This information needs to be filled in the configuration class below.

e7dfd38f2c6e4593b7b4d04faf579d0b.png

3. View key information

70fb5f589aa1443fa0066e8a9eeb26c6.png

4. Write a tool class. The relevant information is available in the personal sandbox environment and you can modify it yourself (relevant keys can be viewed by clicking on the system default key).

public class AlipayConfig {
    /**
     *Alipay gateway address
     */
    public static String serverUrl = "https://openapi.alipaydev.com/gateway.do";
    /**
     *appId
     */
    public static String appId = "2021000119697439";
    /**
     * Apply private key and later replace it with your own private key
     */
    public static String privateKey = "MIIEvgIBADANBgkqhkiG9w0BAQEFAAASCBKgwggSkAgEAAoIBAQC3PgI3lAW40dRwevBzwxdUkKGhjVIX9K4zuUmCeF5PhWo11LGTmhjrTpBEq/BiBa/v1yZl + 3/3/eU14aGxwE86 qMnUEiweNVIclp9Gh2o85RiB2EGXyAi5wvTdwziZ50P2s/5VFzyhjjU/Pj6XKg + SShc1gyFsEfttGnMsvP3tm44XsxtRFvTZBqGV90sZ61H9DzRVxHf4dfhnRLJvRFVYC + 2XdGFwP + 1 + UOhCdjOJla6wkrz9B0kvXB1XdAdJHuXTvisTRgBDnc8lY2tyA9RIfAceqHFHub1x0Q0V2HDgYcd2EllGCDP/MLeLAKbGC4H + bh6w57h3NkhbhA/ER8adAgMBAAECggEAGpWgdLfA7MNkcr0jTWgsZlRlX q7GDjutWkuzYn5cEGVmt1CYQrXEj77iJ1Ral54DnGQ2ae1G74 + iRWLq + 4qpXV8Vj3xk4Ujo6q6Styr1l0DsozyeJ3UlWVcNSybGMXCDoYyxey7KgtZg9kVf5PVi0JypqKgjNfz0YLU6 kdIUouYbmz7HPBRQSV3mLclAUiJmbiVa7g6luV/PyNJFh3c1PITvsXah6gvOmOuARn3ZadHvS546AbLYmerVI0c3/Y7HOW5XyLnR + EzzqA + PXtXAV/RV67ywhb9KSEJBevsbPe83ZQkzkoXhKZF NhQb5QdmDXmNA6cRZ1hW6ohuhcQKBgQDlwzuAA3MHpQ3MLfyuUUD1o2fvQ9hymURm4BGzHrPlSz + 3yWIuNyUKCfbtslqdGeHPXTlOaKtBiS2wrVbv/JaNA/Elzl + BZgkNCcb3tnsha7e522syHdgapdPrXyGSDN69mIZsWoRJQlGpRISJnd75XClZf3nGlr4g4hV9 + dS3rwKBgQDMKtJUSxlb 8rf9NZ/xOmklcLxBgFGo39noVS + FDz5O1P1o3I1LSHF + vOTkkqLTO4TrEtr2q0Ijb/xj65wX42i0Av2t63fbMEAkYTatih8Pve9LtX1G6nv2Fw9U/ZDOUKRdhPO2GDG59SifXEgDI4eV29AZh h4oqwRH7wz5neitcwKBgQCg2SR2YfPNjkcygZ87ibaoQFUqs5x73cB9JLA/bWcTRrK8v0b0g7ZyaLdtgEbfZJcozGKp + ayqnJZX8YHDUFk1L2VKykciF4SOlCGumRlqNDbS7kEFPM9lGGJbjK W70Ta + FGFGybeCceMpVMZUcSj/ + P0Zopxl4nIIIz5YiuXYEQKBgDmC8n6WLQ2OoK9uFKDiIE5QpGcbG2WjsQFWRa2IrreMHdoVDqQfQwE9eoi8matA/98sD4wej + HloMYQz4aXI55ZnVYJl1ii Dd9xlvJpjvhjO24rMJ/yW3rl4gbB6rGDW9mQIwqvZAqK + adyWkKwFnhrVAJsmkBAdFNDDneeOLXrAoGBAOEsOJ76yaxY3RGrvWnGm7aA/tyVLNtpz3Hj0T/zTN24bsKm5TwuobVq5jVvQ 2UagBQRlGAl3mP6XiVv0NclDPRupSCOjhkbLlMw + B6rE5uV7HkxtrtHsSFaruehRI94K6tbGNQJdImqWjHKBIjqoHr8snLk41vXxxwyK2G38puD";
    /**
     * The format of sending data is currently only json
     */
    public static String format = "json";
    /**
     * Set the character set encoding. Currently it can only be utf-8
     */
    public static String charset = "utf-8";
    /**
     * Alipay public key will be replaced with your own Alipay public key later.
     */
    public static String publicKey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAh2yYUlCpO6tNqNa + svqMJfnl1Ax9LrOAf8bNxexVPIJh6LF77ca4qVPpuYTbvQNuGEMDSP35uZ3g + Vch3WasIaYy/D36NfOV jPzrB2b3cXKbUSEjgRawnx15oyBj687tOKEJcPO9okGUgYr2/HkVQPVU0IpFZVRfcRk8BbadS7AOz38RtRYteY1bu + YVFWqf0O0WTILHAZeDpLqENhgHjmj1ATKdCPel0K2US/uCSe6rPJgclFHplEBKI 9ysfTKfhEKNhj56w6CrG7XQ1MQHZI1V7rR2busYRntoHh/DB6CZSiv/X5L8 + TxZvAtUCn + z6Ns + 8e3LfG1/bq59OU0wIDAQAB";
    /**
     * Alipay signature is currently RSA2
     */
    public static String signType = "RSA2";
    public static AlipayClient getAlipayClient() {
        // Get the initialized AlipayClient
        return new DefaultAlipayClient(AlipayConfig.serverUrl, AlipayConfig.appId,
                AlipayConfig.privateKey, AlipayConfig.format, AlipayConfig.charset, AlipayConfig.publicKey,
                AlipayConfig.signType);
    }
}

4. Write a controller and simulate the request interface

package com.lili.controller;

import com.alipay.api.AlipayClient;
import com.alipay.api.domain.AlipayTradePayModel;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.lili.util.AlipayConfig;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author QiJingJing
 * @since 2022/12/31
 */
@RestController
@RequestMapping("alipay")
public class PayController {
    /**
     * Payment request interface
     */
    @RequestMapping("pay/{orderId}/{cost}") // Order id (cannot be repeated) and consumption amount
    public void pay(@PathVariable String orderId,@PathVariable String cost, HttpServletResponse response){
        try {
            AlipayClient alipayClient = AlipayConfig.getAlipayClient();
            //Set request parameters
            AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
            AlipayTradePayModel model = new AlipayTradePayModel();
            // Setting the order number must be written, and the order number cannot be repeated. It is currently just for testing and has been hard-coded.
            model.setOutTradeNo(orderId);
            //Set the order amount
            model.setTotalAmount(cost);
            // Order name
            model.setSubject("Book Order");
            // order description
            model.setBody("This is a consumption order for a book");
            // product code
            model.setProductCode("FAST_INSTANT_TRADE_PAY");
            // Setting parameters
            alipayRequest.setBizModel(model);
            //Set callback address
            String url = "http://localhost:8080/alipay/success?orderId=" + orderId + "";
            System.out.println(url);
            alipayRequest.setReturnUrl(url);
            String result = alipayClient.pageExecute(alipayRequest).getBody();
            response.setContentType("text/html;charset=utf-8");
            response.getWriter().println(result);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    /**
     * After successful payment, call back the page
     */
    @RequestMapping("success")
    public void success(@RequestParam("orderId") String orderId, HttpServletResponse response) throws IOException {
        response.setContentType("text/html;charset=utf-8");
        response.getWriter().println("The order with orderId" + orderId + "has been paid successfully");
    }
}

5. Visit http://localhost:8080/alipay/pay/23232/509 with the browser

The order number is 23232 and the amount is 509 yuan. After pressing Enter, you can see the following page.

c29d77aeb2bf4a80b4d95e123480206f.png

Click on the order details to see the information about our order:

37386f23939249ccb2a12850b45f6f54.png

6. We need to log in to the buyer’s account to log in.

a821b54273b04385894767d462a41584.png

7. After the login is completed, the following page will appear (if the balance is not enough, you can recharge on the above page)

2b706745d2fa46e0adadbcf46ef4a92e.png

8. After the payment is completed, you can successfully jump to the callback address we set.

9d53a0b0c6164beda7d94d482775be45.png

d409e734577f41c28ddab2023d194a1b.png

The knowledge points of the article match the official knowledge files, and you can further learn relevant knowledge. Java skill treeUsing JDBC to operate the databaseDatabase operation 135242 people are learning the system