SpringBoot integrates Alipay payment - read this article without detours

I am working on a website recently, and the backend uses SpringBoot, which needs to integrate Alipay for online payment. In the process, I have studied a lot of Alipay integration information, and I have also taken some detours. Now I summarize it. I believe you can easily integrate it after reading it. Pay with Ali-Pay.

Before starting to integrate Alipay payment, we need to prepare an Alipay merchant account. If it is an individual developer, it can be authorized by registering a company or a unit with company qualifications. This information needs to be provided when integrating related APIs.

Let me take online payment on the computer web page as an example to introduce the entire process from integration, testing to launch.

1. Expected effect display

Before we start, let's take a look at the final effect we want to achieve, as follows:

  1. Front-end click payment to jump to Alipay interface
  2. Alipay interface display payment QR code
  3. User mobile payment
  4. After the payment is completed, Alipay calls back the url specified by the developer.

2. Development process

2.1 Sandbox debugging

Alipay has prepared a complete sandbox development environment for us. We can debug the program in the sandbox environment first, and after creating a new application and successfully launching it, replace the corresponding parameters in the program with online parameters.

1. Create a sandbox application

Go directly to  http://open.alipay.com/develop/san ... to create a sandbox application,

Here, because it is a test environment, we just choose the system default key. Next, choose the public key mode. In addition, the application gateway address is the url that Alipay will call back after the user completes the payment. In the development environment, we can use the intranet penetration method to expose our local port to a public network address. Here we recommend  http://natapp.cn/  , which can be registered and used for free.

2. SpringBoot code implementation

After creating the sandbox application and obtaining the key, APPID, merchant account PID and other information, you can develop and integrate the corresponding API in the test environment. Here I take the computer-side payment API as an example to introduce how to integrate.

For detailed product introduction and API access documents about computer website payment, please refer to: http://opendocs.alipay.com/open/repo-0 … and  http://opendocs.alipay.com/open/270/01
  • Step 1. Add the Maven dependency corresponding to alipay sdk.
<!-- alipay -->  
<dependency>  
   <groupId>com.alipay.sdk</groupId>  
   <artifactId>alipay-sdk-java</artifactId>  
   <version>4.35.132.ALL</version>  
</dependency>
  • Step 2, add Alipay order, synchronous call and asynchronous call interface after successful payment.
It should be noted here that the synchronous interface is the address that will automatically jump after the user completes the payment, so it needs to be a Get request. The asynchronous interface is the address where Alipay will call back to notify the payment result after the user completes the payment, so it is a POST request.
@RestController  
@RequestMapping("/alipay")  
public class AliPayController {  
  
    @Autowired  
    AliPayService aliPayService;  
  
    @PostMapping("/order")  
    public GenericResponse<Object> placeOrderForPCWeb(@RequestBody AliPayRequest aliPayRequest) {  
        try {  
            return aliPayService.placeOrderForPCWeb(aliPayRequest);  
        } catch (IOException e) {  
            throw new RuntimeException(e);  
        }  
    }  
  
    @PostMapping("/callback/async")  
    public String asyncCallback(HttpServletRequest request) {  
        return aliPayService.orderCallbackInAsync(request);  
    }  
  
    @GetMapping("/callback/sync")  
    public void syncCallback(HttpServletRequest request, HttpServletResponse response) {  
        aliPayService.orderCallbackInSync(request, response);  
    }  

}
  • Step 3, implement the Service layer code

Here, for the three interfaces in the above controller, complete the methods corresponding to the service layer. The following is the core process of the entire payment. In some places, you need to save the order to the DB or check the order status according to your own actual situation. This can be designed according to actual business needs.

public class AliPayService {  
  
    @Autowired  
    AliPayHelper aliPayHelper;  
  
    @Resource  
    AlipayConfig alipayConfig;  
  
