微信公衆號支付--2--統一下單

調用統一下單api之前,需要先獲取openid,請先查看https://blog.csdn.net/hjfcgt123/article/details/104172909這篇博文。

一、配置JSAPI支付授權目錄

登錄企業公衆號關聯的商戶平臺https://pay.weixin.qq.com/index.php/core/info,產品中心--開發配置--支付配置--JSAPI支付--支付授權目錄,配置如下

JSAPI支付在請求支付的時候會校驗請求來源是否有在商戶平臺做了配置,所以必須確保支付目錄已經正確的被配置,否則將驗證失敗,請求支付不成功。

二、引入依賴

這裏使用一個新的sdk包

github地址:https://github.com/Pay-Group/best-pay-sdk

碼雲地址:https://gitee.com/liaoshixiong/best-pay-sdk 

maven依賴

<dependency>
    <groupId>cn.springboot</groupId>
    <artifactId>best-pay-sdk</artifactId>
    <version>1.1.0</version>
</dependency>

三、主要調用api

創建預支付訂單:com.lly835.bestpay.service.impl.BestPayServiceImpl.pay(PayRequest request)

四、代碼實現

1、添加配置文件

在application.yml文件中添加配置

wechat:
  #公衆號appId
  mpAppId: xxxxxx
  #公衆號appSecret
  mpAppSecret: xxxxxx
  #商戶號
  mchId: xxxxxx
  #商戶祕鑰
  mchKey: xxxxxx
  #商戶API證書下載之後放置在服務器上的地址(退款的時候需要驗證證書)
  keyPath: D:\\h5.p12
  #異步接收微信支付結果通知的回調地址,通知url必須爲外網可訪問的url,不能攜帶參數
  notifyUrl: http://hungteshun.viphk.ngrok.org/sell/pay/notify

2、將配置文件寫入對象

@Data
@Component
@ConfigurationProperties(prefix = "wechat")
public class WechatAccountConfig {

    private String mpAppId;
    private String mpAppSecret;
    /**
     * 商戶id
     */
    private String mchId;
    /**
     * 商戶祕鑰
     */
    private String mchKey;
    /**
     * 商戶證書路徑
     */
    private String keyPath;
    /**
     * 微信支付異步通知地址
     */
    private String notifyUrl;
}

3、構建com.lly835.bestpay.service.impl.BestPayServiceImpl對象,並交由spring管理 

@Component
public class WechatPayConfig {

    @Autowired
    private WechatAccountConfig wechatAccountConfig;

    @Bean
    public BestPayServiceImpl bestPayService () {
        BestPayServiceImpl bestPayService = new BestPayServiceImpl();
        bestPayService.setWxPayH5Config(wxPayH5Config());
        return bestPayService;
    }

    @Bean
    public WxPayH5Config wxPayH5Config() {
        WxPayH5Config wxPayH5Config = new WxPayH5Config();
        wxPayH5Config.setAppId(wechatAccountConfig.getMpAppId());
        wxPayH5Config.setAppSecret(wechatAccountConfig.getMpAppSecret());
        wxPayH5Config.setMchId(wechatAccountConfig.getMchId());
        wxPayH5Config.setMchKey(wechatAccountConfig.getMchKey());
        wxPayH5Config.setKeyPath(wechatAccountConfig.getKeyPath());
        wxPayH5Config.setNotifyUrl(wechatAccountConfig.getNotifyUrl());
        return wxPayH5Config;
    }
}

4、controller

@Controller
@RequestMapping("/pay")
public class PayController {

    @Autowired
    private OrderService orderService;
    @Autowired
    private PayService payService;

    @GetMapping("/create")
    public ModelAndView create(@RequestParam("orderId") String orderId,
                               @RequestParam("returnUrl") String returnUrl,
                               Map<String, Object> map) {
        //1、查詢訂單
        OrderDTO orderDTO = orderService.findOne(orderId);
        if (ObjectUtils.isEmpty(orderDTO)) {
            throw new SellException(ResultEnum.ORDER_NOT_EXIST);
        }
        //2、發起微信支付
        PayResponse payResponse = payService.create(orderDTO);
        map.put("payResponse", payResponse);
        map.put("returnUrl", returnUrl);
        return new ModelAndView("pay/create", map);
    }
}

5、controller返回的視圖

使用的是freemarker模板,文件路徑:src\main\resources\templates\pay\create.ftl

<script>
    function onBridgeReady(){
        WeixinJSBridge.invoke(
            'getBrandWCPayRequest', {
                "appId":"${payResponse.appId}",     //公衆號名稱,由商戶傳入
                "timeStamp":"${payResponse.timeStamp}",         //時間戳,自1970年以來的秒數
                "nonceStr":"${payResponse.nonceStr}", //隨機串
                "package":"${payResponse.packAge}",
                "signType":"${payResponse.signType}",         //微信簽名方式:
                "paySign":"${payResponse.paySign}" //微信簽名
            },
            function(res){
                if(res.err_msg == "get_brand_wcpay_request:ok" ) {
                    location.href = "${returnUrl}";
                }     // 使用以上方式判斷前端返回,微信團隊鄭重提示:res.err_msg將在用戶支付成功後返回    ok,但並不保證它絕對可靠。
            }
        );
    }
    if (typeof WeixinJSBridge == "undefined"){
        if( document.addEventListener ){
            document.addEventListener('WeixinJSBridgeReady', onBridgeReady, false);
        }else if (document.attachEvent){
            document.attachEvent('WeixinJSBridgeReady', onBridgeReady);
            document.attachEvent('onWeixinJSBridgeReady', onBridgeReady);
        }
    }else{
        onBridgeReady();
    }
</script>

6、service實現類

@Service
@Slf4j
public class PayServiceImpl implements PayService {

    private static final String orderName = "微信點餐訂單";

    @Autowired
    private BestPayServiceImpl bestPayService;

    @Override
    public PayResponse create(OrderDTO orderDTO) {
        PayRequest payRequest = new PayRequest();
        payRequest.setOpenid(orderDTO.getBuyerOpenid());
        payRequest.setOrderId(orderDTO.getOrderId());
        payRequest.setOrderAmount(orderDTO.getOrderAmount().doubleValue());
        payRequest.setOrderName(orderName);
        payRequest.setPayTypeEnum(BestPayTypeEnum.WXPAY_H5);
        return bestPayService.pay(payRequest);
    }
	
}

四、前端調用

官網鏈接:https://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=7_7&index=6

前端調用方法

this.$http.post("/sell/buyer/order/create", {
                    'openid': getCookie('openid'),
                    'phone': this.phone,
                    'name': this.name,
                    'address': this.address,
                    'items': JSON.stringify(goods)}
                ).then((respones) => {
                    respones = respones.body;
                    if (respones.code == ERR_OK) {
                      location.href = config.wechatPayUrl +
                        '?openid=' + getCookie('openid') +
                        '&orderId=' + respones.data.orderId +
                        '&returnUrl=' + encodeURIComponent(config.sellUrl + '/#/order/' + respones.data.orderId);
                    }else {
                      alert(respones.msg);
                    }
                });

注意:WeixinJSBridge內置對象在其他瀏覽器中無效,所以需要在微信瀏覽器裏面打開H5網頁中執行JS調起支付。接口輸入輸出數據格式爲JSON。

其中config.wechatPayUrl 和 config.sellUrl地址爲

sellUrl: 'http://sell.com',
wechatPayUrl: 'http://hungteshun.viphk.ngrok.org/sell/pay/create'

思路是:請求生成預支付訂單之後跳轉到訂單詳情頁面。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章