微信支付之掃碼支付相關程式碼(Java)
最近開發網站過程,需要引入支付過程,第三方支付中最火的莫過於支付寶支付和微信支付,下邊藉助微信支付官網上的文件,寫一下接入微信支付之掃碼支付的流程
相對支付寶支付而言,微信支付的開發文件寫的相當的low,demo寫的一點都不簡潔,下邊寫一下微信掃碼支付的過程,這一過程中,需要注意的所涉及的實際業務是怎樣的,根據實際情況結合業務進行引入,在進入正式開發之前,要申請微信支付的相關內容按照官網的操作進行即可,稽核成功後,會得到appId,商戶號,商戶平臺登入賬號和密碼
登入微信支付官網
https://pay.weixin.qq.com,照相開發文件入口,檢視掃碼支付,大致瞭解一下掃碼支付的相關資訊後,進入開發流程,這是官網上的模式二的業務流程,(1)商戶後臺系統根據使用者選購的商品生成訂單。
(2)使用者確認支付後呼叫微信支付【統一下單API】生成預支付交易;
(3)微信支付系統收到請求後生成預支付交易單,並返回交易會話的二維碼連結code_url。
(4)商戶後臺系統根據返回的code_url生成二維碼。
(5)使用者開啟微信“掃一掃”掃描二維碼,微信客戶端將掃碼內容傳送到微信支付系統。
(6)微信支付系統收到客戶端請求,驗證連結有效性後發起使用者支付,要求使用者授權。
(7)使用者在微信客戶端輸入密碼,確認支付後,微信客戶端提交授權。
(8)微信支付系統根據使用者授權完成支付交易。
(9)微信支付系統完成支付交易後給微信客戶端返回交易結果,並將交易結果通過簡訊、微信訊息提示使用者。微信客戶端展示支付交易結果頁面。
(10)微信支付系統通過傳送非同步訊息通知商戶後臺系統支付結果。商戶後臺系統需回覆接收情況,通知微信後臺系統不再發送該單的支付通知。
(11)未收到支付通知的情況,商戶後臺系統呼叫【查詢訂單API】。
(12)商戶確認訂單已支付後給使用者發貨。
開發的流程,首先根據自己的業務流程,生成訂單儲存到資料庫當中,這一過程包含了商品的資訊,需要支付的錢數,商品名稱等,下邊開始進入統一下單的方法,這部分是微信統一下單入口(controller方法)
下邊是微信支付統一下單具體實現方法/** * 微信掃碼支付統一下單 */ @RequestMapping(value = "/WxPayUnifiedorder", method = RequestMethod.GET) @ResponseBody public Object WxPayUnifiedorder(String out_trade_no) throws Exception{ HashMap<String,Object> map = new HashMap<String,Object>(); String codeUrl = wxPayService.weixin_pay(out_trade_no); map.put("codeUrl",codeUrl); return map; }
/**
* 微信支付統一下單介面
* @param out_trade_no
* @return
* @throws Exception
*/
public String weixin_pay(String out_trade_no) throws Exception {
// 賬號資訊
String appid = PayConfigUtil.getAppid(); // appid
//String appsecret = PayConfigUtil.APP_SECRET; // appsecret
// 商業號
String mch_id = PayConfigUtil.getMchid();
// key
String key = PayConfigUtil.getKey();
String currTime = PayCommonUtil.getCurrTime();
String strTime = currTime.substring(8, currTime.length());
String strRandom = PayCommonUtil.buildRandom(4) + "";
//隨機字串
String nonce_str = strTime + strRandom;
// 價格 注意:價格的單位是分
//String order_price = "1";
// 商品名稱
//String body = "企嘉科技商品";
//查詢訂單資料表獲取訂單資訊
PayOrder payOrder = payOrderDao.get(PayOrder.class,out_trade_no);
// 獲取發起電腦 ip
String spbill_create_ip = PayConfigUtil.getIP();
// 回撥介面
String notify_url = PayConfigUtil.NOTIFY_URL;
String trade_type = "NATIVE";
String time_start = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
Calendar ca = Calendar.getInstance();
ca.setTime(new Date());
ca.add(Calendar.DATE, 1);
String time_expire = new SimpleDateFormat("yyyyMMddHHmmss").format(ca.getTime());
SortedMap<Object,Object> packageParams = new TreeMap<Object,Object>();
packageParams.put("appid", appid);
packageParams.put("mch_id", mch_id);
packageParams.put("nonce_str", nonce_str);
packageParams.put("body",payOrder.getBody());
packageParams.put("out_trade_no", out_trade_no);
//packageParams.put("total_fee", "1");
packageParams.put("total_fee", payOrder.getTotalFee());
packageParams.put("spbill_create_ip", spbill_create_ip);
packageParams.put("notify_url", notify_url);
packageParams.put("trade_type", trade_type);
packageParams.put("time_start", time_start);
packageParams.put("time_expire", time_expire);
String sign = PayCommonUtil.createSign("UTF-8", packageParams,key);
packageParams.put("sign", sign);
String requestXML = PayCommonUtil.getRequestXml(packageParams);
System.out.println("請求xml::::"+requestXML);
String resXml = HttpUtil.postData(PayConfigUtil.PAY_API, requestXML);
System.out.println("返回xml::::"+resXml);
Map map = XMLUtil.doXMLParse(resXml);
//String return_code = (String) map.get("return_code");
//String prepay_id = (String) map.get("prepay_id");
String urlCode = (String) map.get("code_url");
System.out.println("列印呼叫統一下單介面生成二維碼url:::::"+urlCode);
return urlCode;
}
這一方法中,我們從工具類中獲取微信官網提供的appId以及商戶號,以及在商戶平臺上設定的支付金鑰,處理一些統一下單介面需要攜帶的引數,回撥連結(微信發起的本地呼叫,並返回成功或錯誤資訊),totalFee的單位為分,官網的介面文件有說明,trade_type寫死指定為NATIVE,另外的兩個量time_start與time_expire是指定訂單的有效期,
可以根據的自己的業務需求具體指定時間,(此處是24小時的訂單有效期),如果無需指定,直接註釋掉即可,sign是簽名操作,藉助工具類將packageParams轉化為XML藉助postData方法請求微信統一下單介面
public static String PAY_API = "https://api.mch.weixin.qq.com/pay/unifiedorder";
resXml作為呼叫統一下單的返回值,當然返回的也是xml檔案,再借助xmlUtil將返回值轉化為map,返回值中有生成二維碼的code_url,接下來我們需要處理的是,解析二維碼url在前端網頁中生成二維碼圖片,在前端使用ajax呼叫統一下單介面方法,接收返回值code_url,接收返回值後在呼叫後臺介面方法解析code_url common.get("/*****/wxpay/WxPayUnifiedorder?out_trade_no="+orderId,function(data){
var codeUrl = data.codeUrl;
if(codeUrl!=null && codeUrl!=""){
$("#id_wxtwoCode").attr('src',"******/wxpay/qr_codeImg?code_url="+codeUrl);
}
});
html中img標籤
<div class="weimg">
<!-- <img src="../common/img/wei_06.png"> -->
<img id="id_wxtwoCode"src=""/>
<p>開啟手機端微信<br>掃一掃繼續支付</p>
</div>
下邊是解析二維碼過程
/**
* 生成二維碼圖片並直接以流的形式輸出到頁面
* @param code_url
* @param response
*/
@RequestMapping("qr_codeImg")
@ResponseBody
public void getQRCode(String code_url,HttpServletResponse response){
wxPayService.encodeQrcode(code_url, response);
}
/**
* 生成二維碼圖片 不儲存 直接以流的形式輸出到頁面
* @param content
* @param response
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
public static void encodeQrcode(String content,HttpServletResponse response){
if(content==null || "".equals(content))
return;
MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
Map hints = new HashMap();
hints.put(EncodeHintType.CHARACTER_SET, "UTF-8"); //設定字符集編碼型別
BitMatrix bitMatrix = null;
try {
bitMatrix = multiFormatWriter.encode(content, BarcodeFormat.QR_CODE, 300, 300,hints);
BufferedImage image = toBufferedImage(bitMatrix);
//輸出二維碼圖片流
try {
ImageIO.write(image, "png", response.getOutputStream());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (WriterException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
這裡的300,300確定了二維碼圖片的大小
二維碼圖片生成後,接下來的流程就是掃碼進行支付操作,這裡還存在一個問題,需要在掃碼後支付成功,需要實現頁面的跳轉,這一過程需要新增js的定時器,定時檢視訂單的支付狀態是否發生了改變是否為支付成功,成功即可跳轉後續流程,失敗跳轉失敗提示
//定時器,每隔1s查詢訂單支付狀態,訂單狀態改變,清除頁面定時器,頁面跳轉
function checkOrder(orderId) {
console.log("定時器方法"+orderId);
common.get("/*******/order/checkOrder?out_trade_no="+orderId,function(data){
var isorder = data.isorder;
var paystatus = data.paystatus;
if(isorder=="1"){
if(paystatus=="1"){
//支付成功跳轉
window.location.href="******/order/wxpaySuccess?out_trade_no="+orderId;
clearInterval(time);
}else if(paystatus=="2"){
//支付失敗
alert("支付失敗!");
clearInterval(time);
}
}
});
}
isorder檢視是否存在訂單,存在訂單時判斷支付狀態,進行後續流程
支付成功後,微信服務端開始回撥方法,
@RequestMapping(value = "/weixinNotify", method = RequestMethod.POST)
@ResponseBody
public void weixinNotify(HttpServletRequest request,HttpServletResponse response) throws Exception{
System.out.println("支付回撥方法開始!");
HashMap<String,Object> map = new HashMap<String,Object>();
wxPayService.weixin_notify(request, response);
System.out.println("支付回撥方法結束!");
}
/**
* 微信支付回撥方法
* @param request
* @param response
* @throws Exception
*/
public void weixin_notify(HttpServletRequest request,HttpServletResponse response) throws Exception{
//讀取引數
InputStream inputStream ;
StringBuffer sb = new StringBuffer();
inputStream = request.getInputStream();
String s ;
BufferedReader in = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
while ((s = in.readLine()) != null){
sb.append(s);
}
in.close();
inputStream.close();
//解析xml成map
Map<String, String> m = new HashMap<String, String>();
m = XMLUtil.doXMLParse(sb.toString());
//過濾空 設定 TreeMap
SortedMap<Object,Object> packageParams = new TreeMap<Object,Object>();
Iterator it = m.keySet().iterator();
while (it.hasNext()) {
String parameter = (String) it.next();
String parameterValue = m.get(parameter);
String v = "";
if(null != parameterValue) {
v = parameterValue.trim();
}
packageParams.put(parameter, v);
}
// 賬號資訊
String key = PayConfigUtil.getKey(); // key
String out_trade_no = (String)packageParams.get("out_trade_no");
//logger.info(packageParams);
//判斷簽名是否正確
if(PayCommonUtil.isTenpaySign("UTF-8", packageParams,key)) {
//------------------------------
//處理業務開始
//------------------------------
String resXml = "";
if("SUCCESS".equals((String)packageParams.get("result_code"))){
// 這裡是支付成功
//////////執行自己的業務邏輯////////////////
String mch_id = (String)packageParams.get("mch_id");
String openid = (String)packageParams.get("openid");
String is_subscribe = (String)packageParams.get("is_subscribe");
String bank_type = (String)packageParams.get("bank_type");
String total_fee = (String)packageParams.get("total_fee");
String transaction_id = (String)packageParams.get("transaction_id");
System.out.println("mch_id:"+mch_id);
System.out.println("openid:"+openid);
System.out.println("is_subscribe:"+is_subscribe);
System.out.println("out_trade_no:"+out_trade_no);
System.out.println("total_fee:"+total_fee);
System.out.println("bank_type:"+bank_type);
System.out.println("transaction_id:"+transaction_id);
//成功回撥後需要處理預生成訂單的狀態和一些支付資訊
//查詢資料庫中訂單,首先判定訂單中金額與返回的金額是否相等,不等金額被纂改
//判定訂單是否已經被支付,不可重複支付
//正常處理相關業務邏輯
} else {
System.out.println("支付失敗,錯誤資訊:" + packageParams.get("err_code")+
"-----訂單號:::"+out_trade_no+"*******支付失敗時間::::"
+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
String err_code = (String)packageParams.get("err_code");
resXml = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>"
+ "<return_msg><![CDATA[報文為空]]></return_msg>" + "</xml> ";
}
//------------------------------
//處理業務完畢
//------------------------------
BufferedOutputStream out = new BufferedOutputStream(
response.getOutputStream());
out.write(resXml.getBytes());
out.flush();
out.close();
} else{
System.out.println("通知簽名驗證失敗---時間::::"+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
}
}
至此,微信支付流程完畢
下邊是相關工具類
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.net.URLConnection;
import com.entplus.log.entity.Log;
public class HttpUtil {
//private static final Log logger = Logs.get();
private final static int CONNECT_TIMEOUT = 5000; // in milliseconds
private final static String DEFAULT_ENCODING = "UTF-8";
public static String postData(String urlStr, String data){
return postData(urlStr, data, null);
}
public static String postData(String urlStr, String data, String contentType){
BufferedReader reader = null;
try {
URL url = new URL(urlStr);
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
conn.setConnectTimeout(CONNECT_TIMEOUT);
conn.setReadTimeout(CONNECT_TIMEOUT);
if(contentType != null)
conn.setRequestProperty("content-type", contentType);
OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream(), DEFAULT_ENCODING);
if(data == null)
data = "";
writer.write(data);
writer.flush();
writer.close();
reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), DEFAULT_ENCODING));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line);
sb.append("\r\n");
}
return sb.toString();
} catch (IOException e) {
//logger.error("Error connecting to " + urlStr + ": " + e.getMessage());
System.out.println("Error connecting to " + urlStr + ": " + e.getMessage());
} finally {
try {
if (reader != null)
reader.close();
} catch (IOException e) {
}
}
return null;
}
}
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.SortedMap;
public class PayCommonUtil {
/**
* 是否簽名正確,規則是:按引數名稱a-z排序,遇到空值的引數不參加簽名。
* @return boolean
*/
public static boolean isTenpaySign(String characterEncoding, SortedMap<Object, Object> packageParams, String API_KEY) {
StringBuffer sb = new StringBuffer();
Set es = packageParams.entrySet();
Iterator it = es.iterator();
while(it.hasNext()) {
Map.Entry entry = (Map.Entry)it.next();
String k = (String)entry.getKey();
String v = (String)entry.getValue();
if(!"sign".equals(k) && null != v && !"".equals(v)) {
sb.append(k + "=" + v + "&");
}
}
sb.append("key=" + API_KEY);
//算出摘要
String mysign = MD5Util.MD5Encode(sb.toString(), characterEncoding).toLowerCase();
String tenpaySign = ((String)packageParams.get("sign")).toLowerCase();
//System.out.println(tenpaySign + " " + mysign);
return tenpaySign.equals(mysign);
}
/**
* @author
* @date 2016-4-22
* @Description:sign簽名
* @param characterEncoding
* 編碼格式
* @param parameters
* 請求引數
* @return
*/
public static String createSign(String characterEncoding, SortedMap<Object, Object> packageParams, String API_KEY) {
StringBuffer sb = new StringBuffer();
Set es = packageParams.entrySet();
Iterator it = es.iterator();
while (it.hasNext()) {
Map.Entry entry = (Map.Entry) it.next();
String k = (String) entry.getKey();
String v = (String) entry.getValue();
if (null != v && !"".equals(v) && !"sign".equals(k) && !"key".equals(k)) {
sb.append(k + "=" + v + "&");
}
}
sb.append("key=" + API_KEY);
String sign = MD5Util.MD5Encode(sb.toString(), characterEncoding).toUpperCase();
return sign;
}
/**
* @author
* @date 2016-4-22
* @Description:將請求引數轉換為xml格式的string
* @param parameters
* 請求引數
* @return
*/
public static String getRequestXml(SortedMap<Object, Object> parameters) {
StringBuffer sb = new StringBuffer();
sb.append("<xml>");
Set es = parameters.entrySet();
Iterator it = es.iterator();
while (it.hasNext()) {
Map.Entry entry = (Map.Entry) it.next();
String k = (String) entry.getKey();
String v = (String) entry.getValue();
if ("attach".equalsIgnoreCase(k) || "body".equalsIgnoreCase(k) || "sign".equalsIgnoreCase(k)) {
sb.append("<" + k + ">" + "<![CDATA[" + v + "]]></" + k + ">");
} else {
sb.append("<" + k + ">" + v + "</" + k + ">");
}
}
sb.append("</xml>");
return sb.toString();
}
/**
* 取出一個指定長度大小的隨機正整數.
*
* @param length
* int 設定所取出隨機數的長度。length小於11
* @return int 返回生成的隨機數。
*/
public static int buildRandom(int length) {
int num = 1;
double random = Math.random();
if (random < 0.1) {
random = random + 0.1;
}
for (int i = 0; i < length; i++) {
num = num * 10;
}
return (int) ((random * num));
}
/**
* 獲取當前時間 yyyyMMddHHmmss
*
* @return String
*/
public static String getCurrTime() {
Date now = new Date();
SimpleDateFormat outFormat = new SimpleDateFormat("yyyyMMddHHmmss");
String s = outFormat.format(now);
return s;
}
}
package com.entplus.wxpay.util;
public class PayConfigUtil {
//這個就是自己要保管好的私有Key了(切記只能放在自己的後臺程式碼裡,不能放在任何可能被看到原始碼的客戶端程式中)
// 每次自己Post資料給API的時候都要用這個key來對所有欄位進行簽名,生成的簽名會放在Sign這個欄位,API收到Post資料的時候也會用同樣的簽名演算法對Post過來的資料進行簽名和驗證
// 收到API的返回的時候也要用這個key來對返回的資料算下簽名,跟API的Sign資料進行比較,如果值不一致,有可能資料被第三方給篡改
private static String key = "";
//微信分配的公眾號ID(開通公眾號之後可以獲取到)
private static String appID = "";
//微信支付分配的商戶號ID(開通公眾號的微信支付功能之後可以獲取到)
private static String mchID = "";
//機器IP
private static String ip = "";
//以下是幾個API的路徑:
//1)被掃支付API
//public static String PAY_API = "https://api.mch.weixin.qq.com/pay/micropay";
public static String PAY_API = "https://api.mch.weixin.qq.com/pay/unifiedorder";
//2)被掃支付查詢API
public static String PAY_QUERY_API = "https://api.mch.weixin.qq.com/pay/orderquery";
//3)退款API
public static String REFUND_API = "https://api.mch.weixin.qq.com/secapi/pay/refund";
//4)退款查詢API
public static String REFUND_QUERY_API = "https://api.mch.weixin.qq.com/pay/refundquery";
//5)撤銷API
public static String REVERSE_API = "https://api.mch.weixin.qq.com/secapi/pay/reverse";
//6)下載對賬單API
public static String DOWNLOAD_BILL_API = "https://api.mch.weixin.qq.com/pay/downloadbill";
//7) 統計上報API
public static String REPORT_API = "https://api.mch.weixin.qq.com/payitil/report";
//回撥地址
//public static String NOTIFY_URL = ""; //測試
public static String HttpsRequestClassName = "com.entplus.wxpay.util.HttpsRequest";
public static void setKey(String key) {
PayConfigUtil.key = key;
}
public static void setAppID(String appID) {
PayConfigUtil.appID = appID;
}
public static void setMchID(String mchID) {
PayConfigUtil.mchID = mchID;
}
public static void setIp(String ip) {
PayConfigUtil.ip = ip;
}
public static String getKey(){
return key;
}
public static String getAppid(){
return appID;
}
public static String getMchid(){
return mchID;
}
public static String getIP(){
return ip;
}
public static void setHttpsRequestClassName(String name){
HttpsRequestClassName = name;
}
}
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
public class XMLUtil {
/**
* 解析xml,返回第一級元素鍵值對。如果第一級元素有子節點,則此節點的值是子節點的xml資料。
* @param strxml
* @return
* @throws JDOMException
* @throws IOException
*/
public static Map doXMLParse(String strxml) throws JDOMException, IOException {
strxml = strxml.replaceFirst("encoding=\".*\"", "encoding=\"UTF-8\"");
if(null == strxml || "".equals(strxml)) {
return null;
}
Map m = new HashMap();
InputStream in = new ByteArrayInputStream(strxml.getBytes("UTF-8"));
SAXBuilder builder = new SAXBuilder();
Document doc = builder.build(in);
Element root = doc.getRootElement();
List list = root.getChildren();
Iterator it = list.iterator();
while(it.hasNext()) {
Element e = (Element) it.next();
String k = e.getName();
String v = "";
List children = e.getChildren();
if(children.isEmpty()) {
v = e.getTextNormalize();
} else {
v = XMLUtil.getChildrenText(children);
}
m.put(k, v);
}
//關閉流
in.close();
return m;
}
/**
* 獲取子結點的xml
* @param children
* @return String
*/
public static String getChildrenText(List children) {
StringBuffer sb = new StringBuffer();
if(!children.isEmpty()) {
Iterator it = children.iterator();
while(it.hasNext()) {
Element e = (Element) it.next();
String name = e.getName();
String value = e.getTextNormalize();
List list = e.getChildren();
sb.append("<" + name + ">");
if(!list.isEmpty()) {
sb.append(XMLUtil.getChildrenText(list));
}
sb.append(value);
sb.append("</" + name + ">");
}
}
return sb.toString();
}
}
import java.security.MessageDigest;
public class MD5Util {
private static String byteArrayToHexString(byte b[]) {
StringBuffer resultSb = new StringBuffer();
for (int i = 0; i < b.length; i++)
resultSb.append(byteToHexString(b[i]));
return resultSb.toString();
}
private static String byteToHexString(byte b) {
int n = b;
if (n < 0)
n += 256;
int d1 = n / 16;
int d2 = n % 16;
return hexDigits[d1] + hexDigits[d2];
}
public static String MD5Encode(String origin, String charsetname) {
String resultString = null;
try {
resultString = new String(origin);
MessageDigest md = MessageDigest.getInstance("MD5");
if (charsetname == null || "".equals(charsetname))
resultString = byteArrayToHexString(md.digest(resultString
.getBytes()));
else
resultString = byteArrayToHexString(md.digest(resultString
.getBytes(charsetname)));
} catch (Exception exception) {
}
return resultString;
}
private static final String hexDigits[] = { "0", "1", "2", "3", "4", "5",
"6", "7", "8", "9", "a", "b", "c", "d", "e", "f" };
}
開發過程中藉助了網路資料,歡迎大家指正。