第三节 SpringBoot实现支付宝当面付

亮子 2022-12-19 12:29:23 10658 0 0 0

1、添加依赖

<dependency>
    <groupId>com.alipay.sdk</groupId>
    <artifactId>alipay-sdk-java</artifactId>
    <version>4.10.97.ALL</version>
</dependency>

2、

package com.shenmazong.shenmablogserver.controller;

import com.alibaba.fastjson2.JSONObject;
import com.alibaba.fastjson2.JSON;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradePrecreateModel;
import com.alipay.api.request.AlipayTradePrecreateRequest;
import com.alipay.api.response.AlipayTradePrecreateResponse;
import com.shenmazong.shenmablogserver.entity.TbOrder;
import com.shenmazong.shenmablogserver.enums.PayTypeEnum;
import com.shenmazong.shenmablogserver.pay.PostOrderVo;
import com.shenmazong.shenmablogserver.pay.WeixinPayUtil;
import com.shenmazong.shenmablogserver.service.TbOrderService;
import com.shenmazong.shenmablogserver.utils.IdWorker;
import com.shenmazong.shenmablogserver.utils.ResponseResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Enumeration;
import java.util.Map;

/**
 * @author 军哥
 * @version 1.0
 * @description: AliPayController
 * @date 2022/12/22 10:32
 */

@RestController
@Slf4j
@CrossOrigin
@RequestMapping(value = "/alipay")
public class AliPayController {

    /**支付宝请求地址*/
    private static String aliUrl = "https://openapi.alipaydev.com/gateway.do";
    /**支付宝应用ID*/
    private static String aliAppId = "2016102300745509";
    /**本地通过"支付宝开放平台开发助手"生成的私钥*/
    private static String aliAppPrivateKey = "";
    /**支付宝应用设置本地公钥后生成对应的支付宝公钥(非本地生成的公钥)*/
    private static String alipayPublicKey = "";
    /**支付宝回调的接口地址*/
    private static String aliNotifyUrl = "https://www.shenmazong.com/alipay/aliNotify";


    @Autowired
    TbOrderService tbOrderService;

    @GetMapping(value = "/getOrderNo")
    public ResponseResult getOrderNo() {
        String orderNo = WeixinPayUtil.getInstance().getOrderNo();
        return ResponseResult.SUCCESS(orderNo);
    }

    @GetMapping(value = "/getOrderInfo")
    public ResponseResult getOrderInfo(@RequestParam("orderNo") Long orderNo) {
        return tbOrderService.getOrderInfo(orderNo);
    }

    /**
     * 返回支付的二维码字符串
     * @param postOrderVo
     * @return
     * @throws IOException
     */

