国产 无码 综合区,色欲AV无码国产永久播放,无码天堂亚洲国产AV,国产日韩欧美女同一区二区

SpringBoot對接微信小程序支付功能開發(fā)(一,下單功能)

這篇具有很好參考價值的文章主要介紹了SpringBoot對接微信小程序支付功能開發(fā)(一,下單功能)。希望對大家有所幫助。如果存在錯誤或未考慮完全的地方,請大家不吝賜教,您也可以點擊"舉報違法"按鈕提交疑問。

1,接入前準(zhǔn)備:

  1. 接入模式選擇直連模式;
  2. 申請小程序,得到APPID,并開通微信支付;
  3. 申請微信商戶號,得到mchid,并綁定APPID;
  4. 配置商戶API key,下載并配置商戶證書,根據(jù)微信官方文檔操作:https://pay.weixin.qq.com/wiki/doc/apiv3/open/pay/chapter2_8_1.shtml
  5. 上面都配置完之后會得到:小程序APPID、商戶號mchid、商戶證書序列號、API_V3密鑰、商戶私鑰。

2,代碼開發(fā)

引入微信支付API v3依賴

        <!--微信支付依賴 v3版本-->
        <dependency>
            <groupId>com.github.wechatpay-apiv3</groupId>
            <artifactId>wechatpay-apache-httpclient</artifactId>
            <version>0.2.2</version>
        </dependency>

微信參數(shù)常量類:WechatPayConstant 參數(shù)自行更換

package com.office.miniapp.constants;

/**
 * @InterfaceName: WechatPayConstant
 * @Description: 微信支付常量類
 * @Authror: XQD
 * @Date: 2022/1/6 15:02
 */
public interface WechatPayConstant {

    /**
     * 支付結(jié)果回調(diào)地址
     */
    String NOTIFY_URL = "線上域名地址/miniapp/wxPay/callback";
    
    /**
     * 退款結(jié)果回調(diào)地址
     */
    String REFUNDS_URL = "線上域名地址/miniapp/refunds/callback";

    /**
     * 商戶號
     */
    String MCH_ID = "***";

    /**
     * 商戶證書序列號
     */
    String MCH_SERIAL_NO = "***";

    /**
     * API_V3密鑰
     */
    String API_V3KEY = "***";

    /**
     * 小程序appId
     */
    String MP_APP_ID = "***";

    /**
     * 商戶私鑰
     */
    String PRIVATE_KEY = "-----BEGIN PRIVATE KEY-----\n" +
            "省略..." +
            "-----END PRIVATE KEY-----\n";

    /**
     * jsapi下單url
     */
    String V3_JSAPI_URL = "https://api.mch.weixin.qq.com/v3/pay/transactions/jsapi";

    /**
     * 商戶訂單號查詢url
     */
    String V3_OUT_TRADE_NO = "https://api.mch.weixin.qq.com/v3/pay/transactions/out-trade-no/{out_trade_no}";

    /**
     * 關(guān)閉訂單url
     */
    String V3_CLOSE = "https://api.mch.weixin.qq.com/v3/pay/transactions/out-trade-no/{out_trade_no}/close";

}

微信支付工具類:WxPayUtil (自己封裝的)

package com.office.miniapp.utils;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.office.miniapp.constants.WechatPayConstant;
import com.wechat.pay.contrib.apache.httpclient.WechatPayHttpClientBuilder;
import com.wechat.pay.contrib.apache.httpclient.auth.AutoUpdateCertificatesVerifier;
import com.wechat.pay.contrib.apache.httpclient.auth.PrivateKeySigner;
import com.wechat.pay.contrib.apache.httpclient.auth.WechatPay2Credentials;
import com.wechat.pay.contrib.apache.httpclient.auth.WechatPay2Validator;
import com.wechat.pay.contrib.apache.httpclient.util.AesUtil;
import com.wechat.pay.contrib.apache.httpclient.util.PemUtil;
import org.apache.http.impl.client.CloseableHttpClient;
import org.springframework.stereotype.Component;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.GeneralSecurityException;
import java.security.PrivateKey;
import java.security.Signature;
import java.util.Base64;

/**
 * @ClassName: WxPayUtil
 * @Description: 微信支付工具類
 * @Authror: XQD
 * @Date: 2022/8/13 23:04
 */
@Component
public class WxPayUtil {

