SpringMVC+Mybatis二維碼實現多平臺付款(附源碼)

今天,這篇文章就帶你們簡單實現多平臺支付!

整體思路:

實現微信支付寶等支付平臺合多為一的二維碼支付,並且實現有效時間內支付有效,本人采用的框架是spring springmvc mybatis框架,maven管理。其實如果支付,不需要mybatis也能實現,代碼和本人見解還需大神指教。

基本流程和思路:

  • 用戶點擊支付
  • 出現一次支付密碼,並且帶有時間限制
  • 掃描二維碼跳轉後臺
  • 後臺判斷是微信支付還是支付寶支付

1.整體架構:

這裡寫圖片描述

2.配置編譯的文件目錄

這裡寫圖片描述

3.pom.xml

其中qrcode.qrcode、qrcode.swetake是從本地編譯到maven庫中,因為網絡maven中沒有。

 
<?xml version="1.0"?>
<project
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"
    xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>fanghuai</groupId>
        <artifactId>nbt</artifactId>
        <version>0.0.1-SNAPSHOT</version>
    </parent>
    <groupId>com.nbt.qrcoder</groupId>
    <artifactId>nbt-qrcode</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>war</packaging>
    <name>nbt-qrcode Maven Webapp</name>
    <url>http://maven.apache.org</url>
    <properties>
        <spring.version>4.1.3.RELEASE</spring.version>
        <mybatis.version>3.2.8</mybatis.version>
        <mybatis.spring.version>1.2.2</mybatis.spring.version>
        <mybatis.paginator.version>1.2.15</mybatis.paginator.version>
        <mysql.version>5.1.32</mysql.version>
        <slf4j.version>1.6.4</slf4j.version>
        <jackson.version>2.4.2</jackson.version>
        <druid.version>1.0.9</druid.version>
        <jstl.version>1.2</jstl.version>
        <servlet-api.version>2.5</servlet-api.version>
        <jsp-api.version>2.0</jsp-api.version>
        <commons-lang3.version>3.3.2</commons-lang3.version>
        <commons-io.version>1.3.2</commons-io.version>
        <commons-net.version>3.3</commons-net.version>
        <pagehelper.version>4.0.0</pagehelper.version>
 
    </properties>
    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>3.8.1</version>
            <scope>test</scope>
        </dependency>
        <!-- qrcode -->
        <dependency>
            <groupId>qrcode.qrcode</groupId>
            <artifactId>qrcode</artifactId>
            <version>1.0</version>
        </dependency>
        <dependency>
            <groupId>qrcode.swetake</groupId>
            <artifactId>swetake</artifactId>
            <version>1.0</version>
        </dependency>
 
        <!-- 日志處理 -->
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>${slf4j.version}</version>
        </dependency>
        <!-- Mybatis -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>${mybatis.version}</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>${mybatis.spring.version}</version>
        </dependency>
        <dependency>
            <groupId>com.github.miemiedev</groupId>
            <artifactId>mybatis-paginator</artifactId>
            <version>${mybatis.paginator.version}</version>
        </dependency>
        <dependency>
            <groupId>com.github.pagehelper</groupId>
            <artifactId>pagehelper</artifactId>
            <version>${pagehelper.version}</version>
        </dependency>
        <!-- MySql -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>${mysql.version}</version>
        </dependency>
        <!-- 連接池 -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>${druid.version}</version>
        </dependency>
        <!-- Spring -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-beans</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aspects</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <!-- JSP相關 -->
        <dependency>
            <groupId>jstl</groupId>
            <artifactId>jstl</artifactId>
            <version>${jstl.version}</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>${servlet-api.version}</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jsp-api</artifactId>
            <version>${jsp-api.version}</version>
            <scope>provided</scope>
        </dependency>
    </dependencies>
    <build>
        <finalName>nbt-qrcode</finalName>
    </build>
</project>

4.二維碼相關屬性(Model)

 
package com.nbt.util;
import java.awt.image.BufferedImage;
import jp.sourceforge.qrcode.data.QRCodeImage;
 
 public   class J2SEImage implements QRCodeImage { 
        BufferedImage bufImg; 
        public J2SEImage(BufferedImage bufImg) { 
            this.bufImg = bufImg; 
        } 
        public int getWidth() { 
            return bufImg.getWidth(); 
        } 
        public int getHeight() { 
            return bufImg.getHeight(); 
        } 
        public int getPixel(int x, int y) { 
            return bufImg.getRGB(x, y); 
        } 
    }