    @PostMapping(value = "/postOrderObj")
    @Transactional
    public ResponseResult postOrderObj(@RequestBody PostOrderVo postOrderVo) throws Exception {
        log.info("开始调用支付宝生成支付二维码字符串...");
        //实例化客户端
        AlipayClient alipayClient = new DefaultAlipayClient(aliUrl, aliAppId, aliAppPrivateKey, "json", "utf-8", alipayPublicKey, "RSA2");
        //设置请求参数
        AlipayTradePrecreateRequest request = new AlipayTradePrecreateRequest();
        AlipayTradePrecreateModel model = new AlipayTradePrecreateModel();
        model.setOutTradeNo(postOrderVo.getOutTradeNo());
        model.setTotalAmount(""+postOrderVo.getAmount());
        model.setSubject(postOrderVo.getDescription());
        //如果没有店铺号可不设置
        model.setStoreId("9527");
        model.setQrCodeTimeoutExpress("10m");
        request.setBizModel(model);
        //支付宝异步通知地址
        request.setNotifyUrl(aliNotifyUrl);
        log.info("创建支付宝订单,请求参数:{} ", JSON.toJSONString(request));
        //调用接口
        AlipayTradePrecreateResponse response = alipayClient.execute(request);

        log.info("创建支付宝订单,返回值:{} ", JSON.toJSONString(response));
        if (!response.isSuccess()) {
            throw new Exception("创建订单失败");
        }

        String body = response.getBody();
        log.info(body);

        log.info("交易订单号outTradeNo:{} ", response.getOutTradeNo());
        log.info("支付二维码qrCode:{} ", response.getQrCode());

        //--3 生成订单
        TbOrder tbOrder = new TbOrder();
        tbOrder.setOrderId(IdWorker.getId());
        tbOrder.setOrderNo(Long.valueOf(postOrderVo.getOutTradeNo()));
        tbOrder.setOrderAmount(postOrderVo.getAmount());
        tbOrder.setDescription(postOrderVo.getDescription());
        tbOrder.setAttach(postOrderVo.getAttach());
        tbOrder.setPayType(PayTypeEnum.ALIPAY.getCode());

        tbOrderService.add(tbOrder);

        return ResponseResult.SUCCESS(response.getQrCode());
    }

//    gmt_create:2022-12-26 21:27:31
//    charset:utf-8
//    seller_email:nojasu2528@sandbox.com
//    subject:david-pay2
//    sign:Bh8hT5NCSIHZ5tWImjz14iYKfm2ynhdwyCKeAJtD2he1cbWKo+2OhvmTVtUMuGpkuEuRSs7+jCmEXU1XkUA/tuA1/QZpgaVbBiQT5rH7ONtTOuSAnJ+P6HkbyLdwl7ktQzXxd6NosYfPPi96UptIhryB4PHObnlykliqNYgBdbmAa8DxH9KfYOSi/gLJ7rX35SGSJhkWThOLJstssSUxN4tqZwH6cwfBoUJSWZkidTKO2i1Vn/kcUIyRkd29piRs+YsesA+sj83lRAEiyF6a/IpP7wab/AefrB1C17RxBba8600k/7fdpMF6TlE+IXNYSTDSQRJXIETAuaBqZQET8A==
//    buyer_id:2088102181012659
//    invoice_amount:1.00
//    notify_id:2022122600222212817012651006037834
//    fund_bill_list:[{"amount":"1.00","fundChannel":"ALIPAYACCOUNT"}]
//    notify_type:trade_status_sync
//    trade_status:TRADE_SUCCESS
//    receipt_amount:1.00
//    buyer_pay_amount:1.00
//    app_id:2016102300745509
//    sign_type:RSA2
//    seller_id:2088102180775782
//    gmt_payment:2022-12-26 21:28:15
//    notify_time:2022-12-26 21:28:19
//    version:1.0
//    out_trade_no:202212262126330001
//    total_amount:1.00
//    trade_no:2022122622001412651000186490
//    auth_app_id:2016102300745509
//    buyer_logon_id:aoa***@sandbox.com
//    point_amount:0.00


    @RequestMapping(value = "/aliNotify")
    public void aliNotify(HttpServletRequest request) throws Exception {
        log.info("aliNotify================================================");

        // 打印所有参数
        Enumeration<String> parameterNames = request.getParameterNames();
        while(parameterNames.hasMoreElements()) {
            String name = parameterNames.nextElement();
            String value = request.getParameter(name);
            System.out.println(name+":"+value);
        }

        // out_trade_no:202212262111140001
        String outTradeNo = request.getParameter("out_trade_no");
        // total_amount:1.00
        String totalAmount = request.getParameter("total_amount");
        // trade_no:2022122622001412651000184836
        String tradeNo = request.getParameter("trade_no");
        // app_id:2016102300745509
        String appId = request.getParameter("app_id");
        // buyer_pay_amount:1.00
        String buyerPayAmount = request.getParameter("buyer_pay_amount");

        // 修改订单状态
        if(outTradeNo != null) {
            tbOrderService.changeOrderPayStatus(outTradeNo);
        }

        log.info("aliNotify================================================");
    }

}