1. 程式人生 > >JAVA實現微信掃碼支付回撥Demo

JAVA實現微信掃碼支付回撥Demo

掃碼效果演示圖 微信掃碼支付 專案結構圖: java實現微信掃碼支付 微信實現JAVA掃碼支付的Demo原始碼,做這個做的很辛苦,熬夜了幾個晚上才把支付和回撥做好的,在這裡貼一下相關程式碼,以免更多開發者避免遇到這些坑,有不動的問題可以加我Q76949433,提供技術支援 package com.pay.common;

public class WxPayConfig {

public static String wxAppId="wsexbd6b2dgd23c841";

public static String wxappStrect="79ch22dsss71gbds5debe8d5c79e";

public static String wxMerchantNo="1523132d21";

public static String wxApiKey="ae12d0fgd3293df7aa1d606q228d91";

public static String notifyUrl ="http://test.pay.sucaiku.xin/wxPayNotifySevlet";

}

package com.pay.servlet;

import java.io.IOException; import java.util.Map; import java.util.Random;

import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse;

import com.jpay.ext.kit.IpKit; import com.jpay.ext.kit.PaymentKit; import com.jpay.ext.kit.StrKit; import com.jpay.weixin.api.WxPayApi; import com.jpay.weixin.api.WxPayApi.TradeType; import com.jpay.weixin.api.WxPayApiConfig; import com.jpay.weixin.api.WxPayApiConfig.PayModel; import com.jpay.weixin.api.WxPayApiConfigKit; import com.pay.common.WxPayConfig; import com.pay.util.MoneyUtil;

/**

  • 微信公眾號支付 */ public class WxPayMpServlet extends HttpServlet { private static final long serialVersionUID = 1L;

    private ServletConfig config;

    Random rand = new Random();

    public void init(ServletConfig config) throws ServletException { this.config = config; }

    public WxPayMpServlet() { super(); }

    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

     String openId = "";
    
     // 訂單金額
     String total_fee = "0.01";
     // 訂單號
     String outTradeNo = "D";
     for (int i = 0; i < 10; i++) {
     	outTradeNo += rand.nextInt(10);
     }
    
     if (StrKit.isBlank(total_fee)) {
     	System.out.println("支付金額不能為空");
     	return;
     }
    
     String ip = IpKit.getRealIp(request);
     if (StrKit.isBlank(ip)) {
     	ip = "127.0.0.1";
     }
    
     WxPayApiConfig wxPayApiConfig = WxPayApiConfig.New();
    
     // 微信公眾號id
     wxPayApiConfig.setAppId(WxPayConfig.wxAppId);
     // 微信商戶號
     wxPayApiConfig.setMchId(WxPayConfig.wxMerchantNo);
     // 微信商戶支付金鑰
     wxPayApiConfig.setPaternerKey(WxPayConfig.wxApiKey);
     // IP
     wxPayApiConfig.setSpbillCreateIp(ip);
     // 交易型別 掃碼支付
     wxPayApiConfig.setTradeType(TradeType.JSAPI);
     wxPayApiConfig.setOpenId(openId);
     // 回撥地址
     wxPayApiConfig.setNotifyUrl(WxPayConfig.notifyUrl);
     // 訂單號 不可重複
     wxPayApiConfig.setOutTradeNo(outTradeNo);
     // 訂單金額
     wxPayApiConfig.setTotalFee(MoneyUtil.getMoney(total_fee));
     // 備註
     wxPayApiConfig.setBody("商品購買");
     // 支付模式 商戶模式(自簽約不可更改)
     wxPayApiConfig.setPayModel(PayModel.BUSINESSMODEL);
     WxPayApiConfigKit.putApiConfig(wxPayApiConfig);
     Map<String, String> params = WxPayApiConfigKit.getWxPayApiConfig().build();
    
     // ************************引數組裝完畢開始發起支付*********************************//
    
     String xmlResult = WxPayApi.pushOrder(false, params);
    
     Map<String, String> result = PaymentKit.xmlToMap(xmlResult);
    
     String return_code = result.get("return_code");
     String return_msg = result.get("return_msg");
     if (!PaymentKit.codeIsOK(return_code)) {
     	System.out.println(return_msg);
     	return;
     }
     String result_code = result.get("result_code");
     if (!PaymentKit.codeIsOK(result_code)) {
     	System.out.println(return_msg);
     	return;
     }
    
     System.out.println(result.toString());
    

    }

} package com.pay.servlet;