    @Transactional(rollbackFor = Exception.class)  
    public GenericResponse<Object> placeOrderForPCWeb(AliPayRequest aliPayRequest) throws IOException {  
        log.info("【请求开始-在线购买-交易创建】*********统一下单开始*********");  
  
        String tradeNo = aliPayHelper.generateTradeNumber();  
    
        String subject = "购买套餐1";  
        Map<String, Object> map = aliPayHelper.placeOrderAndPayForPCWeb(tradeNo, 100, subject);  
  
        if (Boolean.parseBoolean(String.valueOf(map.get("isSuccess")))) {  
            log.info("【请求开始-在线购买-交易创建】统一下单成功,开始保存订单数据");  
  
            //保存订单信息  
            // 添加你自己的业务逻辑,主要是保存订单数据
  
            log.info("【请求成功-在线购买-交易创建】*********统一下单结束*********");  
            return new GenericResponse<>(ResponseCode.SUCCESS, map.get("body"));  
        }else{  
            log.info("【失败:请求失败-在线购买-交易创建】*********统一下单结束*********");  
            return new GenericResponse<>(ResponseCode.INTERNAL_ERROR, String.valueOf(map.get("subMsg")));  
        }  
    }  
  
    // sync return page  
    public void orderCallbackInSync(HttpServletRequest request, HttpServletResponse response) {  
        try {  
            OutputStream outputStream = response.getOutputStream();  
            //通过设置响应头控制浏览器以UTF-8的编码显示数据,如果不加这句话,那么浏览器显示的将是乱码  
            response.setHeader("content-type", "text/html;charset=UTF-8");  
            String outputData = "支付成功,请返回网站并刷新页面。";  
  
            /**  
             * data.getBytes()是一个将字符转换成字节数组的过程,这个过程中一定会去查码表,  
             * 如果是中文的操作系统环境,默认就是查找查GB2312的码表,  
             */  
            byte[] dataByteArr = outputData.getBytes("UTF-8");//将字符转换成字节数组,指定以UTF-8编码进行转换  
            outputStream.write(dataByteArr);//使用OutputStream流向客户端输出字节数组  
        } catch (IOException e) {  
            throw new RuntimeException(e);  
        }  
    }  
  
    public String orderCallbackInAsync(HttpServletRequest request) {  
        try {  
            Map<String, String> map = aliPayHelper.paramstoMap(request);  
            String tradeNo = map.get("out_trade_no");  
            String sign = map.get("sign");  
            String content = AlipaySignature.getSignCheckContentV1(map);  
            boolean signVerified = aliPayHelper.CheckSignIn(sign, content);  
  
            // check order status  
            // 这里在DB中检查order的状态,如果已经支付成功,无需再次验证。
            if(从DB中拿到order,并且判断order是否支付成功过){  
                log.info("订单:" + tradeNo + " 已经支付成功,无需再次验证。");  
                return "success";  
            }  
  
            //验证业务数据是否一致  
            if(!checkData(map, order)){  
                log.error("返回业务数据验证失败,订单:" + tradeNo );  
                return "返回业务数据验证失败";  
            }  
            //签名验证成功  
            if(signVerified){  
                log.info("支付宝签名验证成功,订单:" + tradeNo);  
                // 验证支付状态  
                String tradeStatus = request.getParameter("trade_status");  
                if(tradeStatus.equals("TRADE_SUCCESS")){  
                    log.info("支付成功,订单:"+tradeNo);  
			        // 更新订单状态,执行一些业务逻辑

                    return "success";  
                }else{  
                    System.out.println("支付失败,订单:" + tradeNo );  
                    return "支付失败";  
                }  
            }else{  
                log.error("签名验证失败,订单:" + tradeNo );  
                return "签名验证失败.";  
            }  
        } catch (IOException e) {  
            log.error("IO exception happened ", e);  
            throw new RuntimeException(ResponseCode.INTERNAL_ERROR, e.getMessage());  
        }  
    }  
  
  
    public boolean checkData(Map<String, String> map, OrderInfo order) {  
        log.info("【请求开始-交易回调-订单确认】*********校验订单确认开始*********");  
  
        //验证订单号是否准确,并且订单状态为待支付  
        if(验证订单号是否准确,并且订单状态为待支付){  
            float amount1 = Float.parseFloat(map.get("total_amount"));  
            float amount2 = (float) order.getOrderAmount();  
            //判断金额是否相等  
            if(amount1 == amount2){  
                //验证收款商户id是否一致  
                if(map.get("seller_id").equals(alipayConfig.getPid())){  
                    //判断appid是否一致  
                    if(map.get("app_id").equals(alipayConfig.getAppid())){  
                        log.info("【成功:请求开始-交易回调-订单确认】*********校验订单确认成功*********");  
                        return true;                    }  
                }  
            }  
        }  
        log.info("【失败:请求开始-交易回调-订单确认】*********校验订单确认失败*********");  
        return false;    }  
}
  • Step 4, implement the alipayHelper class. This class encapsulates the interface of Alipay.
