springboot 支付宝支付(电脑网站)


springboot 支付宝支付(电脑支付)

应用:在电脑网页端使用支付宝支付

官方文档:https://opendocs.alipay.com/open/270

***************************

引入 jar 包

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

***************************

示例

******************

配置文件

application.yml

alipay:
  appid: 2016092500591327
  gatewayUrl: https://openapi.alipaydev.com/gateway.do
  format: JSON
  charset: utf-8
  signType: RSA2
  notifyUrl: http://localhost:8080/notify
  returnUrl: http://localhost:8080/return
  app-private-key: MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQCcF+Oc3uJEFt59LXB30LkP/Ocn6cMtxTeeqiM99tzGi3nyMao33jPYjwKvQk+djDb7i4bgJNVjx5QtEuJruMsiOMUO34QzYqnSZLLdA8Oltbf5LG/+qJMnF+K1dw9DWvw5dF6rbXvvqMpzruBJ99ntbWBK5hE/ayYODPhmcQ8rLV0nedYCb4nIhQueF3l6pFDG5e/eRyTj3Vb6faSf30DTKhMk4Yvj3Mx3f8h4eGGjFvvbSKdO8oI8HQYkEQh8k8pqkkQs3FSawp5KNAH13CNzGEnLewsOaHiEEwT1qSTc7ppewp7oyP2KtXw9TQySlkNFyLorqUHjF71hgCFmDEIxAgMBAAECggEACT5c60hDq/aSvGT5eQ7yNqEqazGrrkU0kv/OUHgTAOr3kMEiLGbLOTLW3NwXbOQFyYWsug9UV7FU9ApfQDPUS7WC7euMn6JjHiN6eB4l8uU8/NOF2lXPSQxgD5D6ZWm48AoVJR+5rCqZupoLjDXSQP4uKqFPOis1OLXJ6/8b/9l7L0jf2eW70Ht6HrNxfXTAn07FoJAEHnjePCgyYHuor9oD/0bi/0KRJkeQtqMZHX3oYhhYmQzIMTXIi9hMd+U6lmaknDFV8AMOfemX0Dq6KNYPwWP86YWelZ230xHXgE3Jk493unFZetliGG6vVyq4Whd5OTcXmE64+8GRKxO5QQKBgQDOwRR4KhyqbA7L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PlSKLgJwVYj560wzElBL+fvjR0V0OA+FWJryKluBtJYUKXBadFKuyVwNnyGqmHFxvtSHuErhOrg0YiYIfhV3f7zE5q1mIz7ecwH0W7nB7gtFjLt1k4WSpwyeEI8Xpl7SLMvHdwEXUwTU0h/V7TumYWgUe0ft70NTps+zPwJlmcEluHg0VSs7UrDVQIDAQAB

说明:app-private-key为应用私钥,alipay-public-key为支付宝公钥

******************

config 层

AlipayProperties

@Data
@Component
@ConfigurationProperties("alipay")
public class AlipayProperties {

    private String appId;
    private String gatewayUrl;
    private String format;
    private String charset;
    private String signType;
    private String appPrivateKey;
    private String alipayPublicKey;

    private String returnUrl;
    private String notifyUrl;
}

AlipayConfig:创建alipayClient客户端

@Configuration
public class AlipayConfig {

    @Resource
    private AlipayProperties alipayProperties;

    @Bean
    public AlipayClient initAlipayClient(){
        return new DefaultAlipayClient(alipayProperties.getGatewayUrl(),
                alipayProperties.getAppId(),alipayProperties.getAppPrivateKey(),
                alipayProperties.getFormat(),alipayProperties.getCharset(),
                alipayProperties.getAlipayPublicKey(),alipayProperties.getSignType());
    }
}

******************

controller 层

AlipayController

@RestController
public class AlipayController {

    @Resource
    private AlipayClient alipayClient;

    @Resource
    private AlipayProperties alipayProperties;

    @RequestMapping("/pay")
    public String pagePay(){
        AlipayTradePagePayModel model=new AlipayTradePagePayModel();
        model.setOutTradeNo("3000");       //商户订单号
        model.setProductCode("FAST_INSTANT_TRADE_PAY");  //电脑网站支付销售产品码,不同的支付方式productCode不同
        model.setSubject("海贼王");         //订单标题
        model.setTotalAmount("100");        //订单总金额
        model.setTimeoutExpress("1h");     //支付超市时间,1h后关闭

        AlipayTradePagePayRequest request=new AlipayTradePagePayRequest();
        request.setBizModel(model);
        request.setReturnUrl(alipayProperties.getReturnUrl());   //支付成功后同步返回的url地址
        request.setNotifyUrl(alipayProperties.getNotifyUrl());   //trade_success、trade_closed触发

        AlipayTradePagePayResponse response= alipayClient.pageExecute(request);
        
        return response.getBody();
    }

