preface

This tutorial details how to use the SSM framework to implement the Alipay payment function. This article is divided into two parts, respectively is “Alipay test environment code test” and “Alipay payment integration into the SSM framework”, detailed code and text explanation, their practice must carefully read the relevant documents, not to say more we begin.

Alipay test environment code test

The source code

https://github.com/OUYANGSIHAI/sihai-maven-ssm-alipay

1. Download the official demo of the computer website:

Download: https://docs.open.alipay.com/270/106291/

2. Download, decompress, and import Eclipse

Please take a good look at readme.txt.

There is only one Java configuration class, and the rest are JSPS.

3. The configuration AlipayConfig

(1) Register an Ant Financial developer account (free, unlike Apple)

Register address: https://open.alipay.com, use your Alipay account to scan code to log in, improve personal information, choose the service type (I choose from research).

(2) Set app_id and gatewayUrl

The key needs to be generated by ourselves, appID and Alipay gateway have been given, and the gateway has the word dev, indicating that it is used for development and testing.

(3) Set the key

Click “Generation Method” to open the interface as follows:

Next week key generation tool, unzip open, select 2048 bits to generate key:

If not, the display text is “Set application public key”, which I have set.

Setting method,” Open key file path “:

Copy the contents of application Public Key 2048. TXT to the popup box of “Set Application Public Key” and save:

  • Merchant private key (merchant_private_key)

    Copy the contents of application private key 2048. TXT into merchant_private_key.

  • Alipay public key (alipay_public_key)

Click the link above to copy the contents of the pop-up to alipay_public_key.

If this setting is not correct, the result is: payment succeeded, but verification failed.

In a formal environment, upload it to the corresponding application:

(4) Server asynchronous notification page path (notify_URL)

If the name is not changed, it is ok to change the IP and port number, my own is as follows:

http://localhost:8080/alipay.trade.page.pay-JAVA-UTF-8/notify_url.jsp

Copy the code

Path to the synchronization notification page (return_URL)

http://localhost:8080/alipay.trade.page.pay-JAVA-UTF-8/return_url.jsp

Copy the code

4. Test run

The alipay buyer account for the test can be found on the page of “Sandbox Account” :

Upon successful payment, inspection result:

Problem solving

Because we are using a sandbox test environment, the gateway of the test environment is different from that of the official live environment. If the configuration is wrong, there will be an appID error. The configuration is as follows:

Source code download

Link: https://pan.baidu.com/s/1n6GbEJiMzoGWJrSw0bb2Cg password: zd9eCopy the code

Integrate Alipay into THE SSM framework

1. Project architecture

  • Project architecture: Spring + SpringMVC + Mybatis

  • Database: mysql

  • Deployment environment: Tomcat9.0

  • Development environment: JDK9, IDEA

  • Payment: Alipay, wechat

As with SSM integration, we need to modify the configuration information of payments just like in the sandbox test environment

2. Database code

It mainly includes the following database tables:

  • User: indicates the user table

  • Order: Pay for the order generated

  • -Serena: I don’t know

  • Product: Table of goods: Used to simulate the purchase of goods.