public class AliPayHelper {  
  
    @Resource  
    private AlipayConfig alipayConfig;  
  
    //返回数据格式  
    private static final String FORMAT = "json";  
    //编码类型  
    private static final String CHART_TYPE = "utf-8";  
    //签名类型  
    private static final String SIGN_TYPE = "RSA2";  
  
    /*支付销售产品码,目前支付宝只支持FAST_INSTANT_TRADE_PAY*/  
    public static final String PRODUCT_CODE = "FAST_INSTANT_TRADE_PAY";  
  
    private static AlipayClient alipayClient = null;  
  
    private static final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmssSSS");  
    private static final Random random = new Random();  
  
    @PostConstruct  
    public void init(){  
        alipayClient = new DefaultAlipayClient(  
                alipayConfig.getGateway(),  
                alipayConfig.getAppid(),  
                alipayConfig.getPrivateKey(),  
                FORMAT,  
                CHART_TYPE,  
                alipayConfig.getPublicKey(),  
                SIGN_TYPE);  
    };  
  
    /*================PC网页支付====================*/  
    /**  
     * 统一下单并调用支付页面接口  
     * @param outTradeNo  
     * @param totalAmount  
     * @param subject  
     * @return  
     */  
    public Map<String, Object> placeOrderAndPayForPCWeb(String outTradeNo, float totalAmount, String subject){  
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();  
        request.setNotifyUrl(alipayConfig.getNotifyUrl());  
        request.setReturnUrl(alipayConfig.getReturnUrl());  
        JSONObject bizContent = new JSONObject();  
        bizContent.put("out_trade_no", outTradeNo);  
        bizContent.put("total_amount", totalAmount);  
        bizContent.put("subject", subject);  
        bizContent.put("product_code", PRODUCT_CODE);  
  
        request.setBizContent(bizContent.toString());  
        AlipayTradePagePayResponse response = null;  
        try {  
            response = alipayClient.pageExecute(request);  
        } catch (AlipayApiException e) {  
            e.printStackTrace();  
        }  
        Map<String, Object> resultMap = new HashMap<>();  
        resultMap.put("isSuccess", response.isSuccess());  
        if(response.isSuccess()){  
            log.info("调用成功");  
            log.info(JSON.toJSONString(response));  
            resultMap.put("body", response.getBody());  
        } else {  
            log.error("调用失败");  
            log.error(response.getSubMsg());  
            resultMap.put("subMsg", response.getSubMsg());  
        }  
        return resultMap;  
    }  
  
    /**  
     * 交易订单查询  
     * @param out_trade_no  
     * @return  
     */  
    public Map<String, Object> tradeQueryForPCWeb(String out_trade_no){  
        AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();  
        JSONObject bizContent = new JSONObject();  
        bizContent.put("trade_no", out_trade_no);  
        request.setBizContent(bizContent.toString());  
        AlipayTradeQueryResponse response = null;  
        try {  
            response = alipayClient.execute(request);  
        } catch (AlipayApiException e) {  
            e.printStackTrace();  
        }  
        Map<String, Object> resultMap = new HashMap<>();  
        resultMap.put("isSuccess", response.isSuccess());  
        if(response.isSuccess()){  
            System.out.println("调用成功");  
            System.out.println(JSON.toJSONString(response));  
            resultMap.put("status", response.getTradeStatus());  
        } else {  
            System.out.println("调用失败");  
            System.out.println(response.getSubMsg());  
            resultMap.put("subMsg", response.getSubMsg());  
        }  
        return resultMap;  
    }  
  
