Spring MVC+Spring+MyBatis實現支付寶掃碼支付功能(圖文詳解)

本教程源代碼:https://github.com/OUYANGSIHAI/sihai-maven-ssm-alipayjavascript

支付寶測試環境代碼測試

1.下載電腦網站的官方demo:
下載:https://docs.open.alipay.com/270/106291/html

2.下載解壓導入eclipsejava

readme.txt請好好看一下。只有一個Java配置類,其他都是JSP。mysql

3.配置AlipayConfiggit

(1) 註冊螞蟻金服開發者帳號(免費,不像蘋果會收取費用)github

註冊地址:https://open.alipay.com ,用你的支付寶帳號掃碼登陸,完善我的信息,選擇服務類型(我選的是自研)。spring

(2) 設置app_id和gatewayUrlsql

其中密鑰須要本身生成,appID和支付寶網關是已經給好的,網關有dev字樣,代表是用於開發測試。數據庫

(3) 設置密鑰express

點擊「生成方法」,打開界面以下:

下週密鑰生成工具,解壓打開後,選擇2048位生成密鑰:

若是沒有設置過,此時顯示文本是"設置應用公鑰",我這裏是已經設置過得。

設置方法,"打開密鑰文件路徑":

複製應用公鑰2048.txt中的內容到點擊"設置應用公鑰"的彈出框中,保存:

  • 商戶私鑰(merchant_private_key):複製 應用私鑰2048.txt 中的內容到merchant_private_key中。

  • 支付寶公鑰(alipay_public_key)

點擊如上圖連接,複製彈出框裏面的內容到alipay_public_key。若是這個設置不對,結果是:支付成功,可是驗籤失敗。

若是是正式環境,須要上傳到對應的應用中:

(4) 服務器異步通知頁面路徑(notify_url)

若是沒有更名,修改IP和端口號就能夠了,我本身的以下:

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

(5) 頁面跳轉同步通知頁面的路徑(return_url)

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

4.測試運行

測試用的支付寶買家帳戶能夠在"沙箱帳"這個頁面能夠找到:

支付成功後,驗簽結果:

問題解決

因爲咱們使用的是沙箱測試環境,測試環境和正式上線的環境的網關是不同的,若是配置錯誤,會出現,appid錯誤的問題。配置以下:

源代碼下載:連接: https://pan.baidu.com/s/1n6GbEJiMzoGWJrSw0bb2Cg 密碼: zd9e

將支付寶支付整合到ssm框架

一、項目架構

  • 項目架構:spring+springmvc+mybatis

  • 數據庫:mysql

  • 部署環境:tomcat9.0

  • 開發環境:jdk九、idea

  • 支付:支付寶、微信

整合到ssm同樣,咱們須要像沙箱測試環境同樣,須要修改支付的配置信息

二、數據庫代碼

主要包括如下的數據庫表:

  • user:用戶表

  • order:支付產生的訂單

  • flow:流水帳

  • product:商品表:用於模擬購買商品。

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='產品表 ';

三、dao數據接口層

這裏就不介紹了,這個只包括簡單的curd,可使用`通用mapper`,或者`逆向工程`就行。以訂單order爲例給出:

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

四、service層

同上,最後在項目源代碼裏可見。以訂單order爲例給出:

/**
 * 訂單操做 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);

}

四、支付寶支付controller(支付流程)

支付流程圖

首先,啓動項目後,輸入http://localhost:8080/,會進入到商品頁面,以下:

下面是頁面代碼

商品頁面(products.jsp)

代碼實現:

<html>
    <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>

點擊上面的購買,進入到訂單頁面

填寫個數,而後點擊生成訂單,調用以下代碼

根據SID(生成id的工具)等信息生成訂單,保存到數據庫。

Tips:能夠關注微信公衆號:Java後端,獲取更多相似技術博文推送。

進入到選擇支付頁面

調用了以下代碼:

而後,咱們選擇支付寶支付,進入到了咱們支付的頁面了,大功告成!

調用了以下代碼:

/**
     *
     * @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;
    }

這段代碼均可以在阿里支付的demo裏面找到的,只須要複製過來,而後改改,整合到ssm環境便可。

上面就是將阿里支付寶支付整合到ssm的全過程了。本文參考了博主「小溪_寧靜而致遠」的支付教程文章,歡迎搜索博主關注。

相關文章
相關標籤/搜索