All Downloads are FREE. Search and download functionalities are using the official Maven repository.

io.gitee.putaoo.easypay.handler.AlipayHandler Maven / Gradle / Ivy

package io.gitee.putaoo.easypay.handler;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.domain.AlipayTradeAppPayModel;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.*;
import com.alipay.api.response.*;
import io.gitee.putaoo.easypay.config.AlipayProperties;
import io.gitee.putaoo.easypay.constant.PayChannel;
import io.gitee.putaoo.easypay.constant.RefundStatus;
import io.gitee.putaoo.easypay.constant.TradeStatus;
import io.gitee.putaoo.easypay.domain.*;
import io.gitee.putaoo.easypay.exception.PayException;
import io.gitee.putaoo.easypay.util.AmountUtil;
import io.gitee.putaoo.easypay.util.DateUtil;
import io.gitee.putaoo.easypay.util.JsonUtils;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

@Slf4j
public class AlipayHandler implements PayHandler{

    private final AlipayClient alipayClient;
    private final AlipayClient sandboxAlipayClient;
    private final AlipayProperties alipayProperties;

    public AlipayHandler(AlipayClient alipayClient, AlipayClient sandboxAlipayClient,AlipayProperties alipayProperties) {
        this.alipayClient = alipayClient;
        this.sandboxAlipayClient = sandboxAlipayClient;
        this.alipayProperties = alipayProperties;
    }

    @Override
    public PayChannel payChannel() {
        return PayChannel.ALIPAY;
    }

    @Override
    public AppPayResponse create4app(AppPayRequest request) {
        AlipayTradeAppPayRequest aliPayRequest = new AlipayTradeAppPayRequest();

        JSONObject bizContent = new JSONObject();
        bizContent.put("out_trade_no", request.getOrderNo());
        bizContent.put("total_amount", AmountUtil.fenToYuan(request.getOrderAmount()));
        bizContent.put("subject", request.getSubject());
        bizContent.put("product_code", "QUICK_MSECURITY_PAY");
        bizContent.put("time_expire", DateUtil.yyyyMMddHHmmss(request.getTimeExpire()));

        //// 商品明细信息,按需传入
        JSONArray goodsDetail = new JSONArray();
        JSONObject goods1 = new JSONObject();
        goods1.put("goods_subject", request.getSubject());
        goods1.put("goods_describe", request.getDescribe());
        //goods1.put("quantity", 1);
        //goods1.put("price", 0.01);
        goodsDetail.add(goods1);
        bizContent.put("goods_detail", goodsDetail);

        aliPayRequest.setNotifyUrl(alipayProperties.getNotifyUrl());
        //aliPayRequest.setReturnUrl(alipayProperties.getReturnUrl());

        aliPayRequest.setBizContent(bizContent.toString());

        try {
            //这里和普通的接口调用不同,使用的是sdkExecute
            AlipayTradeAppPayResponse aliResponse;

            if (request.isSandbox()){
                aliResponse = sandboxAlipayClient.sdkExecute(aliPayRequest);
            }else {
                aliResponse = alipayClient.pageExecute(aliPayRequest);
            }

            //response.getBody() 就是orderString 可以直接给客户端请求,无需再做处理

            AppPayResponse appPayResponse = new AppPayResponse();
            appPayResponse.setAliPayStr(aliResponse.getBody());

            return appPayResponse;
        } catch (AlipayApiException e) {
            e.printStackTrace();
            throw new PayException("调用支付宝支付失败");
        }
    }

    @Override
    public FindOrderResponse find(FindOrderRequest request) {
        AlipayTradeQueryRequest aliQueryRequest = new AlipayTradeQueryRequest();

        JSONObject bizContent = new JSONObject();
        bizContent.put("out_trade_no", request.getOrderNo());
        bizContent.put("trade_no", request.getOutOrderNo());
        aliQueryRequest.setBizContent(bizContent.toString());

        try {
            //这里和普通的接口调用不同,使用的是sdkExecute
            AlipayTradeQueryResponse aliResponse;

            if (request.isSandbox()){
                aliResponse = sandboxAlipayClient.execute(aliQueryRequest);
            }else {
                aliResponse = alipayClient.execute(aliQueryRequest);
            }

            if (!aliResponse.isSuccess()){
                throw new PayException("调用支付宝查询交易失败");
            }

            FindOrderResponse findOrderResponse = new FindOrderResponse();
            findOrderResponse.setOrderNo(aliResponse.getOutTradeNo());
            findOrderResponse.setOutOrderNo(aliResponse.getTradeNo());
            findOrderResponse.setBuyerId(aliResponse.getBuyerUserId());
            findOrderResponse.setBuyerLogonId(aliResponse.getBuyerLogonId());
            findOrderResponse.setBuyerName(aliResponse.getBuyerUserName());
            findOrderResponse.setTradeStatus(TradeStatus.fromAli(aliResponse.getTradeStatus()));
            findOrderResponse.setOrderAmount(AmountUtil.yuanToFen(aliResponse.getTotalAmount()));
            findOrderResponse.setFinishTime(aliResponse.getSendPayDate().getTime());

            return findOrderResponse;
        } catch (AlipayApiException e) {
            e.printStackTrace();
            throw new PayException("调用支付宝查询交易失败");
        }
    }