    /**  
     * 验证签名是否正确  
     * @param sign  
     * @param content  
     * @return  
     */  
    public boolean CheckSignIn(String sign, String content){  
        try {  
            return AlipaySignature.rsaCheck(content, sign, alipayConfig.getPublicKey(), CHART_TYPE, SIGN_TYPE);  
        } catch (AlipayApiException e) {  
            e.printStackTrace();  
        }  
        return false;  
    }  
  
    /**  
     * 将异步通知的参数转化为Map  
     * @return  
     */  
    public Map<String, String> paramstoMap(HttpServletRequest request) throws UnsupportedEncodingException {  
        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] + ",";  
            }  
            // 乱码解决,这段代码在出现乱码时使用。  
//            valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");  
            params.put(name, valueStr);  
        }  
        return params;  
    }  

}
  • Step 5, encapsulate the config class, which is used to store all configuration attributes.
@Data  
@Component  
@ConfigurationProperties(prefix = "alipay")  
public class AlipayConfig {  
  
    private String gateway;  
  
    private String appid;  
  
    private String pid;  
  
    private String privateKey;  
  
    private String publicKey;  
  
    private String returnUrl;  
  
    private String notifyUrl;  
  
}

In addition, you need to prepare the above corresponding properties in application.properties.

# alipay config  
alipay.gateway=https://openapi.alipaydev.com/gateway.do  
alipay.appid=your_appid
alipay.pid=your_pid  
alipay.privatekey=your_private_key
alipay.publickey=your_public_key
alipay.returnurl=完成支付后的同步跳转地址 
alipay.notifyurl=完成支付后,支付宝会异步回调的地址

3. Front-end code implementation

The front-end code only needs to complete two functions,

  1. Initiate a payment request to the backend according to the user's request.
  2. Submit the returned data directly to complete the jump.

In the following example, I use typescript to implement the function after the user clicks to pay,

async function onPositiveClick() {  
   paymentLoading.value = true  
  
   const { data } = await placeAlipayOrder<string>({  
	//你的一些请求参数,例如金额等等
   })  
  
   const div = document.createElement('divform')  
   div.innerHTML = data  
   document.body.appendChild(div)  
   document.forms[0].setAttribute('target', '_blank')  
   document.forms[0].submit()  
  
   showModal.value = false  
   paymentLoading.value = false  
}

2.2 Create and launch APP

After completing the sandbox debugging, we need to create the corresponding Alipay web application and launch it.

Log in to  http://open.alipay.com/develop/man… and select Create Web Application,

Fill in the relevant application information:

After creating the application, first set the interface signing method and application gateway in the development settings.

Note that the key is RSA2, and others can follow the above operation guide step by step, and take care of your private key and public key.

Then on the product binding page, bind the corresponding API. For example, here we are paying on the PC web page, just find the corresponding API binding. If you bind for the first time, you may need to fill in relevant information for review, just fill in as needed, and the review usually passes within one day.

Finally, if everything is ready, we can submit the APP online. After the online is successful, we need to replace the properties in the following SpringBoot with the information of the online APP, and then we can call the Alipay interface to pay in the production environment.

# alipay config  
alipay.gateway=https://openapi.alipaydev.com/gateway.do  
alipay.appid=your_appid
alipay.pid=your_pid  
alipay.privatekey=your_private_key
alipay.publickey=your_public_key
alipay.returnurl=完成支付后的同步跳转地址 
alipay.notifyurl=完成支付后,支付宝会异步回调的地址

Guess you like

Origin blog.csdn.net/mxt51220/article/details/131248176