SSM realizes Alipay payment function

Artificial intelligence, zero-based entry! http://www.captainbed.net/inner

Preface

This tutorial details how to use the ssm framework to implement Alipay payment functions. This article is divided into two parts, namely "Alipay Test Environment Code Test" and "Integrating Alipay Payment into the ssm Framework". Detailed code and graphic explanations. When you practice yourself, you must carefully read the relevant documents, not much to say. Let's start.

Alipay test environment code test

Source code

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

1. Download the official demo from the computer website:

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

 

2. Download, unzip and import eclipse

Please take a good look at readme.txt.

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

3. Configure AlipayConfig

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

Registered address: https://open.alipay.com  , use your Alipay account to scan the QR code to log in, complete your personal information, and select the type of service (I chose self-study).

(2) Set app_id and gatewayUrl

The key needs to be generated by yourself, the 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 "Generate Method" to open the interface as follows:

Next week’s key generation tool, after unzipping and opening, select 2048 bits to generate the key:

If it has not been set, the text displayed at this time is "Set Application Public Key", I have already set it here.

Setting method, "Open the key file path":

Copy the content of the application public key 2048.txt to the pop-up box that clicks "Set Application Public Key", and save:

 

  • Merchant private key (merchant_private_key)
    copy the content of application private key 2048.txt to merchant_private_key.
  • Alipay public key (alipay_public_key)

Click the link as shown in the figure above and copy the content in the pop-up box to alipay_public_key.

If this setting is incorrect, the result is: the payment is successful, but the verification fails.

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

(4) Server asynchronous notification page path (notify_url)

If you haven't changed your name, just 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) The path of the page jump synchronization notification page (return_url)

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

4. Test run

 

The Alipay buyer account used for testing can be found on the "Sandbox Account" page:

After the payment is successful, the verification result

 

problem solved

Since we are using a sandbox test environment, the gateway of the test environment and the officially launched environment are different. If the configuration is wrong, the problem of wrong appid will occur. The configuration is as follows:

 

Source code download

Link:  https://pan.baidu.com/s/1n6GbEJiMzoGWJrSw0bb2Cg  Password: zd9e

Integrate Alipay payment into the ssm framework

1. Project structure

Project structure: spring+springmvc+mybatis

  • Database: mysql
  • Deployment environment: tomcat9.0
  • Development environment: jdk9, idea
  • Payment: Alipay, WeChat

As integrated into ssm, we need to modify the payment configuration information like a sandbox test environment

 

2. Database code

Mainly include the following database tables:

  • user: user table
  • order: Order generated by payment
  • flow: running account
  • product: Product table: used to simulate the purchase of products.
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 '用户表';CREATE TABLE `flow` (  `id` varchar(20) NOT NULL,  `flow_num` varchar(20) DEFAULT NULL COMMENT '流水号',  `order_num` varchar(20) DEFAULT NULL COMMENT '订单号',  `product_id` varchar(20) DEFAULT NULL COMMENT '产品主键ID',  `paid_amount` varchar(11) DEFAULT NULL COMMENT '支付金额',  `paid_method` int(11) DEFAULT NULL COMMENT '支付方式\r\n            1:支付宝\r\n            2:微信',  `buy_counts` int(11) DEFAULT NULL COMMENT '购买个数',  `create_time` datetime DEFAULT NULL COMMENT '创建时间',  PRIMARY KEY (`id`)) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='流水表';CREATE TABLE `orders` (  `id` varchar(20) NOT NULL,  `order_num` varchar(20) DEFAULT NULL COMMENT '订单号',  `order_status` varchar(20) DEFAULT NULL COMMENT '订单状态\r\n            10:待付款\r\n            20:已付款',  `order_amount` varchar(11) DEFAULT NULL COMMENT '订单金额',  `paid_amount` varchar(11) DEFAULT NULL COMMENT '实际支付金额',  `product_id` varchar(20) DEFAULT NULL COMMENT '产品表外键ID',  `buy_counts` int(11) DEFAULT NULL COMMENT '产品购买的个数',  `create_time` datetime DEFAULT NULL COMMENT '订单创建时间',  `paid_time` datetime DEFAULT NULL COMMENT '支付时间',  PRIMARY KEY (`id`)) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='订单表';CREATE TABLE `product` (  `id` varchar(20) NOT NULL,  `name` varchar(20) DEFAULT NULL COMMENT '产品名称',  `price` varchar(11) DEFAULT NULL COMMENT '价格',  PRIMARY KEY (`id`)) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='产品表 ';

3. Dao data interface layer

I won't introduce it here, this only includes simple curd, you can use `universal mapper`, or `reverse engineering`. Take the 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);}

Note: The source code is given at the end

4. Service layer

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

/** * 订单操作 service * @author ibm * */public interface OrdersService {    /**     * 新增订单     * @param order     */    public void saveOrder(Orders order);    /**     *      * @Title: OrdersService.java     * @Package com.sihai.service     * @Description: 修改叮当状态,改为 支付成功,已付款; 同时新增支付流水     * Copyright: Copyright (c) 2017     * Company:FURUIBOKE.SCIENCE.AND.TECHNOLOGY     *      * @author sihai     * @date 2017年8月23日 下午9:04:35     * @version V1.0     */    public void updateOrderStatus(String orderId, String alpayFlowNum, String paidAmount);    /**     * 获取订单     * @param orderId     * @return     */    public Orders getOrderById(String orderId);}

4. Alipay payment controller (payment process)

Payment flow chart

 

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

Below is the page code

Product page (products.jsp)

Code:

<%@ 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>                <td>                    产品名称                </td>                <td>                    产品价格                </td>                <td>                    操作                </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 }">购买</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 on the purchase above to enter the order page

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

The order is SIDgenerated based on the information (tool that generates the id) and saved to the database.

Enter to choose payment page

 

The following code is called:

Then, we chose Alipay to pay and entered our payment page, and we are done!

The following code is called:

/**     *     * @Title: AlipayController.java     * @Package com.sihai.controller     * @Description: 前往支付宝第三方网关进行支付     * Copyright: Copyright (c) 2017     * Company:FURUIBOKE.SCIENCE.AND.TECHNOLOGY     *     * @author sihai     * @date 2017年8月23日 下午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 alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id, AlipayConfig.merchant_private_key, "json", AlipayConfig.charset, AlipayConfig.alipay_public_key, AlipayConfig.sign_type);        //设置请求参数        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();        alipayRequest.setReturnUrl(AlipayConfig.return_url);        alipayRequest.setNotifyUrl(AlipayConfig.notify_url);        //商户订单号,商户网站订单系统中唯一订单号,必填        String out_trade_no = orderId;        //付款金额,必填        String total_amount = order.getOrderAmount();        //订单名称,必填        String subject = product.getName();        //商品描述,可空        String body = "用户订购商品个数:" + order.getBuyCounts();        // 该笔订单允许的最晚付款时间,逾期将关闭交易。取值范围:1m~15d。m-分钟,h-小时,d-天,1c-当天(1c-当天的情况下,无论交易何时创建,都在0点关闭)。该参数数值不接受小数点, 如 1.5h,可转换为 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\"}");        //请求        String result = alipayClient.pageExecute(alipayRequest).getBody();        return result;    }

This code can be found in the demo of Alipay, just copy it, then change it, and integrate it into the ssm environment.

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

 

Guess you like

Origin blog.csdn.net/qq_35860138/article/details/106188982