5.二維碼生成代碼

package com.nbt.util;
 
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
 
import javax.imageio.ImageIO;
 
import jp.sourceforge.qrcode.QRCodeDecoder;
import jp.sourceforge.qrcode.exception.DecodingFailedException;
 
import com.swetake.util.Qrcode;
 
public class QRCode {
 
     /**
     * 生成二維碼(QRCode)圖片
     * @param content  二維碼內容
     * @param imgPath 存放二維位置
     */ 
    public static  void encoderQRCode(BuildQRCode bc) { 
 
        try { 
            Qrcode qrcodeHandler = new Qrcode(); 
            qrcodeHandler.setQrcodeErrorCorrect('M'); 
            qrcodeHandler.setQrcodeEncodeMode('B'); 
            qrcodeHandler.setQrcodeVersion(7); 
            System.out.println(bc.getContent()); 
            byte[] contentBytes = bc.getContent().getBytes("gb2312"); 
            BufferedImage bufImg = new BufferedImage(140, 140, 
                    BufferedImage.TYPE_INT_RGB); 
            Graphics2D gs = bufImg.createGraphics(); 
            gs.setBackground(Color.WHITE); 
            gs.clearRect(0, 0, 140, 140); 
            // 設定圖像顏色> BLACK 
            gs.setColor(Color.BLACK); 
            // 設置偏移量 不設置可能導致解析出錯 
            int pixoff = 2; 
            // 輸出內容> 二維碼 
            if (contentBytes.length > 0 && contentBytes.length < 120) { 
                boolean[][] codeOut = qrcodeHandler.calQrcode(contentBytes); 
                for (int i = 0; i < codeOut.length; i++) { 
                    for (int j = 0; j < codeOut.length; j++) { 
                        if (codeOut[j][i]) { 
                            gs.fillRect(j * 3 + pixoff, i * 3 + pixoff, 3, 3); 
                        } 
                    } 
                } 
            } else { 
                System.err.println("QRCode content bytes length = " + contentBytes.length + " not in [ 0,120 ]. "); 
            } 
            gs.dispose(); 
            bufImg.flush(); 
            File imgFile = new File(bc.getImgPath()); 
            // 生成二維碼QRCode圖片 
            ImageIO.write(bufImg, "png", imgFile); 
 
        } catch (Exception e) { 
 
            e.printStackTrace(); 
        } 
    } 
 
    /**
     * 解碼二維碼
     * @param imgPath
     * @return String
     */ 
    public static  String decoderQRCode(String imgPath) { 
        // QRCode 二維碼圖片的文件 
        File imageFile = new File(imgPath); 
        BufferedImage bufImg = null; 
        String decodedData = null; 
        try { 
            bufImg = ImageIO.read(imageFile); 
            QRCodeDecoder decoder = new QRCodeDecoder(); 
            decodedData = new String(decoder.decode(new J2SEImage(bufImg))); 
            // try { 
            // System.out.println(new String(decodedData.getBytes("gb2312"), 
            // "gb2312")); 
            // } catch (Exception e) { 
            // // TODO: handle exception 
            // } 
        } catch (IOException e) { 
            System.out.println("Error: " + e.getMessage()); 
            e.printStackTrace(); 
        } catch (DecodingFailedException dfe) { 
            System.out.println("Error: " + dfe.getMessage()); 
            dfe.printStackTrace(); 
        } 
        return decodedData; 
    } 
 
 
    public static void main(String[] args) {
 
    //生成二維碼
         String imgPath = "D:/test/Michael_QRCode.png"; 
         String content = "http://www.baidu.com"; 
         BuildQRCode bc = new BuildQRCode(imgPath,content);
         encoderQRCode(bc); 
         System.out.println("encoder QRcode success"); 
 
 
     //解讀二維碼
         String decoderContent =decoderQRCode(imgPath); 
         System.out.println("解析結果如下:"); 
         System.out.println(decoderContent); 
         System.out.println("========decoder success!!!");
     } 
}

6.Controller相關代碼

(jsp頁面要通過流的形式放在頁面上,不然二維碼顯示不出來。)

package com.nbt.controller;
 
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Map;
 
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
 
import com.mysql.jdbc.StringUtils;
import com.nbt.util.BuildQRCode;
import com.nbt.util.QRCode;
@Controller
@RequestMapping("/qr")
public class QRCodeController {
 
