springboot對(duì)接微信支付的完整流程(附前后端代碼)
展示圖:

對(duì)接的完整流程如下
首先是配置
gzh.appid=公眾號(hào)appid wxPay.mchId=商戶號(hào) wxPay.key=支付密鑰 wxPay.notifyUrl=域名回調(diào)地址
常量:
/**微信支付統(tǒng)一下單接口*/
public static final String unifiedOrderUrl = "https://api.mch.weixin.qq.com/pay/unifiedorder";
public static String SUCCESSxml = "<xml> \r\n" +
"\r\n" +
" <return_code><![CDATA[SUCCESS]]></return_code>\r\n" +
" <return_msg><![CDATA[OK]]></return_msg>\r\n" +
" </xml> \r\n" +
"";
public static String ERRORxml = "<xml> \r\n" +
"\r\n" +
" <return_code><![CDATA[FAIL]]></return_code>\r\n" +
" <return_msg><![CDATA[invalid sign]]></return_msg>\r\n" +
" </xml> \r\n" +
"";
工具類準(zhǔn)備:
package com.jc.utils.util;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContexts;
import org.apache.http.util.EntityUtils;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.input.SAXBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.net.ssl.SSLContext;
import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.text.SimpleDateFormat;
import java.util.*;
public class CommUtils {
private static Logger logger = LoggerFactory.getLogger(CommUtils.class);
// 連接超時(shí)時(shí)間,默認(rèn)10秒
private static int socketTimeout = 60000;
// 傳輸超時(shí)時(shí)間,默認(rèn)30秒
private static int connectTimeout= 60000;
/**
* Util工具類方法
* 獲取一定長度的隨機(jī)字符串,范圍0-9,a-z
* @param length:指定字符串長度
* @return 一定長度的隨機(jī)字符串
*/
public static String getRandomStringByLength(int length) {
String base = "abcdefghijklmnopqrstuvwxyz0123456789";
Random random = new Random();
StringBuffer sb = new StringBuffer();
for (int i = 0; i < length; i++) {
int number = random.nextInt(base.length());
sb.append(base.charAt(number));
}
return sb.toString();
}
/**
* 獲取訂單號(hào)
* @return
*/
public static String getOrderNo(){
SimpleDateFormat ft = new SimpleDateFormat("yyyyMMddHHmmss");
String time = ft.format(new Date());
int mathCode = (int) ((Math.random() * 9 + 1) * 10000);// 5位隨機(jī)數(shù)
String resultCode = time+mathCode;
return resultCode;
}
/**
* Util工具類方法
* 獲取真實(shí)的ip地址
* @param request
* @return
*/
public static String getIpAddr(HttpServletRequest request) {
String ip = request.getHeader("X-Forwarded-For");
if (StringUtils.isNotEmpty(ip) && !"unKnown".equalsIgnoreCase(ip)) {
//多次反向代理后會(huì)有多個(gè)ip值,
int index = ip.indexOf(",");
if (index != -1) {
return ip.substring(0, index);
} else {
return ip;
}
}
ip = request.getHeader("X-Real-IP");
if (StringUtils.isNotEmpty(ip) && !"unKnown".equalsIgnoreCase(ip)) {
return ip;
}
return request.getRemoteAddr();
}
/**
* 簽名字符串
* @param text 需要簽名的字符串
* @param key 密鑰
* @param input_charset 編碼格式
* @return 簽名結(jié)果
*/
public static String sign(String text, String key, String input_charset) {
text = text + "&key=" + key;
System.out.println(text);
return DigestUtils.md5Hex(getContentBytes(text, input_charset));
}
/**
* 簽名字符串
* @param text 需要簽名的字符串
* @param sign 簽名結(jié)果
* @param key 密鑰
* @param input_charset 編碼格式
* @return 簽名結(jié)果
*/
public static boolean verify(String text, String sign, String key, String input_charset) {
text = text + key;
String mysign = DigestUtils.md5Hex(getContentBytes(text, input_charset));
if (mysign.equals(sign)) {
return true;
} else {
return false;
}
}
/**
* @param content
* @param charset
* @return
* @throws UnsupportedEncodingException
*/
public static byte[] getContentBytes(String content, String charset) {
if (charset == null || "".equals(charset)) {
return content.getBytes();
}
try {
return content.getBytes(charset);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("MD5簽名過程中出現(xiàn)錯(cuò)誤,指定的編碼集不對(duì),您目前指定的編碼集是:" + charset);
}
}
/**
* 生成6位或10位隨機(jī)數(shù) param codeLength(多少位)
* @return
*/
public static String createCode(int codeLength) {
String code = "";
for (int i = 0; i < codeLength; i++) {
code += (int) (Math.random() * 9);
}
return code;
}
@SuppressWarnings("unused")
private static boolean isValidChar(char ch) {
if ((ch >= '0' && ch <= '9') || (ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z'))
return true;
if ((ch >= 0x4e00 && ch <= 0x7fff) || (ch >= 0x8000 && ch <= 0x952f))
return true;// 簡體中文漢字編碼
return false;
}
/**
* 除去數(shù)組中的空值和簽名參數(shù)
* @param sArray 簽名參數(shù)組
* @return 去掉空值與簽名參數(shù)后的新簽名參數(shù)組
*/
public static Map<String, String> paraFilter(Map<String, String> sArray) {
Map<String, String> result = new HashMap<>();
if (sArray == null || sArray.size() <= 0) {
return result;
}
for (String key : sArray.keySet()) {
String value = sArray.get(key);
if (value == null || value.equals("") || key.equalsIgnoreCase("sign")
|| key.equalsIgnoreCase("sign_type")) {
continue;
}
result.put(key, value);
}
return result;
}
/**
* 把數(shù)組所有元素排序,并按照“參數(shù)=參數(shù)值”的模式用“&”字符拼接成字符串
* @param params 需要排序并參與字符拼接的參數(shù)組
* @return 拼接后字符串
*/
public static String createLinkString(Map<String, String> params) {
List<String> keys = new ArrayList<>(params.keySet());
Collections.sort(keys);
String prestr = "";
for (int i = 0; i < keys.size(); i++) {
String key = keys.get(i);
String value = params.get(key);
if (i == keys.size() - 1) {// 拼接時(shí),不包括最后一個(gè)&字符
prestr = prestr + key + "=" + value;
} else {
prestr = prestr + key + "=" + value + "&";
}
}
return prestr;
}
/**
*
* @param requestUrl 請(qǐng)求地址
* @param requestMethod 請(qǐng)求方法
* @param outputStr 參數(shù)
*/
public static String httpRequest(String requestUrl,String requestMethod,String outputStr){
logger.warn("請(qǐng)求報(bào)文:"+outputStr);
StringBuffer buffer = null;
try{
URL url = new URL(requestUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod(requestMethod);
conn.setDoOutput(true);
conn.setDoInput(true);
conn.connect();
//往服務(wù)器端寫內(nèi)容
if(null !=outputStr){
OutputStream os=conn.getOutputStream();
os.write(outputStr.getBytes("utf-8"));
os.close();
}
// 讀取服務(wù)器端返回的內(nèi)容
InputStream is = conn.getInputStream();
InputStreamReader isr = new InputStreamReader(is, "utf-8");
BufferedReader br = new BufferedReader(isr);
buffer = new StringBuffer();
String line = null;
while ((line = br.readLine()) != null) {
buffer.append(line);
}
br.close();
}catch(Exception e){
e.printStackTrace();
}
logger.warn("返回報(bào)文:"+buffer.toString());
return buffer.toString();
}
/**
* POST請(qǐng)求
* @param url 請(qǐng)求url
* @param xmlParam 請(qǐng)求參數(shù)
* @param apiclient 證書
* @param mch_id 商戶號(hào)
* @return
* @throws Exception
*/
public static String post(String url, String xmlParam,String apiclient,String mch_id) throws Exception {
logger.warn("請(qǐng)求報(bào)文:"+xmlParam);
StringBuilder sb = new StringBuilder();
try {
KeyStore keyStore = KeyStore.getInstance("PKCS12");
FileInputStream instream = new FileInputStream(new File(apiclient));
try {
keyStore.load(instream, mch_id.toCharArray());
} finally {
instream.close();
}
// 證書
SSLContext sslcontext = SSLContexts.custom()
.loadKeyMaterial(keyStore, mch_id.toCharArray()).build();
// 只允許TLSv1協(xié)議
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
sslcontext, new String[]{"TLSv1"}, null, SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
//創(chuàng)建基于證書的httpClient,后面要用到
CloseableHttpClient client = HttpClients.custom().setSSLSocketFactory(sslsf).build();
HttpPost httpPost = new HttpPost(url);//退款接口
StringEntity reqEntity = new StringEntity(xmlParam,"UTF-8");
// 設(shè)置類型
reqEntity.setContentType("application/x-www-form-urlencoded");
httpPost.setEntity(reqEntity);
CloseableHttpResponse response = client.execute(httpPost);
try {
HttpEntity entity = response.getEntity();
System.out.println(response.getStatusLine());
if (entity != null) {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(entity.getContent(), "UTF-8"));
String text = "";
while ((text = bufferedReader.readLine()) != null) {
sb.append(text);
}
}
EntityUtils.consume(entity);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
response.close();
} catch (IOException e) {
e.printStackTrace();
}
}
} catch (KeyStoreException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
logger.warn("返回報(bào)文:"+sb.toString());
return sb.toString();
}
public static String urlEncodeUTF8(String source){
String result=source;
try {
result=java.net.URLEncoder.encode(source, "UTF-8");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
}
/**
* 解析xml,返回第一級(jí)元素鍵值對(duì)。如果第一級(jí)元素有子節(jié)點(diǎn),則此節(jié)點(diǎn)的值是子節(jié)點(diǎn)的xml數(shù)據(jù)。
* @param strxml
* @return
* @throws org.jdom2.JDOMException
* @throws IOException
*/
public static Map doXMLParse(String strxml) throws Exception {
if(null == strxml || "".equals(strxml)) {
return null;
}
Map m = new HashMap();
InputStream in = String2Inputstream(strxml);
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 = getChildrenText(children);
}
m.put(k, v);
}
in.close();
return m;
}
/**
* 獲取子結(jié)點(diǎn)的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(getChildrenText(list));
}
sb.append(value);
sb.append("</" + name + ">");
}
}
return sb.toString();
}
public static InputStream String2Inputstream(String str) {
return new ByteArrayInputStream(str.getBytes());
}
}
controller:
package com.jch.mng.controller;
import com.jch.boot.component.CommonInfo;
import com.jch.boot.component.Result;
import com.jch.boot.component.ServiceCommonInfo;
import com.jch.mng.dto.input.gzh.WxPayDto;
import com.jch.mng.service.WxPayService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Created by xxs on 2021/7/30 10:54
*
* @Description 公眾號(hào)微信支付
* @Version 2.9
*/
@RestController
@RequestMapping("/wxPay")
public class WxPayController {
@Autowired
private WxPayService payService;
/**
* @Author: xxs
* @param dto
* @param request
* @Date: 2021/7/30 11:55
* @Description: 公眾號(hào)微信支付
* @Version: 2.9
* @Return: com.jch.boot.component.Result<java.lang.String>
*/
@PostMapping("/pay")
public Result<String> pay(@RequestBody WxPayDto dto, HttpServletRequest request) throws Exception {
ServiceCommonInfo<Object> result = payService.pay(dto,request);
return CommonInfo.controllerBack(result);
}
/**
* @Author: xxs
* @param request
* @param response
* @Date: 2021/7/30 11:55
* @Description: 支付回調(diào)
* @Version: 2.9
* @Return: void
*/
@PostMapping("/notify")
public void notify(HttpServletRequest request, HttpServletResponse response) throws Exception {
payService.notify(request,response);
}
}
service接口:
package com.jch.mng.service;
import com.jch.boot.component.ServiceCommonInfo;
import com.jch.mng.dto.input.gzh.WxPayDto;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Created by xxs on 2021/7/30 9:56
*
* @Description
* @Version 2.9
*/
public interface WxPayService {
ServiceCommonInfo<Object> pay(WxPayDto dto, HttpServletRequest request) throws Exception;
void notify(HttpServletRequest request, HttpServletResponse response) throws Exception;
}
接口實(shí)現(xiàn):
package com.jch.mng.service.impl;
import com.alibaba.fastjson.JSON;
import com.jc.utils.util.CommUtils;
import com.jch.boot.component.ServiceCommonInfo;
import com.jch.mng.constant.WeChatConstants;
import com.jch.mng.dto.input.gzh.WxPayDto;
import com.jch.mng.service.WxPayService;
import com.jch.mng.utils.DoubleUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;
/**
* Created by xxs on 2021/7/30 9:56
*
* @Description
* @Version 2.9
*/
@Service
public class WxPayServiceImpl implements WxPayService {
public String appId;
public String mch_id;
public String notify_url;
public String key;
@Value("${gzh.appid}")
public void setAppId(String appId) {
this.appId = appId;
}
@Value("${wxPay.mchId}")
public void setMch_id(String mch_id) {
this.mch_id = mch_id;
}
@Value("${wxPay.notifyUrl}")
public void setNotify_url(String notify_url) {
this.notify_url = notify_url;
}
@Value("${wxPay.key}")
public void setKey(String key) {
this.key = key;
}
private static Logger logger = LoggerFactory.getLogger(WxPayServiceImpl.class);
/**
* @Author: xxs
* @param dto
* @param request
* @Date: 2021/7/30 11:01
* @Description: 微信支付
* @Version: 2.9
* @Return: com.jch.boot.component.ServiceCommonInfo<java.lang.Object>
*/
@Override
public ServiceCommonInfo<Object> pay(WxPayDto dto, HttpServletRequest request) throws Exception {
logger.info("公眾號(hào)微信支付, 入?yún)?{}", JSON.toJSONString(dto));
String openid = dto.getOpenid();
String outTradeNo = dto.getOutTradeNo();
String body = dto.getBody();
Double totalFee = dto.getTotalFee();
String nonce_str = CommUtils.getRandomStringByLength(32);
String spbill_create_ip = CommUtils.getIpAddr(request);
Map<String, String> packageParams = new HashMap<>();
packageParams.put("appid", appId);
packageParams.put("mch_id",mch_id);
packageParams.put("nonce_str", nonce_str);
packageParams.put("body", body);
packageParams.put("out_trade_no", outTradeNo);
double t = DoubleUtil.parseDouble(totalFee);//保留兩位小數(shù)
int aDouble = Integer.parseInt(new java.text.DecimalFormat("0").format(t*100));
packageParams.put("total_fee", aDouble+"");
packageParams.put("spbill_create_ip", spbill_create_ip);
packageParams.put("notify_url", notify_url);
packageParams.put("trade_type","JSAPI");
packageParams.put("openid", openid);
packageParams = CommUtils.paraFilter(packageParams);
String prestr = CommUtils.createLinkString(packageParams);
String sign = CommUtils.sign(prestr, key, "utf-8").toUpperCase();
logger.info("統(tǒng)一下單請(qǐng)求簽名:" + sign );
String xml = "<xml version='1.0' encoding='gbk'>" + "<appid>" + appId + "</appid>"
+ "<body><![CDATA[" + body + "]]></body>"
+ "<mch_id>" + mch_id + "</mch_id>"
+ "<nonce_str>" + nonce_str + "</nonce_str>"
+ "<notify_url>" + notify_url+ "</notify_url>"
+ "<openid>" + openid + "</openid>"
+ "<out_trade_no>" + outTradeNo + "</out_trade_no>"
+ "<spbill_create_ip>" + spbill_create_ip + "</spbill_create_ip>"
+ "<total_fee>" + aDouble+"" + "</total_fee>"
+ "<trade_type>" + "JSAPI" + "</trade_type>"
+ "<sign>" + sign + "</sign>"
+ "</xml>";
String result = CommUtils.httpRequest(WeChatConstants.unifiedOrderUrl, "POST", xml);
Map map = CommUtils.doXMLParse(result);
Object return_code = map.get("return_code");
logger.info("統(tǒng)一下單返回return_code:" + return_code );
if(return_code == "SUCCESS" || return_code.equals(return_code)){
Map<String,String> resultMap=new HashMap<String, String>();
String prepay_id = (String) map.get("prepay_id");
resultMap.put("appId", appId);
Long timeStamp = System.currentTimeMillis() / 1000;
resultMap.put("timeStamp", timeStamp + "");
resultMap.put("nonceStr", nonce_str);
resultMap.put("package", "prepay_id=" + prepay_id);
resultMap.put("signType", "MD5");
logger.info("參與paySign簽名數(shù)據(jù), 入?yún)?{}", JSON.toJSONString(resultMap));
String linkString = CommUtils.createLinkString(resultMap);
String paySign = CommUtils.sign(linkString, key, "utf-8").toUpperCase();
logger.info("獲取到paySign:"+paySign);
resultMap.put("paySign", paySign);
return ServiceCommonInfo.success("ok", resultMap);
}
return ServiceCommonInfo.serviceFail("支付失敗", null);
}
/**
* @Author: xxs
* @param request
* @param response
* @Date: 2021/7/31 15:17
* @Description: 微信支付回調(diào)
* @Version: 2.9
* @Return: void
*/
@Override
public void notify(HttpServletRequest request, HttpServletResponse response) throws Exception {
logger.info("進(jìn)入支付回調(diào)啦啦啦啦*-*");
String resXml = "";
BufferedReader br = new BufferedReader(new InputStreamReader((ServletInputStream) request.getInputStream()));
String line = null;
StringBuilder sb = new StringBuilder();
while ((line = br.readLine()) != null) {
sb.append(line);
}
br.close();
String notityXml = sb.toString();
logger.info("支付回調(diào)返回?cái)?shù)據(jù):"+notityXml);
Map map = CommUtils.doXMLParse(notityXml);
Object returnCode = map.get("return_code");
Object result_code = map.get("result_code");
if ("SUCCESS".equals(returnCode) && "SUCCESS".equals(result_code)) {
Map<String, String> validParams = CommUtils.paraFilter(map); //回調(diào)驗(yàn)簽時(shí)需要去除sign和空值參數(shù)
String validStr = CommUtils.createLinkString(validParams);//把數(shù)組所有元素,按照“參數(shù)=參數(shù)值”的模式用“&”字符拼接成字符串
String sign = CommUtils.sign(validStr, key , "utf-8").toUpperCase();//拼裝生成服務(wù)器端驗(yàn)證的簽名
logger.info("支付回調(diào)生成簽名:"+sign);
String transaction_id = (String) map.get("transaction_id");
String order_no = (String) map.get("out_trade_no");
String time_end = (String) map.get("time_end");
String total_fee = (String) map.get("total_fee");
//簽名驗(yàn)證,并校驗(yàn)返回的訂單金額是否與商戶側(cè)的訂單金額一致
if (sign.equals(map.get("sign"))) {
logger.info("支付回調(diào)驗(yàn)簽通過");
//通知微信服務(wù)器已經(jīng)支付成功
resXml = WeChatConstants.SUCCESSxml;
} else {
logger.info("微信支付回調(diào)失敗!簽名不一致");
}
}else{
resXml = WeChatConstants.ERRORxml;
}
System.out.println(resXml);
logger.info("微信支付回調(diào)返回?cái)?shù)據(jù):"+resXml);
logger.info("微信支付回調(diào)數(shù)據(jù)結(jié)束");
BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());
out.write(resXml.getBytes());
out.flush();
out.close();
}
}
前端頁面:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<meta content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0;" name="viewport" />
</head>
<body>
body: <input type="text" class="inp-body"><br>
outTradeNo: <input type="text" class="inp-outTradeNo"><br>
totalFee: <input type="text" class="inp-totalFee"><br>
openid: <input type="text" class="inp-openid"><br>
<button onclick="handleWxPay()">支付</button>
</body>
</html>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
function handleWxPay(){
let obj = {
"body":$(".inp-body").val(),
"outTradeNo":$(".inp-outTradeNo").val(),
"totalFee":$(".inp-totalFee").val(),
"openid":$(".inp-openid").val(),
}
$.ajax({
type: "POST",
url: "微信支付接口地址",
data:JSON.stringify(obj),
beforeSend: function(request) {
request.setRequestHeader("Content-Type","application/json");
},
success: result=> {
let obj = JSON.parse(result.data)
onBridgeReady(obj)
}
});
}
function onBridgeReady(obj){
WeixinJSBridge.invoke(
'getBrandWCPayRequest', obj,
function(res){
alert(JSON.stringify(res))
if(res.err_msg == "get_brand_wcpay_request:ok" ){
// 使用以上方式判斷前端返回,微信團(tuán)隊(duì)鄭重提示:
//res.err_msg將在用戶支付成功后返回ok,但并不保證它絕對(duì)可靠。
}
});
}
</script>
訪問前端頁面記得加依賴:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
訪問頁面需要寫控制類:
package com.jch.mng.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.http.HttpServletResponse;
/**
* Created by xxs on 2021/7/31 12:29
*
* @Description
* @Version 2.9
*/
@Controller
public class TestPageController {
@RequestMapping("/wxPayTest")
public String test(HttpServletResponse response) {
return "wxPay";
}
}
運(yùn)行項(xiàng)目訪問。

部署項(xiàng)目到服務(wù)器,用手機(jī)訪問即可拉起支付。
附:名詞解釋
商戶號(hào):微信支付分配的商戶號(hào)。支付審核通過后,申請(qǐng)人郵箱會(huì)收到騰訊下發(fā)的開戶郵件, 郵件中包含商戶平臺(tái)的賬號(hào)、密碼等重要信息。
appid:商戶通過微信管理后臺(tái),申請(qǐng)服務(wù)號(hào)、訂閱號(hào)、小程序或APP應(yīng)用成功之后,微信會(huì)為每個(gè)應(yīng)用分配一個(gè)唯一標(biāo)識(shí)id。
openid:用戶在公眾號(hào)內(nèi)的身份標(biāo)識(shí),一旦確認(rèn),不會(huì)再變;同一用戶在不同公眾號(hào)擁有不同的openid。商戶后臺(tái)系統(tǒng)通過登錄授權(quán)、支付通知、查詢訂單等API可獲取到用戶的openid。主要用途是判斷同一個(gè)用戶,對(duì)用戶發(fā)送客服消息、模版消息等。
微信管理后臺(tái):微信有很多管理平臺(tái),容易混淆,我們主要關(guān)注下面三個(gè)平臺(tái):
1. 微信公眾平臺(tái) 微信公眾賬號(hào)申請(qǐng)入口和管理后臺(tái)。商戶可以在公眾平臺(tái)提交基本資料、業(yè)務(wù)資料、財(cái)務(wù)資料申請(qǐng)開通微信支付功能。帳號(hào)分類:服務(wù)號(hào)、訂閱號(hào)、小程序、企業(yè)微信(也叫企業(yè)號(hào),類似于企業(yè)OA)。
2. 微信商戶平臺(tái) 微信支付相關(guān)的商戶功能集合,包括參數(shù)配置、支付數(shù)據(jù)查詢與統(tǒng)計(jì)、在線退款、代金券或立減優(yōu)惠運(yùn)營等功能。
3. 微信開放平臺(tái) 商戶APP接入微信支付開放接口的申請(qǐng)入口,通過此平臺(tái)可申請(qǐng)微信APP支付。
簽名:商戶后臺(tái)和微信支付后臺(tái)根據(jù)相同的密鑰和算法生成一個(gè)結(jié)果,用于校驗(yàn)雙方身份合法性。簽名的算法 由微信支付制定并公開,常用的簽名方式有:MD5、SHA1、SHA256、HMAC等。
密鑰:作為簽名算法中的鹽,需要在微信平臺(tái)及商戶業(yè)務(wù)系統(tǒng)各存一份,要妥善保管。 key設(shè)置路徑:微信商戶平臺(tái)(http://pay.weixin.qq.com)-->賬戶設(shè)置-->API安全-->密鑰設(shè)置。
總結(jié)
到此這篇關(guān)于springboot對(duì)接微信支付的文章就介紹到這了,更多相關(guān)springboot對(duì)接微信支付內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- SpringBoot實(shí)現(xiàn)微信支付接口調(diào)用及回調(diào)函數(shù)(商戶參數(shù)獲取)
- java?Springboot對(duì)接開發(fā)微信支付詳細(xì)流程
- SpringBoot對(duì)接小程序微信支付的實(shí)現(xiàn)
- Springboot整合微信支付(訂單過期取消及商戶主動(dòng)查單)
- UniApp?+?SpringBoot?實(shí)現(xiàn)微信支付和退款功能
- SpringBoot實(shí)現(xiàn)整合微信支付方法詳解
- 一篇文章帶你入門Springboot整合微信登錄與微信支付(附源碼)
- springboot整合微信支付sdk過程解析
- SpringBoot+MyBatis集成微信支付實(shí)現(xiàn)示例
相關(guān)文章
Springcloud基于OpenFeign實(shí)現(xiàn)服務(wù)調(diào)用代碼實(shí)例
這篇文章主要介紹了Springcloud基于OpenFeign實(shí)現(xiàn)服務(wù)調(diào)用代碼實(shí)例,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-08-08
詳解springboot項(xiàng)目帶Tomcat和不帶Tomcat的兩種打包方式
這篇文章主要介紹了詳解springboot項(xiàng)目帶Tomcat和不帶Tomcat的兩種打包方式,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-09-09
mybatis-plus動(dòng)態(tài)數(shù)據(jù)源讀寫分離方式
在分布式項(xiàng)目開發(fā)中,動(dòng)態(tài)數(shù)據(jù)源的配置與使用至關(guān)重要,通過創(chuàng)建DynamicDatasourceService,實(shí)現(xiàn)數(shù)據(jù)源的動(dòng)態(tài)添加與調(diào)用,有效管理主從庫操作,減輕數(shù)據(jù)庫壓力,此外,通過配置類與@DS注解,實(shí)現(xiàn)了靈活的分庫查詢功能,為高效處理數(shù)據(jù)提供了強(qiáng)有力的支持2024-10-10
java實(shí)現(xiàn)簡單登錄界面的實(shí)戰(zhàn)過程
學(xué)習(xí)JAVA的過程當(dāng)中,登陸界面是多數(shù)人第一個(gè)實(shí)現(xiàn)的小程序,下面這篇文章主要給大家介紹了關(guān)于利用java實(shí)現(xiàn)簡單登錄界面的相關(guān)資料,文中通過實(shí)例代碼介紹的非常詳細(xì),需要的朋友可以參考下2022-05-05
基于springmvc之常用注解,操作傳入?yún)?shù)
這篇文章主要介紹了springmvc之常用注解,操作傳入?yún)?shù)方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-09-09
Java藍(lán)橋杯實(shí)現(xiàn)線段和點(diǎn)
本文主要介紹Java藍(lán)橋杯實(shí)現(xiàn)線段和點(diǎn)的內(nèi)容,感興趣的小伙伴可以參考下文2021-08-08
Spring ApplicationListener的使用詳解
這篇文章主要介紹了Spring ApplicationListener的使用,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-06-06