    @RequestMapping("/query")
    public String query() throws Exception{
        AlipayTradeQueryModel model=new AlipayTradeQueryModel();
        model.setOutTradeNo("3000");

        AlipayTradeQueryRequest request=new AlipayTradeQueryRequest();
        request.setBizModel(model);

        return alipayClient.execute(request).getTradeStatus();
    }

    @RequestMapping("/close")
    public String close() throws Exception{
        AlipayTradeCloseModel model=new AlipayTradeCloseModel();
        model.setOutTradeNo("3000");

        AlipayTradeCloseRequest request=new AlipayTradeCloseRequest();
        request.setBizModel(model);

        return alipayClient.execute(request).getBody();
    }

    @RequestMapping("/refund")
    public String refund() throws Exception{
        AlipayTradeRefundModel model=new AlipayTradeRefundModel();
        model.setOutTradeNo("3000");
        model.setRefundAmount("20");
        model.setOutRequestNo("100");  //分批次退款时,对应的每一次退款请求号,同一订单该值不能相同

        AlipayTradeRefundRequest refundRequest=new AlipayTradeRefundRequest();
        refundRequest.setBizModel(model);

        AlipayTradeRefundResponse refundResponse=alipayClient.execute(refundRequest);

        return "退款总金额:"+refundResponse.getRefundFee();
    }

    @RequestMapping("/refundQuery")
    public String refundQuery() throws Exception{
        AlipayTradeFastpayRefundQueryModel model=new AlipayTradeFastpayRefundQueryModel();
        model.setOutTradeNo("3000");     //商户订单号
        model.setOutRequestNo("100");    //退款请求号

        AlipayTradeFastpayRefundQueryRequest refundQueryRequest=new AlipayTradeFastpayRefundQueryRequest();
        refundQueryRequest.setBizModel(model);

        AlipayTradeFastpayRefundQueryResponse refundQueryResponse=alipayClient.execute(refundQueryRequest);

        return "本次退款金额为:"+refundQueryResponse.getRefundAmount()+
                "\n订单总金额为:"+refundQueryResponse.getTotalAmount();
    }

    @RequestMapping("/queryDownload")
    public String downloadUrl() throws Exception{    //对账单下载地址
        AlipayDataDataserviceBillDownloadurlQueryModel model=new AlipayDataDataserviceBillDownloadurlQueryModel();
        model.setBillType("trade");
        model.setBillDate("2020-04-06");

        AlipayDataDataserviceBillDownloadurlQueryRequest request=new AlipayDataDataserviceBillDownloadurlQueryRequest();
        request.setBizModel(model);

        AlipayDataDataserviceBillDownloadurlQueryResponse response=alipayClient.execute(request);

        return response.getBillDownloadUrl();
    }

    @RequestMapping("/notify")
    public void notify(HttpServletRequest request) throws Exception{  //异步通知接口
        if (check(request.getParameterMap())){
            System.out.println("异步通知");
        }else {
            System.out.println("验签失败");
        }
    }

    @RequestMapping("/return")
    public String returnUrl(HttpServletRequest request) throws Exception{ //同步跳转接口
        if (check(request.getParameterMap())){
            return "success";
        }else {
            return "false";
        }
    }

    private boolean check(Map<String,String[]> requestParams) throws Exception{
        Map<String,String> params = new HashMap<>();

        for (String name : requestParams.keySet()) {
            String[] values = requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }

            params.put(name, valueStr);
        }

        return AlipaySignature.rsaCheckV1(params, alipayProperties.getAlipayPublicKey(),
                alipayProperties.getCharset(), alipayProperties.getSignType()); //调用SDK验证签名
    }
}

说明:notify接口只在trade_success状态下调用,

notify调用:支付成功后、部分退款成功后,支付状态为trade_success

notify不调用:全部退款、多次部分退款将余额全退,支付状态变为trade_closed

发布了387 篇原创文章 · 获赞 98 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/weixin_43931625/article/details/105356707