Native掃碼支付
開發(fā)步驟:
- 1.開發(fā)平臺(tái)賬號(hào)申請(qǐng)(已擁有請(qǐng)忽略)
- 2.開通支付(審核過程需要6-7個(gè)工作日)
- 3.下載開發(fā)平臺(tái)支付DEMO,進(jìn)行相關(guān)工具類的提取即學(xué)習(xí)(也可以通過繼承WXPayConfig配置直接引用SDK)
- 4.閱讀接口文檔及注意事項(xiàng),微信商戶平臺(tái)掃碼支付文檔
Native支付開通申請(qǐng)?jiān)O(shè)置流程:
-
1.首先進(jìn)行Native類型支付申請(qǐng)(微信掃碼支付)
點(diǎn)擊支付產(chǎn)品進(jìn)行選擇 -
2.申請(qǐng)開通
-
3.填入你的回調(diào)地址,提交審核(回調(diào)地址后期可以修改)
申請(qǐng)過程 -
4.申請(qǐng)成功進(jìn)行相應(yīng)回調(diào)地址設(shè)置
產(chǎn)品設(shè)置
注意事項(xiàng)
閱讀接口文檔進(jìn)行開發(fā):
-
1.下載API對(duì)應(yīng)的SDK和調(diào)用示例,提取部分有用的代碼放入項(xiàng)目中
所需要的工具類
WXPayConstants類
/**
* 常量
*/
public class WXPayConstants {
public enum SignType {
MD5, HMACSHA256
}
public static final String FIELD_SIGN = "sign";
}
WXPayXmlUtil類
import org.w3c.dom.Document;
import javax.xml.XMLConstants;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
public final class WXPayXmlUtil {
/**
* XML解析
*
* @param inStream 微信發(fā)的流信息
* @param encoding 編碼格式
* @return
*/
public static String inputStream2String(InputStream inStream, String encoding) {
String result = null;
ByteArrayOutputStream outStream = null;
try {
if (inStream != null) {
outStream = new ByteArrayOutputStream();
byte[] tempBytes = new byte[1024];
int count = 0;
while ((count = inStream.read(tempBytes)) != -1) {
outStream.write(tempBytes, 0, count);
}
tempBytes = null;
outStream.flush();
result = new String(outStream.toByteArray(), encoding);
outStream.close();
}
} catch (Exception e) {
result = null;
}
return result;
}
public static DocumentBuilder newDocumentBuilder() throws ParserConfigurationException {
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
documentBuilderFactory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
documentBuilderFactory.setFeature("http://xml.org/sax/features/external-general-entities", false);
documentBuilderFactory.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
documentBuilderFactory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
documentBuilderFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
documentBuilderFactory.setXIncludeAware(false);
documentBuilderFactory.setExpandEntityReferences(false);
return documentBuilderFactory.newDocumentBuilder();
}
public static Document newDocument() throws ParserConfigurationException {
return newDocumentBuilder().newDocument();
}
}
WXPayUtil類
import com.itcast.dormmanagesys.utils.pay.WXPayConstants.SignType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.StringWriter;
import java.security.MessageDigest;
import java.security.SecureRandom;
import java.util.*;
public class WXPayUtil {
private static final String SYMBOLS = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
private static final Random RANDOM = new SecureRandom();
/**
* XML格式字符串轉(zhuǎn)換為Map
*
* @param strXML XML字符串
* @return XML數(shù)據(jù)轉(zhuǎn)換后的Map
* @throws Exception
*/
public static Map<String, String> xmlToMap(String strXML) throws Exception {
try {
Map<String, String> data = new HashMap<String, String>();
DocumentBuilder documentBuilder = WXPayXmlUtil.newDocumentBuilder();
InputStream stream = new ByteArrayInputStream(strXML.getBytes("UTF-8"));
org.w3c.dom.Document doc = documentBuilder.parse(stream);
doc.getDocumentElement().normalize();
NodeList nodeList = doc.getDocumentElement().getChildNodes();
for (int idx = 0; idx < nodeList.getLength(); ++idx) {
Node node = nodeList.item(idx);
if (node.getNodeType() == Node.ELEMENT_NODE) {
org.w3c.dom.Element element = (org.w3c.dom.Element) node;
data.put(element.getNodeName(), element.getTextContent());
}
}
try {
stream.close();
} catch (Exception ex) {
// do nothing
}
return data;
} catch (Exception ex) {
WXPayUtil.getLogger().warn("Invalid XML, can not convert to map. Error message: {}. XML content: {}", ex.getMessage(), strXML);
throw ex;
}
}
/**
* 將Map轉(zhuǎn)換為XML格式的字符串
*
* @param data Map類型數(shù)據(jù)
* @return XML格式的字符串
* @throws Exception
*/
public static String mapToXml(Map<String, String> data) throws Exception {
org.w3c.dom.Document document = WXPayXmlUtil.newDocument();
org.w3c.dom.Element root = document.createElement("xml");
document.appendChild(root);
for (String key : data.keySet()) {
String value = data.get(key);
if (value == null) {
value = "";
}
value = value.trim();
org.w3c.dom.Element filed = document.createElement(key);
filed.appendChild(document.createTextNode(value));
root.appendChild(filed);
}
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer();
DOMSource source = new DOMSource(document);
transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
StringWriter writer = new StringWriter();
StreamResult result = new StreamResult(writer);
transformer.transform(source, result);
String output = writer.getBuffer().toString(); //.replaceAll("\n|\r", "");
try {
writer.close();
} catch (Exception ex) {
}
return output;
}
/**
* 生成帶有 sign 的 XML 格式字符串
*
* @param data Map類型數(shù)據(jù)
* @param key API密鑰
* @return 含有sign字段的XML
*/
public static String generateSignedXml(final Map<String, String> data, String key) throws Exception {
return generateSignedXml(data, key, SignType.MD5);
}
/**
* 生成帶有 sign 的 XML 格式字符串
*
* @param data Map類型數(shù)據(jù)
* @param key API密鑰
* @param signType 簽名類型
* @return 含有sign字段的XML
*/
public static String generateSignedXml(final Map<String, String> data, String key, SignType signType) throws Exception {
String sign = generateSignature(data, key, signType);
data.put(WXPayConstants.FIELD_SIGN, sign);
return mapToXml(data);
}
/**
* 判斷簽名是否正確
*
* @param xmlStr XML格式數(shù)據(jù)
* @param key API密鑰
* @return 簽名是否正確
* @throws Exception
*/
public static boolean isSignatureValid(String xmlStr, String key) throws Exception {
Map<String, String> data = xmlToMap(xmlStr);
if (!data.containsKey(WXPayConstants.FIELD_SIGN)) {
return false;
}
String sign = data.get(WXPayConstants.FIELD_SIGN);
return generateSignature(data, key).equals(sign);
}
/**
* 判斷簽名是否正確取募,必須包含sign字段兄渺,否則返回false鞋屈。使用MD5簽名戴卜。
*
* @param data Map類型數(shù)據(jù)
* @param key API密鑰
* @return 簽名是否正確
* @throws Exception
*/
public static boolean isSignatureValid(Map<String, String> data, String key) throws Exception {
return isSignatureValid(data, key, SignType.MD5);
}
/**
* 判斷簽名是否正確捣域,必須包含sign字段啼染,否則返回false。
*
* @param data Map類型數(shù)據(jù)
* @param key API密鑰
* @param signType 簽名方式
* @return 簽名是否正確
* @throws Exception
*/
public static boolean isSignatureValid(Map<String, String> data, String key, SignType signType) throws Exception {
if (!data.containsKey(WXPayConstants.FIELD_SIGN)) {
return false;
}
String sign = data.get(WXPayConstants.FIELD_SIGN);
return generateSignature(data, key, signType).equals(sign);
}
/**
* 生成簽名
*
* @param data 待簽名數(shù)據(jù)
* @param key API密鑰
* @return 簽名
*/
public static String generateSignature(final Map<String, String> data, String key) throws Exception {
return generateSignature(data, key, SignType.MD5);
}
/**
* 生成簽名. 注意焕梅,若含有sign_type字段迹鹅,必須和signType參數(shù)保持一致。
*
* @param data 待簽名數(shù)據(jù)
* @param key API密鑰
* @param signType 簽名方式
* @return 簽名
*/
public static String generateSignature(final Map<String, String> data, String key, SignType signType) throws Exception {
Set<String> keySet = data.keySet();
String[] keyArray = keySet.toArray(new String[keySet.size()]);
Arrays.sort(keyArray);
StringBuilder sb = new StringBuilder();
for (String k : keyArray) {
if (k.equals(WXPayConstants.FIELD_SIGN)) {
continue;
}
if (data.get(k).trim().length() > 0) // 參數(shù)值為空丘侠,則不參與簽名
sb.append(k).append("=").append(data.get(k).trim()).append("&");
}
sb.append("key=").append(key);
if (SignType.MD5.equals(signType)) {
return MD5(sb.toString()).toUpperCase();
} else if (SignType.HMACSHA256.equals(signType)) {
return HMACSHA256(sb.toString(), key);
} else {
throw new Exception(String.format("Invalid sign_type: %s", signType));
}
}
/**
* 獲取隨機(jī)字符串 Nonce Str
*
* @return String 隨機(jī)字符串
*/
public static String generateNonceStr() {
char[] nonceChars = new char[32];
for (int index = 0; index < nonceChars.length; ++index) {
nonceChars[index] = SYMBOLS.charAt(RANDOM.nextInt(SYMBOLS.length()));
}
return new String(nonceChars);
}
/**
* 生成 MD5
*
* @param data 待處理數(shù)據(jù)
* @return MD5結(jié)果
*/
public static String MD5(String data) throws Exception {
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] array = md.digest(data.getBytes("UTF-8"));
StringBuilder sb = new StringBuilder();
for (byte item : array) {
sb.append(Integer.toHexString((item & 0xFF) | 0x100).substring(1, 3));
}
return sb.toString().toUpperCase();
}
/**
* 生成 HMACSHA256
*
* @param data 待處理數(shù)據(jù)
* @param key 密鑰
* @return 加密結(jié)果
* @throws Exception
*/
public static String HMACSHA256(String data, String key) throws Exception {
Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
SecretKeySpec secret_key = new SecretKeySpec(key.getBytes("UTF-8"), "HmacSHA256");
sha256_HMAC.init(secret_key);
byte[] array = sha256_HMAC.doFinal(data.getBytes("UTF-8"));
StringBuilder sb = new StringBuilder();
for (byte item : array) {
sb.append(Integer.toHexString((item & 0xFF) | 0x100).substring(1, 3));
}
return sb.toString().toUpperCase();
}
/**
* 日志
*
* @return
*/
public static Logger getLogger() {
Logger logger = LoggerFactory.getLogger("wxpay java sdk");
return logger;
}
/**
* 獲取當(dāng)前時(shí)間戳徒欣,單位秒
*
* @return
*/
public static long getCurrentTimestamp() {
return System.currentTimeMillis() / 1000;
}
/**
* 獲取當(dāng)前時(shí)間戳,單位毫秒
*
* @return
*/
public static long getCurrentTimestampMs() {
return System.currentTimeMillis();
}
}
-
2.相應(yīng)后端代碼如下:
import com.itcast.commom.util.Result;
import com.itcast.commom.util.ResultEnum;
import com.itcast.dormmanagesys.utils.pay.Httpclient;
import com.itcast.dormmanagesys.utils.pay.SystemUtil;
import com.itcast.dormmanagesys.utils.pay.WXPayUtil;
import com.itcast.dormmanagesys.utils.pay.WXPayXmlUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
/**
* 功能描述:
*
* @authro JIAQI
* @date 2019/11/6 - 10:36
*/
@Slf4j
@Controller
@RequestMapping("/wechat/pay")
public class PayController {
//公眾賬號(hào)ID
final private String appid = "你的公眾賬號(hào)ID";
//商戶號(hào)
final private String mch_id = "你的開放平臺(tái)商戶號(hào)";
/*商戶密鑰*/
final private String mch_Key = "你的開放平臺(tái)商戶密鑰";
//商品ID(這里寫死了,若用到請(qǐng)自行修改使用隨機(jī)數(shù)等等)
final private String product_id = "CS20191133344";
//異步回調(diào)地址
final private String notify_url = "你的異步回調(diào)地址";
/**
* 掃碼異步回調(diào)地址
*
* @param request
* @param response
* @return
*/
@PostMapping("/paycallback")
public String payCallBack(HttpServletRequest request,
HttpServletResponse response) {
InputStream is = null;
try {
//獲取請(qǐng)求的異步回調(diào)信息
is = request.getInputStream();
String xml = WXPayXmlUtil.inputStream2String(is, "UTF-8");
final Map<String, String> map = WXPayUtil.xmlToMap(xml);
//判斷是否支付成功 業(yè)務(wù)結(jié)果:SUCCESS/FAIL
if ("SUCCESS".equals(map.get("result_code"))) {
//公眾賬號(hào)ID
map.get("appid");
//商戶號(hào)
map.get("mch_id");
//隨機(jī)字符串
map.get("nonce_str");
//簽名
map.get("sign");
//用戶標(biāo)識(shí)
map.get("openid");
//是否關(guān)注公眾賬號(hào)
map.get("is_subscribe");
//交易類型
map.get("trade_type");
//付款銀行
map.get("bank_type");
//訂單金額
map.get("total_fee");
//貨幣種類
map.get("fee_type");
//現(xiàn)金支付金額
map.get("cash_fee");
//微信支付訂單號(hào)
map.get("transaction_id");
//商戶訂單號(hào)
map.get("out_trade_no");
//支付完成時(shí)間
map.get("time_end");
}
//回復(fù)微信服務(wù)器信息
response.getWriter().write("<xml><return_code><![CDATA[SUCCESS]]></return_code></xml>");
is.close();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 檢驗(yàn)是否支付成功
*
* @param out_trade_no 訂單號(hào)
* @return 支付結(jié)果
*/
private final String orderqueryURL = "https://api.mch.weixin.qq.com/pay/orderquery";
@PostMapping("/queryOrder")
@ResponseBody
public Result ajaxCheckPay(@RequestBody String out_trade_no) {
log.info("【所需校驗(yàn)支付狀態(tài)的訂單號(hào)】:{}", out_trade_no);
Map<String, String> reqData = new HashMap<String, String>();
try {
reqData.put("appid", appid);
reqData.put("mch_id", mch_id);
reqData.put("out_trade_no", out_trade_no);
reqData.put("nonce_str", WXPayUtil.generateNonceStr());
//簽名
String sign = WXPayUtil.generateSignature(reqData, mch_Key);
reqData.put("sign", sign);
//XML轉(zhuǎn)義即可
String xml = WXPayUtil.mapToXml(reqData);
String xmlStr = Httpclient.doPostJson(orderqueryURL, xml);
final Map<String, String> map = WXPayUtil.xmlToMap(xmlStr);
/*交易狀態(tài):
*SUCCESS—支付成功
*REFUND—轉(zhuǎn)入退款
*NOTPAY—未支付
*CLOSED—已關(guān)閉
*REVOKED—已撤銷(付款碼支付)
* USERPAYING--用戶支付中(付款碼支付)
*/
if ("SUCCESS".equals(map.get("trade_state"))) {
log.info("【訂單支付成功】:{}", out_trade_no);
return Result.success();
}
} catch (Exception e) {
e.printStackTrace();
}
return Result.failure(ResultEnum.FAILURE);
}
/**
* 下單獲取二維碼
*
* @param request
* @param model
* @return
*/
private final String unifiedorderURL = "https://api.mch.weixin.qq.com/pay/unifiedorder";
@GetMapping("/pay")
public String pay(HttpServletRequest request, Model model) {
String code_url = null;
try {
Map<String, String> reqData = new HashMap<String, String>();
//公眾賬號(hào)ID
reqData.put("appid", appid);
//商戶號(hào)
reqData.put("mch_id", mch_id);
//隨機(jī)字符串
reqData.put("nonce_str", WXPayUtil.generateNonceStr());
//商品描述
reqData.put("body", "測(cè)試PC端支付");
//商戶訂單號(hào)
reqData.put("out_trade_no", product_id);
//標(biāo)價(jià)金額 / 分
reqData.put("total_fee", "1");
//終端IP
reqData.put("spbill_create_ip", SystemUtil.getIpAddress(request));
// //交易起始時(shí)間
// final String dateStart = DateUtil.getDate(new Date(), DateStyle.YYYYMMDDHHMMSS);
// reqData.put("time_start", dateStart);
// System.out.println(dateStart);
// //交易結(jié)束時(shí)間
// reqData.put("time_expire", DateUtil.addMinute(dateStart, 2));
//通知地址
reqData.put("notify_url", notify_url);
//交易類型
reqData.put("trade_type", "NATIVE");
//簽名
String sign = WXPayUtil.generateSignature(reqData, mch_Key);
reqData.put("sign", sign);
//XML轉(zhuǎn)義即可
String xml = WXPayUtil.mapToXml(reqData);
String xmlStr = Httpclient.doPostJson(unifiedorderURL, xml);
final Map<String, String> map = WXPayUtil.xmlToMap(xmlStr);
if ("SUCCESS".equals(map.get("result_code")) && "OK".equals(map.get("return_msg"))) {
code_url = map.get("code_url");
}
System.out.println(code_url);
} catch (Exception e) {
e.printStackTrace();
}
//二維碼URL
model.addAttribute("code_url", code_url);
System.out.println(product_id);
//訂單號(hào)
model.addAttribute("out_tradeno", product_id);
return "/pay";
}
-
3.相應(yīng)工具類如下:
HttpClient工具類蜗字、pom依賴
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.3</version>
</dependency>
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
public class Httpclient {
public static String doGet(String url, Map<String, String> param) {
// 創(chuàng)建Httpclient對(duì)象
CloseableHttpClient httpclient = HttpClients.createDefault();
String resultString = "";
CloseableHttpResponse response = null;
try {
// 創(chuàng)建uri
URIBuilder builder = new URIBuilder(url);
if (param != null) {
for (String key : param.keySet()) {
builder.addParameter(key, param.get(key));
}
}
URI uri = builder.build();
// 創(chuàng)建http GET請(qǐng)求
HttpGet httpGet = new HttpGet(uri);
// 執(zhí)行請(qǐng)求
response = httpclient.execute(httpGet);
// 判斷返回狀態(tài)是否為200
if (response.getStatusLine().getStatusCode() == 200) {
resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (response != null) {
response.close();
}
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return resultString;
}
public static String doGet(String url) {
return doGet(url, null);
}
public static String doPost(String url, Map<String, String> param) {
// 創(chuàng)建Httpclient對(duì)象
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = null;
String resultString = "";
try {
// 創(chuàng)建Http Post請(qǐng)求
HttpPost httpPost = new HttpPost(url);
// 創(chuàng)建參數(shù)列表
if (param != null) {
List<NameValuePair> paramList = new ArrayList<>();
for (String key : param.keySet()) {
paramList.add(new BasicNameValuePair(key, param.get(key)));
}
// 模擬表單
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList,"utf-8");
httpPost.setEntity(entity);
}
// 執(zhí)行http請(qǐng)求
response = httpClient.execute(httpPost);
resultString = EntityUtils.toString(response.getEntity(), "utf-8");
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
response.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return resultString;
}
public static String doPost(String url) {
return doPost(url, null);
}
public static String doPostJson(String url, String json) {
// 創(chuàng)建Httpclient對(duì)象
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = null;
String resultString = "";
try {
// 創(chuàng)建Http Post請(qǐng)求
HttpPost httpPost = new HttpPost(url);
// 創(chuàng)建請(qǐng)求內(nèi)容
StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
httpPost.setEntity(entity);
// 執(zhí)行http請(qǐng)求
response = httpClient.execute(httpPost);
resultString = EntityUtils.toString(response.getEntity(), "utf-8");
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
response.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return resultString;
}
}
系統(tǒng)工具類(用來獲取ip地址)
package com.itcast.dormmanagesys.utils.pay;
import javax.servlet.http.HttpServletRequest;
/**
* 功能描述:
*
* @authro JIAQI
* @date 2019/7/18 - 17:55
*/
public class SystemUtil {
/**
* 獲取用戶真實(shí)IP地址打肝,不使用request.getRemoteAddr();的原因是有可能用戶使用了代理軟件方式避免真實(shí)IP地址,
* 可是,如果通過了多級(jí)反向代理的話挪捕,X-Forwarded-For的值并不止一個(gè)粗梭,而是一串IP值,究竟哪個(gè)才是真正的用戶端的真實(shí)IP呢级零?
* 答案是取X-Forwarded-For中第一個(gè)非unknown的有效IP字符串断医。
* 如:X-Forwarded-For:192.168.1.110, 192.168.1.120, 192.168.1.130,
* 192.168.1.100
* 用戶真實(shí)IP為: 192.168.1.110
*
* @param request
* @return
*/
public static String getIpAddress(HttpServletRequest request) {
String ip = request.getHeader("x-forwarded-for");
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("WL-Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("HTTP_CLIENT_IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("HTTP_X_FORWARDED_FOR");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getRemoteAddr();
}
return ip;
}
}
-
4.相應(yīng)前端代碼如下:
頁(yè)面中的二維碼生成是使用qrcode.js生成的滞乙,可在此GitHub使用文檔地址中進(jìn)行下載
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>內(nèi)嵌式——PC支付</title>
<script th:src="@{/commom/js/jquery.min.js}"></script>
<script th:src="@{/js/qrcode.js}"></script>
</head>
<body>
<div id="code"></div>
<div id="succer" hidden>支付成功</div>
</body>
<script>
var qrcode = new QRCode(document.getElementById("code"), {
width: 200,//設(shè)置寬高
height: 200
});
qrcode.makeCode('[[${code_url}]]');
//ajax長(zhǎng)輪詢 5s 循環(huán)一次
var siv = setInterval(function () {
$.ajax({
type: "POST",
url: "/wechat/pay/queryOrder",
data: '[[${out_tradeno}]]',
dataType: 'json',
contentType: 'application/json',
success: function (res) {
if (res.code == 0) {
$("#code").hide();
$("#succer").show();
clearInterval(siv); //成功后
}
}, error: function () {
}
})
}, 5000);
</script>
</html>
開發(fā)即注意事項(xiàng):
-
1.在配置開放平臺(tái)回調(diào)的時(shí)候注意不要回調(diào)的全地址,寫網(wǎng)站地址即可
附錄:
①:寫法有很多種鉴嗤,個(gè)人覺得如果有多余的可以使用Websocket的方式進(jìn)行支付成功通知,Websocket相比于Ajax長(zhǎng)輪詢會(huì)在性能上有所提升斩启,避免每次多余的前后端交互,可以參考下此Websocket寫法進(jìn)行替換醉锅。
②:在本人的筆記中采用了SDK中部分工具類提取的方式兔簇,移除了原SDK中一些用不上的代碼(開發(fā)中也可參考其寫法自行進(jìn)行需要的接口封裝),如果說需要用到支付中很多功能的朋友可以直接引用SDK的代碼然后通過繼承類WXPayConfig的方式進(jìn)行調(diào)用SDK中WXPayUtil類中已寫好的方法即可硬耍,官網(wǎng)的SDK對(duì)微信支付開發(fā)者文檔中給出的API進(jìn)行了封裝垄琐。
SDK調(diào)用示例
配置類MyConfig:
import com.github.wxpay.sdk.WXPayConfig;
import java.io.*;
public class MyConfig implements WXPayConfig{
private byte[] certData;
public MyConfig() throws Exception {
String certPath = "/path/to/apiclient_cert.p12";
File file = new File(certPath);
InputStream certStream = new FileInputStream(file);
this.certData = new byte[(int) file.length()];
certStream.read(this.certData);
certStream.close();
}
public String getAppID() {
return "wx8888888888888888";
}
public String getMchID() {
return "12888888";
}
public String getKey() {
return "88888888888888888888888888888888";
}
public InputStream getCertStream() {
ByteArrayInputStream certBis = new ByteArrayInputStream(this.certData);
return certBis;
}
public int getHttpConnectTimeoutMs() {
return 8000;
}
public int getHttpReadTimeoutMs() {
return 10000;
}
}
統(tǒng)一下單:
import com.github.wxpay.sdk.WXPay;
import java.util.HashMap;
import java.util.Map;
public class WXPayExample {
public static void main(String[] args) throws Exception {
MyConfig config = new MyConfig();
WXPay wxpay = new WXPay(config);
Map<String, String> data = new HashMap<String, String>();
data.put("body", "騰訊充值中心-QQ會(huì)員充值");
data.put("out_trade_no", "2016090910595900000012");
data.put("device_info", "");
data.put("fee_type", "CNY");
data.put("total_fee", "1");
data.put("spbill_create_ip", "123.12.12.123");
data.put("notify_url", "http://www.example.com/wxpay/notify");
data.put("trade_type", "NATIVE"); // 此處指定為掃碼支付
data.put("product_id", "12");
try {
Map<String, String> resp = wxpay.unifiedOrder(data);
System.out.println(resp);
} catch (Exception e) {
e.printStackTrace();
}
}
}