package com.hys.app.pay.ali;

import com.hys.app.framework.exception.ServiceException;
import com.wechat.pay.java.core.Config;
import com.wechat.pay.java.core.RSAAutoCertificateConfig;
import com.wechat.pay.java.core.auth.WechatPay2Validator;
import com.wechat.pay.java.service.payments.h5.model.Amount;
import com.wechat.pay.java.service.payments.h5.H5Service;
import com.wechat.pay.java.service.payments.h5.model.PrepayRequest;
import com.wechat.pay.java.service.payments.h5.model.PrepayResponse;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
public class WxService {
    @Resource
    private WxConfig wxConfig;

    public PrepayResponse pay(PayOrder payOrder) {

        try {
            // 初始化SDK
            Config config = new RSAAutoCertificateConfig.Builder()
                    .merchantId(wxConfig.getMerchantId())
                    .privateKeyFromPath(wxConfig.getPrivateKeyPath())
                    .merchantSerialNumber(wxConfig.getMerchantSerialNumber())
                    .apiV3Key(wxConfig.getApiV3Key())
                    .build();
            // 构建service
            H5Service service = new H5Service.Builder().config(config).build();
            PrepayRequest request = new PrepayRequest();
            request.setAppid(wxConfig.getAppid());
            request.setMchid(wxConfig.getMerchantId());
            request.setOutTradeNo(payOrder.getTraceNo());
            request.setTimeExpire(payOrder.getTimeExpire().toString());
            Amount amount = new Amount();
            amount.setTotal(payOrder.getTotalAmount().intValue()*100);
            request.setAmount(amount);
            request.setDescription(payOrder.getSubject());
            return service.prepay(request);
        } catch (Exception e) {
            e.printStackTrace();
        }
        throw new ServiceException("拉起微信异常");
    }
}