欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

springboot對接微信支付的完整流程(附前后端代碼)

 更新時間:2021年08月03日 09:22:25   作者:小小舍  
最近在做支付平臺的項目,承接公司業(yè)務(wù)系統(tǒng)與第三方支付平臺的對接任務(wù),主要涉及微信支付、支付寶支付以及理房通支付等第三方平臺,這篇文章主要給大家介紹了關(guān)于springboot對接微信支付的完整流程,需要的朋友可以參考下

展示圖:

 

對接的完整流程如下

首先是配置

gzh.appid=公眾號appid
wxPay.mchId=商戶號
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" +
            "";

工具類準備:

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);
    // 連接超時時間,默認10秒
    private static int socketTimeout = 60000;
 
    // 傳輸超時時間,默認30秒
    private static int connectTimeout= 60000;
    /**
     * Util工具類方法
     * 獲取一定長度的隨機字符串,范圍0-9,a-z
     * @param length:指定字符串長度
     * @return 一定長度的隨機字符串
     */
    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();
    }
 
    /**
     * 獲取訂單號
     * @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位隨機數(shù)
        String resultCode = time+mathCode;
        return resultCode;
    }
 
    /**
     * Util工具類方法
     * 獲取真實的ip地址
     * @param request
     * @return
     */
    public static String getIpAddr(HttpServletRequest request) {
        String ip = request.getHeader("X-Forwarded-For");
        if (StringUtils.isNotEmpty(ip) && !"unKnown".equalsIgnoreCase(ip)) {
            //多次反向代理后會有多個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)錯誤,指定的編碼集不對,您目前指定的編碼集是:" + charset);
        }
    }
 
    /**
     * 生成6位或10位隨機數(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) {// 拼接時,不包括最后一個&字符
                prestr = prestr + key + "=" + value;
            } else {
                prestr = prestr + key + "=" + value + "&";
            }
        }
        return prestr;
    }
    /**
     *
     * @param requestUrl 請求地址
     * @param requestMethod 請求方法
     * @param outputStr 參數(shù)
     */
    public static String httpRequest(String requestUrl,String requestMethod,String outputStr){
        logger.warn("請求報文:"+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("返回報文:"+buffer.toString());
        return buffer.toString();
    }
 
    /**
     * POST請求
     * @param url           請求url
     * @param xmlParam      請求參數(shù)
     * @param apiclient     證書
     * @param mch_id        商戶號
     * @return
     * @throws Exception
     */
    public static String post(String url, String xmlParam,String apiclient,String mch_id) throws Exception {
        logger.warn("請求報文:"+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("返回報文:"+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,返回第一級元素鍵值對。如果第一級元素有子節(jié)點,則此節(jié)點的值是子節(jié)點的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é)點的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 公眾號微信支付
 * @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:  公眾號微信支付
    * @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;
}

接口實現(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("公眾號微信支付, 入?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)一下單請求簽名:" + 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("進入支付回調(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)返回數(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)驗簽時需要去除sign和空值參數(shù)
            String validStr = CommUtils.createLinkString(validParams);//把數(shù)組所有元素,按照“參數(shù)=參數(shù)值”的模式用“&”字符拼接成字符串
            String sign = CommUtils.sign(validStr, key , "utf-8").toUpperCase();//拼裝生成服務(wù)器端驗證的簽名
            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");
            //簽名驗證,并校驗返回的訂單金額是否與商戶側(cè)的訂單金額一致
            if (sign.equals(map.get("sign"))) {
                logger.info("支付回調(diào)驗簽通過");
                //通知微信服務(wù)器已經(jīng)支付成功
                resXml = WeChatConstants.SUCCESSxml;
            } else {
                logger.info("微信支付回調(diào)失敗!簽名不一致");
            }
        }else{
            resXml = WeChatConstants.ERRORxml;
        }
        System.out.println(resXml);
        logger.info("微信支付回調(diào)返回數(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" ){
                    // 使用以上方式判斷前端返回,微信團隊鄭重提示:
                    //res.err_msg將在用戶支付成功后返回ok,但并不保證它絕對可靠。
                }
            });
    }
</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";
    }
}

運行項目訪問。

部署項目到服務(wù)器,用手機訪問即可拉起支付。

附:名詞解釋

商戶號:微信支付分配的商戶號。支付審核通過后,申請人郵箱會收到騰訊下發(fā)的開戶郵件, 郵件中包含商戶平臺的賬號、密碼等重要信息。

appid:商戶通過微信管理后臺,申請服務(wù)號、訂閱號、小程序或APP應(yīng)用成功之后,微信會為每個應(yīng)用分配一個唯一標識id。

openid:用戶在公眾號內(nèi)的身份標識,一旦確認,不會再變;同一用戶在不同公眾號擁有不同的openid。商戶后臺系統(tǒng)通過登錄授權(quán)、支付通知、查詢訂單等API可獲取到用戶的openid。主要用途是判斷同一個用戶,對用戶發(fā)送客服消息、模版消息等。

微信管理后臺:微信有很多管理平臺,容易混淆,我們主要關(guān)注下面三個平臺:

1. 微信公眾平臺 微信公眾賬號申請入口和管理后臺。商戶可以在公眾平臺提交基本資料、業(yè)務(wù)資料、財務(wù)資料申請開通微信支付功能。帳號分類:服務(wù)號、訂閱號、小程序、企業(yè)微信(也叫企業(yè)號,類似于企業(yè)OA)。

2. 微信商戶平臺 微信支付相關(guān)的商戶功能集合,包括參數(shù)配置、支付數(shù)據(jù)查詢與統(tǒng)計、在線退款、代金券或立減優(yōu)惠運營等功能。

3. 微信開放平臺 商戶APP接入微信支付開放接口的申請入口,通過此平臺可申請微信APP支付。

簽名:商戶后臺和微信支付后臺根據(jù)相同的密鑰和算法生成一個結(jié)果,用于校驗雙方身份合法性。簽名的算法 由微信支付制定并公開,常用的簽名方式有:MD5、SHA1、SHA256、HMAC等。

密鑰:作為簽名算法中的鹽,需要在微信平臺及商戶業(yè)務(wù)系統(tǒng)各存一份,要妥善保管。 key設(shè)置路徑:微信商戶平臺(http://pay.weixin.qq.com)-->賬戶設(shè)置-->API安全-->密鑰設(shè)置。

總結(jié)

到此這篇關(guān)于springboot對接微信支付的文章就介紹到這了,更多相關(guān)springboot對接微信支付內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • Java @Async注解導(dǎo)致spring啟動失敗解決方案詳解

    Java @Async注解導(dǎo)致spring啟動失敗解決方案詳解

    這篇文章主要介紹了Java @Async注解導(dǎo)致spring啟動失敗解決方案詳解,本篇文章通過簡要的案例,講解了該項技術(shù)的了解與使用,以下就是詳細內(nèi)容,需要的朋友可以參考下
    2021-08-08
  • java多線程-同步塊實例講解

    java多線程-同步塊實例講解

    本文主要介紹java多線程-同步塊的知識,這里整理了相關(guān)的詳細資料及簡單示例代碼,有興趣的小伙伴可以參考下
    2016-09-09
  • Java如何使用JSR303校驗數(shù)據(jù)與自定義校驗注解

    Java如何使用JSR303校驗數(shù)據(jù)與自定義校驗注解

    這篇文章主要介紹了Java如何使用JSR303校驗數(shù)據(jù)與自定義校驗注解,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2020-09-09
  • java動態(tài)代理和cglib動態(tài)代理示例分享

    java動態(tài)代理和cglib動態(tài)代理示例分享

    這篇文章主要介紹了java動態(tài)代理和cglib動態(tài)代理示例,JDK1.3之后,Java提供了動態(tài)代理的技術(shù),允許開發(fā)者在運行期間創(chuàng)建接口的代理實例,下面我們使用示例學習一下
    2014-03-03
  • Java以命令模式設(shè)計模式

    Java以命令模式設(shè)計模式

    這篇文章主要詳細的介紹Java以命令的模式設(shè)計模式,是用場景、優(yōu)缺點等都作有詳細介紹,需要的朋友請具體參考下面文章內(nèi)容
    2021-09-09
  • Spring Bean Scope 有狀態(tài)的Bean與無狀態(tài)的Bean

    Spring Bean Scope 有狀態(tài)的Bean與無狀態(tài)的Bean

    這篇文章主要介紹了Spring Bean Scope 有狀態(tài)的Bean與無狀態(tài)的Bean,每個用戶有自己特有的一個實例,在用戶的生存期內(nèi),bean保持了用戶的信息,下面來了解有狀態(tài)和無狀態(tài)的區(qū)別吧
    2022-01-01
  • 解決Maven多模塊編譯慢的問題

    解決Maven多模塊編譯慢的問題

    這篇文章主要介紹了Maven多模塊編譯慢的問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2021-09-09
  • Java并發(fā)編程之ConcurrentLinkedQueue隊列詳情

    Java并發(fā)編程之ConcurrentLinkedQueue隊列詳情

    這篇文章主要介紹了Java并發(fā)編程之ConcurrentLinkedQueue隊列詳情,ConcurrentLinkedQueue?內(nèi)部的隊列使用單向鏈表方式實現(xiàn),下文更多相關(guān)內(nèi)容敘述需要的小伙伴可以參考一下
    2022-04-04
  • 詳解關(guān)于eclipse中使用jdk15對應(yīng)javafx15的配置問題總結(jié)

    詳解關(guān)于eclipse中使用jdk15對應(yīng)javafx15的配置問題總結(jié)

    這篇文章主要介紹了詳解關(guān)于eclipse中使用jdk15對應(yīng)javafx15的配置問題總結(jié),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2020-11-11
  • 解決Properties屬性文件中的值有等號和換行的小問題

    解決Properties屬性文件中的值有等號和換行的小問題

    這篇文章主要介紹了解決Properties屬性文件中的值有等號有換行的小問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2021-08-08

最新評論