苹果内购、支付宝微信app支付H5支付、退款

  • Post author:
  • Post category:其他



/**
 * @author: tjr
 * @Date: 2021/4/20 15:11
 * @Description: 支付接口
 */
@Slf4j
@RestController
@RequestMapping(value = "/pay")
@Api(value = "支付", tags = "支付模块")
public class PayController {
    private final AliPayService aliPayService;
    private final WxPayService wxPayService;
    private final CacheService cacheService;
    private final IosPayService iosPayService;
    private final DistributedLocker distributedLocker;


    private final static String SUCCESS = "SUCCESS";

    private final static String FAIL = "FAIL";

    private final static String key = "pay:";

    private final static Long lastTime = 5 * 60L;

    private final static String CHECK_MWEB_URL = "https://wx.tenpay.com/cgi-bin/mmpayweb-bin/checkmweb?";

    public PayController(AliPayService aliPayService, WxPayService wxPayService, CacheService cacheService, IosPayService iosPayService, DistributedLocker distributedLocker) {
        this.aliPayService = aliPayService;
        this.wxPayService = wxPayService;
        this.cacheService = cacheService;
        this.iosPayService = iosPayService;
        this.distributedLocker = distributedLocker;
    }


    @ApiOperation(value = "苹果内购支付接口")
    @PostMapping("/iosPay")
    public boolean iosInAppPurchase(@RequestBody @Valid IosPayEntity iosPayEntity) {
        String key = "IosPay:" + WebUtils.getAppUserId();
        Lock lock = distributedLocker.getLock(key);

        boolean result = false;
        boolean hasLock = lock.tryLock();
        if (hasLock) {
            try {
                // 先清除缓存,再查
                JpaUtils.clear();
                result = iosPayService.buyAccountDetails(iosPayEntity);
            } catch (Exception e) {
                log.error("苹果内购支付失败" + e);
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        }
        return result;
    }

    @ApiOperation(value = "统一H5支付接口")
    @PostMapping("/h5Pay")
    public AliPayEntityVo h5Pay(@RequestBody AliWxPayEntity entity) throws AlipayApiException {
        if (entity.getMoney() == null || entity.getChannel() == null) {
            throw BaseException.of(2000, "请输入参数");
        }
        if (entity.getChannel() == OrderConstants.PAY_CHANNEL_WX) {
            WxPayEntity wxPayEntity = new WxPayEntity();
            String ip = WebUtils.getIp();
            BigDecimal bigDecimal = new BigDecimal(entity.getMoney());
            int i = bigDecimal.multiply(new BigDecimal(100)).intValue();
            wxPayEntity.setTotalMoney(String.valueOf(i));
            wxPayEntity.setOrderId(entity.getOrderId());
            wxPayEntity.setIp(ip);
            wxPayEntity.setBody(entity.getBody());
            //微信支付
            ResultMap resultMap = wxPayService.h5Pay(wxPayEntity);
            AliPayEntityVo payEntity = new AliPayEntityVo();
            payEntity.setOrderId(entity.getOrderId());
            Map<String, String> data = (Map<String, String>) resultMap.get("data");
            log.info("wei xin pay info : {}", data);
            String wxString = CHECK_MWEB_URL + "prepay_id=" + data.get("prepayid") + "&package=" + data.get("package");
            cacheService.set(key + payEntity.getOrderId(), wxString, lastTime);
            return payEntity;
        }

        if (entity.getChannel() == OrderConstants.PAY_CHANNEL_ZFB) {
            //发起支付,支付宝
            //获取支付
            AlipayTradeWapPayResponse response = aliPayService.h5Pay(entity);
            if (response.isSuccess()) {
                log.debug("调用成功" + response.getBody());
                AliPayEntityVo payEntity = new AliPayEntityVo();
                payEntity.setOrderId(entity.getOrderId());
                cacheService.set(key + payEntity.getOrderId(), response.getBody(), lastTime);
                return payEntity;
            } else {
                log.error("调用失败" + response.getBody());
                throw BaseException.of(2000, response.getBody());
            }
        }

        throw BaseException.of(2000, "下单失败");
    }


    @ApiOperation(value = "统一app支付接口")
    @PostMapping("/appPay")
    public ApiResponse<PayEntity> appPay(@RequestBody AliWxPayEntity entity) {
        ApiResponse<PayEntity> apiResponse = new ApiResponse<>();
        if (entity.getMoney() == null || entity.getChannel() == null
                || entity.getOrderId() == null) {
            throw BaseException.of(2000, "请输入参数");
        }
        if (entity.getChannel() == OrderConstants.PAY_CHANNEL_ZFB) {
            //发起支付,支付宝
            //获取支付
            AlipayTradeAppPayResponse response = aliPayService.tradeAppPay(entity);
            if (response.isSuccess()) {
                log.debug("调用成功" + response.getBody());
                PayEntity payEntity = new PayEntity();
                payEntity.setOrderId(String.valueOf(entity.getOrderId()));
                payEntity.setPay(response.getBody());
                if (ObjectUtils.isEmpty(response.getBody())) {
                    apiResponse.setCode(500);
                    apiResponse.setMessage("支付宝下单失败!");
                }
                apiResponse.setData(payEntity);
                return apiResponse;
            } else {
                log.error("调用失败" + response.getBody());
                throw BaseException.of(2000, response.getBody());
            }
        }
        if (entity.getChannel() == OrderConstants.PAY_CHANNEL_WX) {
            WxPayEntity wxPayEntity = new WxPayEntity();
            String ip = WebUtils.getIp();
            BigDecimal bigDecimal = new BigDecimal(entity.getMoney());
            int i = bigDecimal.multiply(new BigDecimal(100)).intValue();
            wxPayEntity.setTotalMoney(String.valueOf(i));
            wxPayEntity.setOrderId(entity.getOrderId());
            wxPayEntity.setIp(ip);
            wxPayEntity.setBody(entity.getBody());
            //微信支付
            ResultMap resultMap = wxPayService.unifiedOrder(wxPayEntity);
            PayEntity payEntity = new PayEntity();
            payEntity.setOrderId(entity.getOrderId());
            payEntity.setResultMap(resultMap);
            apiResponse.setData(payEntity);
            apiResponse.setCode(Integer.parseInt(resultMap.get("code").toString()));
            apiResponse.setMessage(resultMap.get("msg").toString());
            return apiResponse;
        }

        throw BaseException.of(2000, "下单失败");
    }

    @ApiOperation(value = "统一查询订单接口")
    @PostMapping("/queryPay")
    public QueryPayResult queryPay(@RequestBody QueryPayEntity entity) throws Exception {
        if (entity.getOrderId() == null || entity.getChannel() == null) {
            throw BaseException.of(2000, "请输入参数");
        }
        log.info("query pay : {}", entity);
        QueryPayResult payResult = new QueryPayResult();
        if (entity.getChannel() == OrderConstants.PAY_CHANNEL_WX) {
            //微信
            Map map = wxPayService.queryPay(entity);
            log.info("weixin : {}", map);
            String trade_state = map.get("result_code").toString();
            if (FAIL.equals(trade_state)) {
                return payResult;
            }
            if (SUCCESS.equals(map.get("trade_state").toString())) {
                payResult.setStatus(true);
            }
        } else if (entity.getChannel() == OrderConstants.PAY_CHANNEL_ZFB) {
            //支付宝
            AlipayResponse response = aliPayService.queryPay(entity);
            log.info("alipay : {}", response);
            if (response.isSuccess()) {
                payResult.setStatus(true);
            }
        }
        return payResult;
    }

    @ApiOperation(value = "统一H5查询串接口")
    @PostMapping("/queryOrderId")
    public String queryPay(@RequestBody AliPayEntityVo entity) {
        String s = cacheService.get(key + entity.getOrderId(), String.class);
        log.info(s + "====" + entity.getOrderId());
        if (StringUtils.isEmpty(s)) {
            throw BaseException.of(2000, "订单失效,请重新下单!");
        }
        return s;
    }


    @PostMapping("/refund")
    @ApiOperation(value = "支付宝退款", notes = "退款")
    public String refund(@RequestParam String orderNo, @RequestParam String amount) throws AlipayApiException {
        return aliPayService.refund(orderNo, amount);

    }

    @Autowired
    private WXPayConfig wxPayConfig;

    @ApiOperation(value = "微信退款", notes = "退款")
    @PostMapping("/wxRefund")
    public boolean wxRefund(@RequestParam String orderNo, @RequestParam String amount) throws Exception {

        Map<String, String> data = new HashMap<String, String>();
        System.err.println("进入微信退款申请");
        Date now = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");//可以方便地修改日期格式
        String hehe = dateFormat.format(now);
        int pay = (int) (Double.parseDouble(amount) * 100); //需要*100
        String out_refund_no = hehe + "wxrefund";
        //String transaction_id = "微信支付时生成的流水号";

        //String total_fee = "微信支付时支付的钱(单位为分)";

        data.put("out_refund_no", out_refund_no);
        data.put("out_trade_no", orderNo);
        data.put("total_fee", String.valueOf(pay));
        data.put("refund_fee", String.valueOf(pay));

        WXPay wxpay = new WXPay(wxPayConfig);
        data.put("appid", wxPayConfig.getAppID());
        data.put("mch_id", wxPayConfig.getMchID());
        data.put("nonce_str", WXPayUtil.generateNonceStr());
        data.put("sign", MD5Util.getSign(data));

        Map<String, String> resp = null;
        try {
            resp = wxpay.refund(data);
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.err.println("返回信息:\n" + resp);
        String return_code = resp.get("return_code");   //返回状态码
        String return_msg = resp.get("return_msg");     //返回信息

        String resultReturn = null;
        if ("SUCCESS".equals(return_code)) {
            String result_code = resp.get("result_code");       //业务结果
            String err_code_des = resp.get("err_code_des");     //错误代码描述
            if ("SUCCESS".equals(result_code)) {
                //表示退款申请接受成功,结果通过退款查询接口查询
                //修改用户订单状态为退款申请中(暂时未写)
                resultReturn = "退款申请成功";
                System.out.println(resultReturn);
                return true;
            } else {
                log.info("订单号:{}错误信息:{}", err_code_des);
                resultReturn = err_code_des;
                return false;
            }
        } else {
            log.info("订单号:{}错误信息:{}", return_msg);
            resultReturn = return_msg;
            return false;
        }
    }

}



版权声明:本文为weixin_43285931原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。