    /**
     * @Description: 獲取httpClient
     * @Param: []
     * @return: org.apache.http.impl.client.CloseableHttpClient
     * @Author: XQD
     * @Date:2022/8/13 23:16
     */
    public static CloseableHttpClient getHttpClient() {
        CloseableHttpClient httpClient = null;
        // 加載商戶私鑰(privateKey:私鑰字符串)
        try {
            PrivateKey merchantPrivateKey = PemUtil.loadPrivateKey(
                    new ByteArrayInputStream(WechatPayConstant.PRIVATE_KEY.getBytes("utf-8")));
        //使用自動更新的簽名驗證器,不需要傳入證書
        AutoUpdateCertificatesVerifier verifier = new AutoUpdateCertificatesVerifier(
                new WechatPay2Credentials(WechatPayConstant.MCH_ID, new PrivateKeySigner(WechatPayConstant.MCH_SERIAL_NO, merchantPrivateKey)),
                WechatPayConstant.API_V3KEY.getBytes("utf-8"));
        // 初始化httpClient
        httpClient = WechatPayHttpClientBuilder.create()
                .withMerchant(WechatPayConstant.MCH_ID, WechatPayConstant.MCH_SERIAL_NO, merchantPrivateKey)
                .withValidator(new WechatPay2Validator(verifier))
                .build();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return httpClient;
    }


    /**
     * @Description: 生成簽名
     * @Param: [message]
     * @return: java.lang.String
     * @Author: XQD
     * @Date:2022/6/7 16:00
     */
    public static String sign(byte[] message) throws Exception {
        Signature sign = Signature.getInstance("SHA256withRSA");
        PrivateKey privateKey = PemUtil.loadPrivateKey(new ByteArrayInputStream(WechatPayConstant.PRIVATE_KEY.getBytes("utf-8")));
        sign.initSign(privateKey);
        sign.update(message);
        return Base64.getEncoder().encodeToString(sign.sign());
    }


    /**
     * @Description: 驗證簽名
     * @Param: [serial, message, signature]請求頭中帶的序列號, 驗簽名串, 請求頭中的應(yīng)答簽名
     * @return: boolean
     * @Author: XQD
     * @Date:2021/9/14 10:36
     */
    public static boolean signVerify(String serial, String message, String signature) {
        AutoUpdateCertificatesVerifier verifier = null;
        try {
            // 加載商戶私鑰(privateKey:私鑰字符串)
            PrivateKey merchantPrivateKey = PemUtil.loadPrivateKey(
                    new ByteArrayInputStream(WechatPayConstant.PRIVATE_KEY.getBytes("utf-8")));

            //使用自動更新的簽名驗證器,不需要傳入證書
            verifier = new AutoUpdateCertificatesVerifier(
                    new WechatPay2Credentials(WechatPayConstant.MCH_ID, new PrivateKeySigner(WechatPayConstant.MCH_SERIAL_NO, merchantPrivateKey)),
                    WechatPayConstant.API_V3KEY.getBytes("utf-8"));
            return verifier.verify(serial, message.getBytes("utf-8"), signature);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * @Description: 解密訂單信息
     * @Param: [body] 應(yīng)答報文主體
     * @return: java.lang.String
     * @Author: XQD
     * @Date:2021/9/14 11:48
     */
    public static String decryptOrder(String body) {
        try {
            AesUtil aesUtil = new AesUtil(WechatPayConstant.API_V3KEY.getBytes("utf-8"));
            ObjectMapper objectMapper = new ObjectMapper();
            JsonNode node = objectMapper.readTree(body);
            JsonNode resource = node.get("resource");
            String ciphertext = resource.get("ciphertext").textValue();
            String associatedData = resource.get("associated_data").textValue();
            String nonce = resource.get("nonce").textValue();
            return aesUtil.decryptToString(associatedData.getBytes("utf-8"), nonce.getBytes("utf-8"), ciphertext);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (GeneralSecurityException e) {
            e.printStackTrace();
        }
        return "";
    }

}

下單接口調(diào)用

下單功能實現(xiàn),返回預(yù)支付交易會話標(biāo)識prepay_id

	/**
     * @Description: 小程序下單
     * @Param: [userId, orders]
     * @return: java.lang.Object
     * @Author: XQD
     * @Date:2022/8/13 18:48
     */
    @Override
    public CommonResult submitOrder() throws Exception {
        // 小程序下單
        CloseableHttpClient httpClient = WxPayUtil.getHttpClient();
        HttpPost httpPost = new HttpPost(WechatPayConstant.V3_JSAPI_URL);
        httpPost.addHeader("Accept", "application/json");
        httpPost.addHeader("Content-type", "application/json; charset=utf-8");

        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        ObjectMapper objectMapper = new ObjectMapper();

        ObjectNode rootNode = objectMapper.createObjectNode();
        rootNode.put("mchid", WechatPayConstant.MCH_ID)
                .put("appid", WechatPayConstant.MP_APP_ID)
                .put("notify_url", WechatPayConstant.NOTIFY_URL)
                .put("description", "商品描述信息")
                .put("out_trade_no", System.currentTimeMillis() + "");
        rootNode.putObject("amount")
                .put("total", 100);// 訂單支付金額
        rootNode.putObject("payer")
                .put("openid", "小程序用戶openid");
        objectMapper.writeValue(bos, rootNode);

        httpPost.setEntity(new StringEntity(bos.toString("UTF-8"), "UTF-8"));
        //完成簽名并執(zhí)行請求
        CloseableHttpResponse response = httpClient.execute(httpPost);
        try {
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode == 200) {
                //處理成功返回的數(shù)據(jù)
                String body= EntityUtils.toString(response.getEntity());
                //JSONObject jsonObject = JSON.parseObject(body);
                //獲取預(yù)支付交易會話標(biāo)識  prepay_id
                //String prepayId= jsonObject.getString("prepay_id");
                //把上面的訂單信息存入訂單數(shù)據(jù)庫
                return body;
            } else if (statusCode == 204) {
                // 處理成功,無返回Body
                return "success";
            } else {
                System.out.println("failed,resp code = " + statusCode + ",return body = " + EntityUtils.toString(response.getEntity()));
                throw new IOException("request failed");
            }
        } finally {
            response.close();
        }
    }

到這里代表下單操作完成了。把預(yù)支付交易id(prepay_id)返回前端,進(jìn)行拉起支付操作

查詢訂單接口調(diào)用
    /**
     * @Description: 查詢訂單
     * @Param: [outTradeNo] 商戶訂單號
     * @return: java.lang.Object
     * @Author: XQD
     * @Date:2022/8/14 21:43
     */
    @Override
    public Object queryOrder(String outTradeNo) throws Exception {
        CloseableHttpClient httpClient = WxPayUtil.getHttpClient();
        String v3_out_trade_no = WechatPayConstant.V3_OUT_TRADE_NO.replaceFirst("\\{out_trade_no}", outTradeNo);
        HttpGet httpGet = new HttpGet(v3_out_trade_no + "?mchid=" + WechatPayConstant.MCH_ID);
        httpGet.addHeader("Accept", "application/json");
        CloseableHttpResponse response = httpClient.execute(httpGet);
        String bodyAsString = EntityUtils.toString(response.getEntity());
        System.out.println(bodyAsString);
        return bodyAsString;
    }
關(guān)閉訂單接口調(diào)用
 /**
     * @Description: 關(guān)閉訂單
     * @Param: [outTradeNo] 商戶訂單號
     * @return: java.lang.Object
     * @Author: XQD
     * @Date:2022/8/14 21:43
     */
    @Override
    public Object closeOrder(String outTradeNo) throws Exception {
        CloseableHttpClient httpClient = WxPayUtil.getHttpClient();
        String v3_close = WechatPayConstant.V3_CLOSE.replaceFirst("\\{out_trade_no}", outTradeNo);
        HttpPost httpPost = new HttpPost(v3_close);
        httpPost.addHeader("Accept", "application/json");
        httpPost.addHeader("Content-type", "application/json; charset=utf-8");

        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        ObjectMapper objectMapper = new ObjectMapper();

        ObjectNode rootNode = objectMapper.createObjectNode();
        rootNode.put("mchid", WechatPayConstant.MCH_ID);

        objectMapper.writeValue(bos, rootNode);

        httpPost.setEntity(new StringEntity(bos.toString("UTF-8"), "UTF-8"));
        CloseableHttpResponse response = httpClient.execute(httpPost);
        // 狀態(tài)碼 204表示關(guān)單成功
        int statusCode = response.getStatusLine().getStatusCode();
        log.info("關(guān)閉訂單返回碼:{}", statusCode);
        if (statusCode == 204) {
            return "關(guān)單成功";
        }
        return "關(guān)單失敗";
    }

下一篇: SpringBoot對接微信小程序支付功能開發(fā)(二,支付回調(diào)功能)文章來源地址http://www.zghlxwxcb.cn/news/detail-495906.html

到了這里,關(guān)于SpringBoot對接微信小程序支付功能開發(fā)(一,下單功能)的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!

本文來自互聯(lián)網(wǎng)用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務(wù),不擁有所有權(quán),不承擔(dān)相關(guān)法律責(zé)任。如若轉(zhuǎn)載,請注明出處: 如若內(nèi)容造成侵權(quán)/違法違規(guī)/事實不符,請點擊違法舉報進(jìn)行投訴反饋,一經(jīng)查實,立即刪除!

領(lǐng)支付寶紅包贊助服務(wù)器費用

相關(guān)文章

覺得文章有用就打賞一下文章作者

支付寶掃一掃打賞

博客贊助

微信掃一掃打賞

請作者喝杯咖啡吧~博客贊助

支付寶掃一掃領(lǐng)取紅包,優(yōu)惠每天領(lǐng)

二維碼1

領(lǐng)取紅包

二維碼2

領(lǐng)紅包