drop table if exists user; /*==============================================================*//* Table: user *//*==============================================================*/create table user( id varchar(20) not null, username varchar(128), sex varchar(20), primary key (id)); Alter table user comment 'user table '; CREATE TABLE 'flow' (' id 'varchar(20) NOT NULL,' flow_num 'varchar(20) DEFAULT NULL COMMENT' iD ', 'order_num' varchar(20) DEFAULT NULL COMMENT 'ID',' product_id 'varchar(20) DEFAULT NULL COMMENT' ID', 'paid_amount' varchar(11) DEFAULT NULL COMMENT 'paid_amount ',' paid_method 'int(11) DEFAULT NULL COMMENT' ', 'buy_counts' int(11) DEFAULT NULL COMMENT' 表 现 ', 'create_time' DEFAULT NULL COMMENT '表 现 ', PRIMARY KEY (' id ')) ENGINE=InnoDB DEFAULT CHARSET= utf8MB4 COMMENT=' table '; CREATE TABLE orders (' id 'varchar(20) NOT NULL,' order_num 'varchar(20) DEFAULT NULL COMMENT' order ', 'order_status' varchar(20) DEFAULT NULL COMMENT' Order_status' \r\n 10: \r\n 20: Order_amount 'varchar(11) DEFAULT NULL COMMENT' order amount ', 'paid_amount' varchar(11) DEFAULT NULL COMMENT 'actual amount ', 'product_id' varchar(20) DEFAULT NULL COMMENT '表 ID',' buy_counts' int(11) DEFAULT NULL COMMENT '表 ID', 'create_time' datetime DEFAULT NULL COMMENT 'create_time ',' paid_time 'datetime DEFAULT NULL COMMENT' create_time ', PRIMARY KEY (' id ') ENGINE=InnoDB DEFAULT CHARSET= utf8MB4 COMMENT=' table '; CREATE TABLE 'product' (' id 'varchar(20) NOT NULL,' name 'varchar(20) DEFAULT NULL COMMENT' 表 名 ', 'price' varchar(11) DEFAULT NULL COMMENT 'price ', PRIMARY KEY (' id')) ENGINE=InnoDB DEFAULT CHARSET= utf8MB4 COMMENT=' table ';

Copy the code

3. Dao data interface layer

It will not be introduced here, this includes simple curDS, which can be used with ‘universal mapper’ or ‘reverse engineering’. Take order order as an example:

public interface OrdersMapper { int countByExample(OrdersExample example); int deleteByExample(OrdersExample example); int deleteByPrimaryKey(String id); int insert(Orders record); int insertSelective(Orders record); List<Orders> selectByExample(OrdersExample example); Orders selectByPrimaryKey(String id); int updateByExampleSelective(@Param("record") Orders record, @Param("example") OrdersExample example); int updateByExample(@Param("record") Orders record, @Param("example") OrdersExample example); int updateByPrimaryKeySelective(Orders record); int updateByPrimaryKey(Orders record); }

Copy the code

Note: The source code is given last

4, the service layer

Same as above, finally visible in the project source code. Take order order as an example:

/** * OrdersService * @author IBM ** /public interface OrdersService {/** * order * @param */public void saveOrder(Orders order); /** ** @title: ordersservice.java * @package com.sihai. Meanwhile, new payment flow * Copyright: Copyright (c) 2017 * Company: FURUIBOKE. SCIENCE AND the TECHNOLOGY of * * @ author sihai * @ date on August 23, 2017 afternoon 9:04:35 * @ version V1.0 */ public void updateOrderStatus(String orderId, String alpayFlowNum, String paidAmount); @param orderId * @return */ public Orders getOrderById(String orderId); }

Copy the code

4. Alipay Payment Controller (Payment process)

Payment flow chart

First of all, after starting the project, enter http://localhost:8080/ to enter the product page as follows:

Here is the page code

Product page (products.jsp)

Code implementation:

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%><%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %><%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %> <script src="<%=request.getContextPath() %>/static/js/jquery.min.js" type="text/javascript"></script>< HTML >< head> </head> <body> <table> <tr> < TD > < td > product name < / td > < td > product price < / td > < td > action < / td > < / tr > < c: forEach items = "${pList}" var = "p" > < tr > < td > ${p.i d} < / td > < td > ${p.name } </td> <td> ${p.price } </td> <td> <a href="<%=request.getContextPath() % > / alipay/goConfirm. Action? ProductId = ${p.i d} "> buy < / a > < / td > < / tr > < / c: forEach > < / table > < input type =" hidden" id="hdnContextPath" name="hdnContextPath" value="<%=request.getContextPath() %>"/> </body></html><script type="text/javascript"> $(document).ready(function() { var hdnContextPath = $("#hdnContextPath").val(); }); </script>

Copy the code

Click on the purchase above to enter the order page

Fill in the number, then click Generate order, call the following code

Generate orders based on information such as the SID (tool for generating ids) and save them to the database.

The Select Payment page is displayed

The following code is called:

Then, we choose Alipay to pay, into our payment page, done!

The following code is called:

/** ** @title: alipayController.java * @package com.sihai.controller * @description: Go to alipay third-party gateway for payment * Copyright: Copyright (c) 2017 * Company: FURUIBOKE. SCIENCE AND the TECHNOLOGY of * * @ author sihai * @ date on August 23, 2017 afternoon 8:50:43 * @ version V1.0 */ @requestMapping (value = "/goAlipay", Produces = "text/ HTML; charset=UTF-8") @ResponseBody public String goAlipay(String orderId, HttpServletRequest request, HttpServletRequest response) throws Exception { Orders order = orderService.getOrderById(orderId); Product product = productService.getProductById(order.getProductId()); 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 parameter AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest (); alipayRequest.setReturnUrl(AlipayConfig.return_url); alipayRequest.setNotifyUrl(AlipayConfig.notify_url); // Merchant order number, which is the unique order number in the order system on merchant website. Mandatory String out_trade_NO = orderId; // Amount of payment, mandatory String total_amount = order.getorderamount (); // Order name, mandatory String subject = product.getName(); Body = "order.getBuyCounts();" + order.getBuyCounts(); // 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; }

Copy the code

This code can be found in the Demo of Ali Pay, just need to copy over, and then change, integrate into the SSM environment.

Above is the ali Alipay payment integration into the whole process of SSM, if there is any doubt you can pay attention to the wechat public number: “learn Java well”, consulting small series.

Recommended reading:

Why do we have to separate the front and back ends?

HTTP protocol status code description

What is cross-domain? What are the solutions?

RESTful Interface implementation Guide