    private static Logger log = Logger.getLogger(QRCodeController.class);
 
 
    /**
     * 跳轉到二維碼頁面
     * @param request
     * @return
     */
    @RequestMapping("/toShowQRCode.do")
    public String showQRCode(HttpServletRequest request){
        log.info("跳轉到二維碼頁面...");
        return "qr";    
    }
 
    /**
     * 通過流的形式實現在jsp上面顯示二維碼
     * @param model
     * @param request
     * @param response
     * @throws IOException
     */
    @RequestMapping("/readImage")
    public void readImage(Model model, HttpServletRequest request, HttpServletResponse response) throws IOException{
        BuildQRCode bc = new BuildQRCode();//調用無參構造方法
        bc.initParam(bc);//對參數進行初始化
        QRCode.encoderQRCode(bc);//生成二維碼
 
        String filePath =  bc.getImgPath();
        File filePic = new File(filePath);
        if(filePic.exists()){
           FileInputStream is = new FileInputStream(filePic);
           int i = is.available(); // 得到文件大小  
           byte data[] = new byte[i];  
           is.read(data); // 讀數據  
           is.close();  
           response.setContentType("image/*"); // 設置返回的文件類型  
           OutputStream toClient = response.getOutputStream(); // 得到向客戶端輸出二進制數據的對象  
           toClient.write(data); // 輸出數據  
           toClient.close();  
        }
    }  
 
    /**
     * 預支付接口
     * @param timeout
     * @param orderNo
     * @return
     */
    @RequestMapping("/toPay.do")
    public String toPay(@RequestParam("timeout") String timeout,@RequestParam("orderNo")String orderNo){
        log.info("開始進行支付");
        if(StringUtils.isNullOrEmpty(orderNo)||StringUtils.isNullOrEmpty(timeout)){
            log.info("訂單號或者時間超時為空");
            return "faile";
        }
 
        Calendar ca = Calendar.getInstance();
        String afterTime = new SimpleDateFormat("yyyyMMddHHmmssSS").format(ca.getTime());
 
        if(!afterTime.equals(timeout)){
            log.info(afterTime+"---->"+timeout);
            log.info("二維碼已失效,請重新支付");
            return "faile";
        }
        /**
         * ..... 這段可以根據二維碼參數不一樣,去相關支付平臺進行支付,
         * 具體代碼可以根據支付平臺的api文檔進行支付操作
         */
        log.info("支付成功");
        return "success";
    }
}

7.二維碼相關參數初始化

(我目前二維碼存放在本地,你們可以把二維碼放在程序目錄下)。

 
package com.nbt.util;
 
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
 
 
public class BuildQRCode {
 
    /**
     * 二維碼存放地址
     */
    private   String imgPath ;
 
    /**
     * 二維碼內容
     */
    private  String content ;
 
    /**
     * 無參構造方法
     */
    public BuildQRCode() {
 
    }
 
 
    /**
     * 有參構造方法
     * @param imgPath
     * @param content
     */
    public BuildQRCode(String imgPath, String content) {
        super();
        this.imgPath = imgPath;
        this.content = content;
    }
 
 
 
    public void initParam(BuildQRCode bqrc){
 
    //  生成臨時訂單號和有效時間
        Calendar ca = Calendar.getInstance();
        Date date  = ca.getTime();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSS");
        System.out.println(sdf.format(date));
        String orderNo = sdf.format(date)+(int)Math.random()*1000;//生成訂單號
        //生成有效時間五分鐘
        ca.add(Calendar.MINUTE,5);
        System.out.println(sdf.format(ca.getTime()));
        String timeout = sdf.format(ca.getTime());
 
    //對參數進行初始化
        bqrc.setImgPath( "D:/test/Michael_QRCode.png");
        bqrc.setContent( "http://localhost:8080/nbt-qrcode/qr/toPay.do?orderNo="+orderNo+"&timeout="+timeout);
    }
 
    public static void main(String[] args) {
        BuildQRCode qc = new BuildQRCode();
        qc.initParam(qc);//設置參數
        QRCode.encoderQRCode(qc);
    }
 
 
 
    public  String getImgPath() {
        return imgPath;
    }
 
    public  void setImgPath(String imgPath) {
        this.imgPath = imgPath;
    }
 
    public  String getContent() {
        return content;
    }
 
    public  void setContent(String content) {
        this.content = content;
    }
}

總結:

到此這篇關於SpringMVC+Mybatis二維碼實現多平臺付款(附源碼)的文章就介紹到這瞭,更多相關SpringMVC Mybatis二維碼付款內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!

推薦閱讀: