Bootstrap

微信支付工具类 小程序 扫码

1.maven导入wxpay-sdk-3.0.9

    <dependency>
        <groupId>com.github.wxpay</groupId>
        <artifactId>wxpay-sdk</artifactId>
        <version>3.0.9</version>
    </dependency>

sdk下载地址:https://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=11_1

注:下载后请自行打成jar包

2.新建WxConfig 继承sdk里面的WXPayConfig

package com.liaoin.tourism.config;

import com.github.wxpay.sdk.*;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

public class WxConfig extends WXPayConfig {

    private byte[] certData;
	//如不需要更换appID就直接写死 例:private String toAppId = "xxxxxx";
    private String toAppId;

    public String getToAppId() {
        return toAppId;
    }

    public void setToAppId(String toAppId) {
        this.toAppId = toAppId;
    }

    public String getAppID() {
        return toAppId;
    }
	
	// 支付商户平台的商户id
    public String getMchID() {
        return "xxxx";
    }
	
    public String getKey() {
        return "xxxx";
    }

    public WxConfig() throws Exception { // 构造方法读取证书, 通过getCertStream 可以使sdk获取到证书
        String certPath = "C:\\Users\\admin\\Desktop\\xxx\\pay\\1500120982_20200407_cert/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();
    }

    @Override
    public InputStream getCertStream() {
        return new ByteArrayInputStream(this.certData);
    }

    @Override
    public IWXPayDomain getWXPayDomain() { // 这个方法需要这样实现, 否则无法正常初始化WXPay
        IWXPayDomain iwxPayDomain = new IWXPayDomain() {
            @Override
            public void report(String domain, long elapsedTimeMillis, Exception ex) {

            }
            @Override
            public DomainInfo getDomain(WXPayConfig config) {
                return new IWXPayDomain.DomainInfo(WXPayConstants.DOMAIN_API, true);
            }
        };
        return iwxPayDomain;
    }


    public int getHttpConnectTimeoutMs() {
        return 8000;
    }

    public int getHttpReadTimeoutMs() {
        return 10000;
    }
}

3.新建WxPayUtil工具类

package com.liaoin.tourism.util;

import com.github.wxpay.sdk.WXPay;
import com.github.wxpay.sdk.WXPayUtil;
import com.liaoin.tourism.business.tourismOrder.parameter.IcbcParameter;
import com.liaoin.tourism.common.constant.VariableConstants;
import com.liaoin.tourism.config.WxConfig;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.Map;

@Slf4j
public class WxPayUtil {

    public static WXPay getWXPay(String appId) {
        WxConfig config;
        WXPay wxpay = null;
        try {
            config = new WxConfig();
            config.setToAppId(appId);
            wxpay = new WXPay(config);
        } catch (Exception e) {
            log.error("WXPay初始化失败.");
            e.printStackTrace();
        }
        return wxpay;
    }

    public static WxConfig getWxConfig(String appId) {
        WxConfig config = null;
        try {
            config = new WxConfig();
            config.setToAppId(appId);
        } catch (Exception e) {
            log.error("获取WxConfig失败.");
            e.printStackTrace();
        }
        return config;
    }


    //微信回调地址
    public static final String wxNotifyUrlServlet = "www.baidu.com";
    /**
     * 小程序下单
     *
     *                 @param
     *                 data.put("body", "腾讯充值中心-QQ会员充值");
     *                 data.put("out_trade_no", "test2020090910595900000012");
     *                 data.put("device_info", "WEB");
     *                 data.put("fee_type", "CNY");
     *                 data.put("total_fee", "1");
     *                 data.put("spbill_create_ip", "58.17.241.195");
     *                 data.put("notify_url", "http://www.example.com/wxpay/notify");
     *                 data.put("trade_type", "JSAPI");  // 此处指定为扫码支付
     *                 data.put("product_id", "12");
     * @return
     */
    public static Map<String, String> createMiniProgramTradePay(Integer datasorce,String orderType,String body,String outTradeNo,String total_fee,String ip,String openid) {
        WXPay wxPay = null;
        WxConfig wxConfig = null;
        Map<String, String> payParam = new HashMap<String, String>();
        payParam.put("body", body);//"测试织金洞微信支付"
        payParam.put("out_trade_no", outTradeNo);//"test2020090910595900000012"
        payParam.put("device_info", "WEB");
        payParam.put("fee_type", "CNY");
        payParam.put("total_fee", total_fee); //"1"
        payParam.put("spbill_create_ip", ip);//"58.17.241.195"
        payParam.put("notify_url", wxNotifyUrlServlet); // 回调地址
        if (datasorce == 1){
            payParam.put("trade_type", "NATIVE");  // 此处指定为扫码支付
        }else{
            payParam.put("trade_type", "JSAPI");  // 此处指定为扫码支付
        }
        payParam.put("product_id", "12");
        payParam.put("openid",openid);//"oTZW-4jVzZ3GnvfNtbwv8TPhI5K8"
        payParam.put("attach","2"); // 附加信息
        String tpAppId = getWxAppId(orderType);
        if (tpAppId != null){
            payParam.put("appid",tpAppId); //应用的appId
            wxPay = getWXPay(tpAppId);
            wxConfig = getWxConfig(tpAppId);
        }

        Map<String, String> result = new HashMap<>();
        try {
            Map<String, String> resp = wxPay.unifiedOrder(payParam);
            log.info("微信支付下单成功, 返回值 response={}", resp);
            String returnCode = resp.get("return_code");
            if (!"SUCCESS".equals(returnCode)) {
                return null;
            }
            String resultCode = resp.get("result_code");
            if (!"SUCCESS".equals(resultCode)) {
                return null;
            }
            String prepay_id = resp.get("prepay_id");
            if (prepay_id == null) {
                return null;
            }
            if (datasorce == 1){
                String code_url = resp.get("code_url");
                if (code_url !=null){
                    Map<String,String> qrcode = new HashMap<>();
                    qrcode.put("qrcode",code_url);
                    return qrcode;
                }
            }
            // ******************************************
            //  前端调起微信支付必要参数
            // ******************************************
            String packages = "prepay_id=" + prepay_id;
            Map<String, String> wxPayMap = new HashMap<String, String>();
            wxPayMap.put("appId", wxConfig.getAppID());
            wxPayMap.put("timeStamp", String.valueOf(System.currentTimeMillis()));
            wxPayMap.put("nonceStr", StringUtil.generateRandomCode(false, 6));
            wxPayMap.put("package", packages);
            wxPayMap.put("signType", "MD5");

            // 加密串中包括 appId timeStamp nonceStr package signType 5个参数, 通过sdk WXPayUtil类加密, 注意, 此处使用  MD5加密  方式
            String sign = WXPayUtil.generateSignature(wxPayMap, wxConfig.getKey());
            // ******************************************
            //  返回给前端调起微信支付的必要参数
            // ******************************************
            result.put("prepay_id", prepay_id);
            result.put("paySign", sign);
            result.putAll(wxPayMap);
        } catch (Exception e) {
            log.error("微信下单失败.  Method:{},订单号:{}", "createMiniProgramTradePay", payParam.get("out_trade_no"));
            e.printStackTrace();
        }
        return result;
    }

    public static Map<String,String> closeOrder(String outTradeNo){
        WXPay wxpay = getWXPay("");
        Map<String, String> data = new HashMap<String, String>();
        data.put("out_trade_no", outTradeNo);
        try {
            Map<String, String> resp = wxpay.closeOrder(data);
            return resp;
        } catch (Exception e) {
            log.error("微信关闭订单失败. Method:{},订单号:{}", "closeOrder", outTradeNo);
            e.printStackTrace();
        }
        return null;
    }


    /**
     * 订单查询
     *
     * @param outTradeNo
     * @return
     */
    public static Map<String, String> orderQuery(String orderType,String outTradeNo) {
        WXPay wxpay = getWXPay(getWxAppId(orderType));
        Map<String, String> data = new HashMap<String, String>();
        data.put("out_trade_no", outTradeNo);
        try {
            Map<String, String> resp = wxpay.orderQuery(data);
            return resp;
        } catch (Exception e) {
            log.error("微信订单号查询失败. Method:{},订单号:{}", "orderQuery", outTradeNo);
            e.printStackTrace();
        }
        return null;
    }

    public static Boolean orderQueryState(String orderType,String outTradeNo){
        WXPay wxpay = getWXPay(getWxAppId(orderType));
        Map<String, String> data = new HashMap<String, String>();
        data.put("out_trade_no", outTradeNo);
        try {
            Map<String, String> resp = wxpay.orderQuery(data);
            if (resp.get("trade_state") == null || !resp.get("trade_state").equalsIgnoreCase("SUCCESS")){
                return false;
            }
            return true;
        } catch (Exception e) {
            log.error("微信订单号查询失败. Method:{},订单号:{}", "orderQuery", outTradeNo);
            e.printStackTrace();
        }
        return false;
    }


    /**
     * 退款查询
     *
     * @param outTradeNo
     * @return
     */
    public static Map<String, String> refundQuery(String outTradeNo) {
        WXPay wxpay = getWXPay("");
        Map<String, String> data = new HashMap<String, String>();
        data.put("out_trade_no", outTradeNo);
        try {
            Map<String, String> resp = wxpay.refundQuery(data);
            return resp;
        } catch (Exception e) {
            log.error("微信退款查询失败. Method:{},订单号:{}", "refundQuery", outTradeNo);
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 退款接口
     * @param outTradeNo 订单号
     * @param outRefundNo 退款号
     * @param refundFee 退款金额
     * @return
     */
    public static  Map<String, String> refund(String outTradeNo,String outRefundNo,String refundFee,String notifyUrl){
        WXPay wxpay = getWXPay("");
        Map<String, String> data = new HashMap<String, String>();
        data.put("out_trade_no", outTradeNo);
        data.put("out_refund_no", outRefundNo);
        data.put("refund_fee", refundFee);
        data.put("notify_url", notifyUrl);
        try {
            Map<String, String> resp = wxpay.refund(data);
            return resp;
        } catch (Exception e) {
            log.error("微信退款查询失败. Method:{},订单号:{},退款单号:{}", "refund", outTradeNo,outRefundNo);
            e.printStackTrace();
        }
        return null;
    }

    public static String getWxAppId(String orderType){
        String tpAppId = VariableConstants.STRING_CONSTANT_1.equals(orderType)||VariableConstants.STRING_CONSTANT_2.equals(orderType)||VariableConstants.STRING_CONSTANT_3.equals(orderType)?
                IcbcParameter.hotelAppId:
                VariableConstants.STRING_CONSTANT_5.equals(orderType)?IcbcParameter.distributionAppId:
                        VariableConstants.STRING_CONSTANT_4.equals(orderType)?IcbcParameter.mallAppId:null;
       return tpAppId;

    }



    public static void main(String arg[]) {
//        Map<String, String> data = new HashMap<String, String>();
//        data.put("body", "测试微信支付");
//        data.put("out_trade_no", "test2020090910595900000012");
//        data.put("device_info", "WEB");
//        data.put("fee_type", "CNY");
//        data.put("total_fee", "1");
//        data.put("spbill_create_ip", "58.17.241.195");
//        data.put("notify_url", "http://www.example.com/wxpay/notify");
//        data.put("trade_type", "NATIVE");  // 此处指定为扫码支付
//        data.put("product_id", "12");
//        data.put("openid","oTZW-4jVzZ3GnvfNtbwv8TPhI5K8");
        // 测试下单接口
       createMiniProgramTradePay(1,"2","测试微信扫码支付","test2020090910595900120012","1","58.17.241.195","oTZW-4jVzZ3GnvfNtbwv8TPhI5K8");
       // 测试查询接口
        orderQueryState("3","1249895377172303872");
    }


}

;