    @Override
    public CloseOrderResponse close(CloseOrderRequest request) {
        AlipayTradeCloseRequest closeRequest = new AlipayTradeCloseRequest();
        JSONObject bizContent = new JSONObject();
        bizContent.put("trade_no", request.getOutOrderNo());
        bizContent.put("out_trade_no", request.getOrderNo());
        closeRequest.setBizContent(bizContent.toString());

        AlipayTradeCloseResponse response;

        try {
            if (request.isSandbox()){
                response = sandboxAlipayClient.execute(closeRequest);
            }else {
                response = alipayClient.execute(closeRequest);
            }
        }catch (AlipayApiException e){
            e.printStackTrace();
            throw new PayException("支付宝关闭订单失败");
        }

        CloseOrderResponse closeOrderResponse = new CloseOrderResponse();
        closeOrderResponse.setOrderNo(response.getOutTradeNo());
        closeOrderResponse.setOutOrderNo(response.getTradeNo());

        return closeOrderResponse;
    }

    @Override
    public RefundResponse refund(RefundRequest request) {
        AlipayTradeRefundRequest alipayTradeRefundRequest = new AlipayTradeRefundRequest();
        JSONObject bizContent = new JSONObject();
        bizContent.put("trade_no", request.getOutOrderNo());
        bizContent.put("out_trade_no", request.getOrderNo());
        bizContent.put("refund_amount", AmountUtil.fenToYuan(request.getRefundAmount()));
        bizContent.put("refund_reason",request.getRefundReason());
        bizContent.put("out_request_no",request.getRefundNo());

        alipayTradeRefundRequest.setBizContent(bizContent.toString());

        AlipayTradeRefundResponse response;

        try {
            if (request.isSandbox()){
                response = sandboxAlipayClient.execute(alipayTradeRefundRequest);
            }else {
                response = alipayClient.execute(alipayTradeRefundRequest);
            }
        }catch (AlipayApiException e){
            e.printStackTrace();
            throw new PayException("支付宝发起退款失败");
        }

        RefundResponse refundResponse = new RefundResponse();
        refundResponse.setOutOrderNo(response.getTradeNo());
        refundResponse.setOrderNo(response.getOutTradeNo());
        refundResponse.setRefundAmount(AmountUtil.yuanToFen(response.getRefundFee()));
        refundResponse.setBuyerLogonId(response.getBuyerLogonId());

        return refundResponse;
    }

    @Override
    public FindRefundResponse findRefund(FindRefundRequest request) {
        AlipayTradeFastpayRefundQueryRequest refundQueryRequest = new AlipayTradeFastpayRefundQueryRequest();
        JSONObject bizContent = new JSONObject();
        bizContent.put("trade_no", request.getOutOrderNo());
        bizContent.put("out_trade_no", request.getOrderNo());
        bizContent.put("out_request_no", request.getRefundNo());

        refundQueryRequest.setBizContent(bizContent.toString());


        AlipayTradeFastpayRefundQueryResponse response;

        try {
            if (request.isSandbox()){
                response = sandboxAlipayClient.execute(refundQueryRequest);
            }else {
                response = alipayClient.execute(refundQueryRequest);
            }
        }catch (AlipayApiException e){
            e.printStackTrace();
            throw new PayException("支付宝查询退款订单失败");
        }

        FindRefundResponse refundResponse = new FindRefundResponse();
        refundResponse.setOrderNo(response.getOutTradeNo());
        refundResponse.setOutOrderNo(response.getTradeNo());
        refundResponse.setRefundNo(response.getOutRequestNo());
        refundResponse.setOrderAmount(AmountUtil.yuanToFen(response.getTotalAmount()));
        refundResponse.setRefundAmount(AmountUtil.yuanToFen(response.getRefundAmount()));
        refundResponse.setRefundReason(response.getRefundReason());
        refundResponse.setRefundStatus(RefundStatus.fromAli(response.getRefundStatus()));

        return refundResponse;
    }

    @Override
    public CallbackResponse callback(HttpServletRequest request) {
        //获取支付宝POST过来反馈信息
        Map< String , String > params = new HashMap< String , String >();
        Map requestParams = request.getParameterMap();

        for(Iterator iter  = requestParams.keySet().iterator(); iter.hasNext();){
            String name = (String)iter.next();
            String[] values = (String [])requestParams.get(name);
            String valueStr = "";
            for(int i = 0;i < values.length;i ++ ){
                valueStr =  (i==values.length-1)?valueStr + values [i]:valueStr + values[i] + ",";
            }
            //乱码解决,这段代码在出现乱码时使用。
            //valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put (name,valueStr);
        }

        try {
            //切记alipaypublickey是支付宝的公钥,请去open.alipay.com对应应用下查看。
            //boolean AlipaySignature.rsaCheckV1(Map params, String publicKey, String charset, String sign_type)
            boolean flag = AlipaySignature.rsaCheckV1 (params,alipayProperties.getPublicKey(), "UTF-8","RSA2");

            if (!flag){
                throw new PayException("支付宝回调通知验签失败");
            }
        }catch (AlipayApiException e){
            e.printStackTrace();
            throw new PayException("支付宝回调通知验签失败");
        }

        CallbackResponse response = new CallbackResponse();
        response.setPayChannel(PayChannel.ALIPAY);
        response.setThirdTradeNo(params.get("trade_no"));
        response.setTradeNo(params.get("out_trade_no"));
        response.setRefundNo(params.get("out_biz_no"));
        response.setAmount(AmountUtil.yuanToFen(params.get("total_amount")));
        response.setRefundAmount(AmountUtil.yuanToFen(params.get("refund_fee")));
        response.setNotifyTime(DateUtil.yyyyMMddHHmmss(params.get("notify_time")));
        response.setBuyerId(params.get("buyer_id"));
        response.setBuyerLogonId(params.get("buyer_logon_id"));
        response.setSubject(params.get("subject"));
        response.setDescribe(params.get("body"));
        response.setContent(params.get("passback_params"));
        response.setTradePaymentTime(params.get("gmt_payment"));
        response.setTradeStatus(TradeStatus.fromAli(params.get("trade_status")));

        return response;
    }
}





© 2015 - 2024 Weber Informatics LLC | Privacy Policy