Actual combat: realize payment function with SSM framework (with source code)

Preface

 

This tutorial details how to use the ssm framework to implement Alipay payment function. This article is divided into two parts, namely "Alipay test environment code test" and "Alipay payment integration into the ssm framework", detailed code and graphic explanation. When you practice, you must read the relevant documents carefully.

 

Alipay test environment code test

 

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

 

1. Download the official demo of computer website

 

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

 

2. Download, extract and import eclipse

 

 

 

Please take a good look at readme.txt.

 

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

 

3. Configure AlipayConfig

 

(1) Sign up for ant financial developer account (free, unlike Apple's fees)

 

Registered address: https://open.alipay.com, login with your Alipay account scan code, improve personal information, choose the type of service (I choose is self research).

 

(2) Set app? ID and gatewayUrl

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

 

(3) Set key

 

Click generate method to open the interface as follows:

Next week, the key generation tool. After decompression and opening, select 2048 bits to generate the key:

If it has not been set, the displayed text is "set application public key". I have set it here.

Setting method, open key file path:

Copy the contents of application public key 2048.txt to the pop-up box of "set application public key", and save:

  • Merchant private key

    Copy the contents of the application private key 2048.txt to the merchant_private_key.

  • Alipay public key (alipay_public_key)

Click the link as shown in the figure above, and copy the contents in the pop-up box to Alipay ﹣ public ﹣ key.

 

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

 

If it is a formal environment, it needs to be uploaded to the corresponding application:

 

(4) Server asynchronous notification page path (notify? URL)

 

If the name is not changed, I can modify the IP and port number. My own is as follows:

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

 

(5) Return? URL of the page Jump synchronization notification page

 

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

 

4. Test run

 

 

The Alipay buyer account can be found on the sandbox account.

After the payment is successful, the signature verification result:

 

Problem solving

 

Because we use sandbox test environment, the test environment is different from the gateway of the officially launched environment. If the configuration is wrong, there will be the problem of wrong appid. The configuration is as follows:

 

To integrate Alipay payment into the ssm framework

 

1. Project architecture

  • Project architecture: spring+springmvc+mybatis

  • Database: mysql

  • Deployment environment: Tomcat 9.0

  • Development environment: jdk9, idea

  • Payment: Alipay, WeChat

 

Like integrating into ssm, we need to modify the payment configuration information like sandbox test environment

 

2. Database code

 

It mainly includes the following database tables:

  • User: user table

  • Order: order generated by payment

  • flow: daily book

  • Product: product table: 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 'Serial number',`order_num` varchar(20) DEFAULT NULL COMMENT 'Order number',`product_id` varchar(20) DEFAULT NULL COMMENT 'Product primary key ID',`paid_amount` varchar(11) DEFAULT NULL COMMENT 'Payment amount',`paid_method` int(11) DEFAULT NULL COMMENT 'Payment method\r\n            1: Alipay\r\n            2: WeChat',`buy_counts` int(11) DEFAULT NULL COMMENT 'Purchase number',`create_time` datetime DEFAULT NULL COMMENT 'Creation time',  PRIMARY KEY (`id`)) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='Flow table';

CREATE TABLE `orders` (`id` varchar(20) NOT NULL,`order_num` varchar(20) DEFAULT NULL COMMENT 'Order number',`order_status` varchar(20) DEFAULT NULL COMMENT 'Order status\r\n            10: Pending payment\r\n            20: Paid',`order_amount` varchar(11) DEFAULT NULL COMMENT 'Order amount',`paid_amount` varchar(11) DEFAULT NULL COMMENT 'Actual payment amount',`product_id` varchar(20) DEFAULT NULL COMMENT 'Product table foreign key ID',`buy_counts` int(11) DEFAULT NULL COMMENT 'Number of products purchased',`create_time` datetime DEFAULT NULL COMMENT 'Order creation time',`paid_time` datetime DEFAULT NULL COMMENT 'Payment time',  PRIMARY KEY (`id`)) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='Order form';

CREATE TABLE `product` (`id` varchar(20) NOT NULL,`name` varchar(20) DEFAULT NULL COMMENT 'Product name',`price` varchar(11) DEFAULT NULL COMMENT 'Price',  PRIMARY KEY (`id`)) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='Product list ';

 

3. dao data interface layer

 

It will not be introduced here. This only includes simple curd. You can use general mapper or reverse engineering.

 

Take 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);}

Note: the source code is given at the end.

 

4. service layer

 

As above, it can be seen in the source code of the project. Take order as an example:

  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
/** * Order operation service * @author ibm * */public interface OrdersService {
/**   * New order   * @param order   */public void saveOrder(Orders order);
/**   *    * @Title: OrdersService.java   * @Package com.sihai.service   * @Description: Modify Dingdang status to payment succeeded and paid; add payment flow   * Copyright: Copyright (c) 2017   * Company:FURUIBOKE.SCIENCE.AND.TECHNOLOGY   *    * @author sihai   * @date 2017 9:04:35 PM, August 23, 2008   * @version V1.0   */public void updateOrderStatus(String orderId, String alpayFlowNum, String paidAmount);
/**   * Get order   * @param orderId   * @return   */public Orders getOrderById(String orderId);
}

 

Alipay pay controller (payment process)

 

Payment flow chart

First, after starting the project, enter http://localhost:8080 /, and you will enter the product page, as follows:

 

Here is the page code.

 

Products 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>              Product number</td><td>              Product name</td><td>              product price</td><td>              operation</td></tr><c:forEach items="${pList }" var="p"><tr><td>                ${p.id }</td><td>                ${p.name }</td><td>                ${p.price }</td><td><a href="<%=request.getContextPath() %>/alipay/goConfirm.action?productId=${p.id }">purchase</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>

Click purchase above to enter the order page.

 

Fill in the number and click generate order to call the following code:

Generate an order according to SID (the tool for generating id) and other information, and save it to the database.

 

Go to select payment page

 

The following code was called:

 

Then, we choose Alipay payment to enter the page we paid, and we are finished.

The following code was 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.TECHNOLOGY   *   * @author sihai   * @date 2017 August 23, 2008 8:50:43 PM   * @version V1.0   */@RequestMapping(value = "/goAlipay", produces = "text/html; charset=UTF-8")@ResponseBodypublic String goAlipay(String orderId, HttpServletRequest request, HttpServletRequest response) throws Exception {
    Orders order = orderService.getOrderById(orderId);
    Product product = productService.getProductById(order.getProductId());
//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 request parameters    AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();    alipayRequest.setReturnUrl(AlipayConfig.return_url);    alipayRequest.setNotifyUrl(AlipayConfig.notify_url);
//Merchant order number, the only order number in the order system of merchant website, requiredString out_trade_no = orderId;//Payment amount, requiredString total_amount = order.getOrderAmount();//Order name, requiredString subject = product.getName();//Product description, can be blankString body = "Number of products ordered by users:" + order.getBuyCounts();
// The latest payment time allowed for this order. If overdue, the transaction will be closed. Value range: 1m-15d. M-minute, H-Hour, D-Day, 1c day (in the case of 1C day, no matter when the transaction is created, it is closed at 0:00). This parameter value does not accept decimal point, such as 1.5h, which 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\"}");
//requestString result = alipayClient.pageExecute(alipayRequest).getBody();
return result;  }

This code can be found in the demo of Alibaba payment. You only need to copy it, change it, and integrate it into the ssm environment.

 

The above is the whole process of integrating Ali Alipay into ssm.

651 original articles published, 329 praised, 310000 visitors+

Tags: Java JSP Database Javascript

Posted on Mon, 03 Feb 2020 07:43:21 -0500 by premiso