import java.io.IOException; import java.util.Map;

import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse;

import com.jpay.ext.kit.HttpKit; import com.jpay.ext.kit.PaymentKit; import com.jpay.weixin.api.WxPayApiConfigKit;

/**

  • 微信回撥
  • @author Administrator

*/ public class WxPayNotifySevlet extends HttpServlet { private static final long serialVersionUID = 1L;

public WxPayNotifySevlet() {
	super();
	// TODO Auto-generated constructor stub
}

protected void service(HttpServletRequest request, HttpServletResponse response)
		throws ServletException, IOException {
	// 支付結果通用通知文件:https://pay.weixin.qq.com/wiki/doc/api/native.php?chapter=9_7&index=8
	String xmlMsg = HttpKit.readData(request);
	System.err.println("收到微信支付回撥通知=" + xmlMsg);
	Map<String, String> params = PaymentKit.xmlToMap(xmlMsg);
	 String appid = params.get("appid");
	 //商戶號
	 String mch_id = params.get("mch_id");
	String result_code = params.get("result_code");
	 String openId = params.get("openid");
	 //交易型別
	 String trade_type = params.get("trade_type");
	 //付款銀行
	 String bank_type = params.get("bank_type");
	 // 總金額
	String money = params.get("total_fee");
	 //現金支付金額
	 String cash_fee = params.get("cash_fee");
	 // 微信支付訂單號
	String transactionId = params.get("transaction_id");
	// // 商戶訂單號
	String outTradeNo = params.get("out_trade_no");
	// // 支付完成時間,格式為yyyyMMddHHmmss
	// String time_end = params.get("time_end");
	///////////////////////////// 以下是附加引數///////////////////////////////////
	String type = params.get("attach");
	 String fee_type = params.get("fee_type");
	 String is_subscribe = params.get("is_subscribe");
	 String err_code = params.get("err_code");
	 String err_code_des = params.get("err_code_des");
	if (PaymentKit.verifyNotify(params, WxPayApiConfigKit.getWxPayApiConfig().getPaternerKey())) {
		if (("SUCCESS").equals(result_code)) {
			//自行實現
			
			package com.pay.servlet;

import java.io.IOException; import java.util.Map; import java.util.Random;

import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse;

import com.jpay.ext.kit.IpKit; import com.jpay.ext.kit.PaymentKit; import com.jpay.ext.kit.StrKit; import com.jpay.weixin.api.WxPayApi; import com.jpay.weixin.api.WxPayApi.TradeType; import com.jpay.weixin.api.WxPayApiConfig; import com.jpay.weixin.api.WxPayApiConfig.PayModel; import com.jpay.weixin.api.WxPayApiConfigKit; import com.pay.common.WxPayConfig; import com.pay.util.MoneyUtil;

import cn.hutool.core.io.FileUtil; import cn.hutool.extra.qrcode.QrCodeUtil;

/**

  • 微信掃碼支付 */ @WebServlet("/WxPayServlet") public class WxPayServlet extends HttpServlet { private static final long serialVersionUID = 1L;

    private ServletConfig config;

    Random rand = new Random();

    public void init(ServletConfig config) throws ServletException { this.config = config; }

    public WxPayServlet() { super(); }

    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 網站根目錄 String rootPath = config.getServletContext().getRealPath("/");

     //訂單金額
     String total_fee = "0.01";
     //訂單號
     String outTradeNo = "D";
     for (int i = 0; i < 10; i++) {
     	outTradeNo += rand.nextInt(10);
     }
    
     if (StrKit.isBlank(total_fee)) {
     	System.out.println("支付金額不能為空");
     	return;
     }
    
     String ip = IpKit.getRealIp(request);
     if (StrKit.isBlank(ip)) {
     	ip = "127.0.0.1";
     }
    
     WxPayApiConfig wxPayApiConfig = WxPayApiConfig.New();
    
     // 微信公眾號id
     wxPayApiConfig.setAppId(WxPayConfig.wxAppId);
     // 微信商戶號
     wxPayApiConfig.setMchId(WxPayConfig.wxMerchantNo);
     // 微信商戶支付金鑰
     wxPayApiConfig.setPaternerKey(WxPayConfig.wxApiKey);
     // IP
     wxPayApiConfig.setSpbillCreateIp(ip);
     // 交易型別 掃碼支付
     wxPayApiConfig.setTradeType(TradeType.NATIVE);
     // 回撥地址
     wxPayApiConfig.setNotifyUrl(WxPayConfig.notifyUrl);
     // 訂單號 不可重複
     wxPayApiConfig.setOutTradeNo(outTradeNo);
     // 訂單金額
     wxPayApiConfig.setTotalFee(MoneyUtil.getMoney(total_fee));
     // 備註
     wxPayApiConfig.setBody("商品購買");
     // 支付模式 商戶模式(自簽約不可更改)
     wxPayApiConfig.setPayModel(PayModel.BUSINESSMODEL);
     WxPayApiConfigKit.putApiConfig(wxPayApiConfig);
     Map<String, String> params = WxPayApiConfigKit.getWxPayApiConfig().build();
    
     // ************************引數組裝完畢開始發起支付*********************************//
    
     String xmlResult = WxPayApi.pushOrder(false, params);
    
     Map<String, String> result = PaymentKit.xmlToMap(xmlResult);
    
     String return_code = result.get("return_code");
     String return_msg = result.get("return_msg");
     if (!PaymentKit.codeIsOK(return_code)) {
     	System.out.println(return_msg);
     	return;
     }
     String result_code = result.get("result_code");
     if (!PaymentKit.codeIsOK(result_code)) {
     	System.out.println(return_msg);
     	return;
     }
     
     // 微信預支付訂單生產成功 獲取二維碼url
     String qrCodeUrl = result.get("code_url");
    
     QrCodeUtil.generate(qrCodeUrl, 300, 300, FileUtil.file(rootPath + "/wxPayCode/" + outTradeNo + ".png"));
     
     request.setAttribute("codeUrl", outTradeNo);
    
     request.getRequestDispatcher("/pay/wxpay.jsp").forward(request, response);
    

    }

}

		}
	}

}

} package com.pay.util;

public class MoneyUtil {

public static String getMoney(String amount) {
	if (amount == null) {
		return "";
	}
	// 金額轉化為分為單位
	String currency = amount.replaceAll("\\$|\\¥|\\,", ""); // 處理包含, ¥
															// 或者$的金額
	int index = currency.indexOf(".");
	int length = currency.length();
	Long amLong = 0l;
	if (index == -1) {
		amLong = Long.valueOf(currency + "00");
	} else if (length - index >= 3) {
		amLong = Long.valueOf((currency.substring(0, index + 3)).replace(".", ""));
	} else if (length - index == 2) {
		amLong = Long.valueOf((currency.substring(0, index + 2)).replace(".", "") + 0);
	} else {
		amLong = Long.valueOf((currency.substring(0, index + 1)).replace(".", "") + "00");
	}
	return amLong.toString();
}

} <%@ page language=“java” import=“java.util.*” pageEncoding=“ISO-8859-1”%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"?/"+request.getServerName()+":"+request.getServerPort()+path+"/"; %>