1. 程式人生 > >微信支付工具

微信支付工具

和支付相關的類

PayHelper

package com.leyou.order.utils;

import com.github.wxpay.sdk.WXPay;
import com.leyou.order.config.PayConfig;
import com.leyou.order.service.OrderService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author: 98050
 * @create: 2018-10-27 15:54
 **/
@Component
public class PayHelper {

    private WXPay wxPay;

    private static final Logger logger = LoggerFactory.getLogger(PayHelper.class);

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private OrderService orderService;

    public PayHelper(PayConfig payConfig) {
        // 真實開發時
        wxPay = new WXPay(payConfig);
        // 測試時
        // wxPay = new WXPay(payConfig, WXPayConstants.SignType.MD5, true);
    }

    public String createPayUrl(Long orderId) {
        String key = "leyou.pay.url." + orderId;
        try {
            String url = this.redisTemplate.opsForValue().get(key);
            if (StringUtils.isNotBlank(url)) {
                return url;
            }
        } catch (Exception e) {
            logger.error("查詢快取付款連結異常,訂單編號:{}", orderId, e);
        }

        try {
            Map<String, String> data = new HashMap<>();
            // 商品描述
            data.put("body", "樂優商城測試");
            // 訂單號
            data.put("out_trade_no", orderId.toString());
            //貨幣
            data.put("fee_type", "CNY");
            //金額,單位是分
            data.put("total_fee", "1");
            //呼叫微信支付的終端IP(estore商城的IP)
            data.put("spbill_create_ip", "127.0.0.1");
            //回撥地址
            data.put("notify_url", "http://test.leyou.com/wxpay/notify");
            // 交易型別為掃碼支付
            data.put("trade_type", "NATIVE");
            //商品id,使用假資料
            data.put("product_id", "1234567");

            Map<String, String> result = this.wxPay.unifiedOrder(data);

            if ("SUCCESS".equals(result.get("return_code"))) {
                String url = result.get("code_url");
                // 將付款地址快取,時間為10分鐘
                try {
                    this.redisTemplate.opsForValue().set(key, url, 10, TimeUnit.MINUTES);
                } catch (Exception e) {
                    logger.error("快取付款連結異常,訂單編號:{}", orderId, e);
                }
                return url;
            } else {
                logger.error("建立預交易訂單失敗,錯誤資訊:{}", result.get("return_msg"));
                return null;
            }
        } catch (Exception e) {
            logger.error("建立預交易訂單異常", e);
            return null;
        }
    }

    /**
     * 查詢訂單狀態
     *
     * @param orderId
     * @return
     */
    public PayState queryOrder(Long orderId) {
        Map<String, String> data = new HashMap<>();
        // 訂單號
        data.put("out_trade_no", orderId.toString());
        try {
            Map<String, String> result = this.wxPay.orderQuery(data);
            if (result == null) {
                // 未查詢到結果,認為是未付款
                return PayState.NOT_PAY;
            }
            String state = result.get("trade_state");
            if ("SUCCESS".equals(state)) {
                // success,則認為付款成功

                // 修改訂單狀態
                this.orderService.updateOrderStatus(orderId, 2);
                return PayState.SUCCESS;
            } else if (StringUtils.equals("USERPAYING", state) || StringUtils.equals("NOTPAY", state)) {
                // 未付款或正在付款,都認為是未付款
                return PayState.NOT_PAY;
            } else {
                // 其它狀態認為是付款失敗
                return PayState.FAIL;
            }
        } catch (Exception e) {
            logger.error("查詢訂單狀態異常", e);
            return PayState.NOT_PAY;
        }
    }
}

PayConfig

package com.leyou.order.config;

import com.github.wxpay.sdk.WXPayConfig;
import com.leyou.order.properties.PayProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Configuration;

import java.io.InputStream;

/**
 * @author: 98050
 * @create: 2018-10-27
 **/
@Configuration
@EnableConfigurationProperties(PayProperties.class)
public class PayConfig implements WXPayConfig {

    @Autowired
    private PayProperties payProperties;

    @Override
    public String getAppID() {
        return payProperties.getAppId();
    }

    @Override
    public String getMchID() {
        return payProperties.getMchId();
    }

    @Override
    public String getKey() {
        return payProperties.getKey();
    }

    @Override
    public InputStream getCertStream() {
        return null;
    }

    @Override
    public int getHttpConnectTimeoutMs() {
        return payProperties.getConnectTimeoutMs();
    }

    @Override
    public int getHttpReadTimeoutMs() {
        return payProperties.getReadTimeoutMs();
    }

}

PayProperties

package com.leyou.order.properties;

import org.springframework.boot.context.properties.ConfigurationProperties;

/**
 * @author: 98050
 * @create: 2018-10-27 11:38
 **/
@ConfigurationProperties(prefix = "leyou.pay")
public class PayProperties {

    /**
     * 公眾賬號ID
     */
    private String appId;

    /**
     * 商戶號
     */
    private String mchId;

    /**
     * 生成簽名的金鑰
     */
    private String key;

    /**
     * 連線超時時間
     */
    private int connectTimeoutMs;

    /**
     * 讀取超時時間
     */
    private int readTimeoutMs;

    public String getAppId() {
        return appId;
    }

    public void setAppId(String appId) {
        this.appId = appId;
    }

    public String getMchId() {
        return mchId;
    }

    public void setMchId(String mchId) {
        this.mchId = mchId;
    }

    public String getKey() {
        return key;
    }

    public void setKey(String key) {
        this.key = key;
    }

    public int getConnectTimeoutMs() {
        return connectTimeoutMs;
    }

    public void setConnectTimeoutMs(int connectTimeoutMs) {
        this.connectTimeoutMs = connectTimeoutMs;
    }

    public int getReadTimeoutMs() {
        return readTimeoutMs;
    }

    public void setReadTimeoutMs(int readTimeoutMs) {
        this.readTimeoutMs = readTimeoutMs;
    }
}

PayState

package com.leyou.order.utils;

/**
 * @author: HuYi.Zhang
 * @create: 2018-06-07 17:44
 **/
public enum PayState {
    /**
     * 未支付0
     * 支付成功1
     * 支付失敗2
     */
    NOT_PAY(0),SUCCESS(1),FAIL(2);

    PayState(int value) {
        this.value = value;
    }

    int value;

    public int getValue() {
        return value;
    }
}