公众号:架构师与哈苏
关注公众号进入it交流群! 公众号:架构师与哈苏 不定时都会推送一些实用的干货。。。

pom

<dependency>
    <groupId>com.alipay.sdk</groupId>
    <artifactId>alipay-easysdk</artifactId>
    <version>2.1.2</version>
</dependency>

yml

alipay:
  app-id: *****
  subject: ***
  # 应用私钥
  merchant-private-key: ***
  # 支付宝公钥
  alipay-public-key: ***
  # 支付宝异步通知地址
  notify-url: https://baidu.com

配置类

AlipayConfig.java

package com.meeno.zhengcaiyun.pay.config;

import com.alipay.easysdk.kernel.Config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class AlipayConfig {

    /**
     * appId
     */
    public static String appId;

    /**
     * 订单标题
     */
    public static String subject;

    /**
     * 应用私钥
     */
    public static String merchantPrivateKey;

    /**
     * 支付宝公钥
     */
    public static String alipayPublicKey;

    /**
     * 支付宝异步通知地址
     */
    public static String notifyUrl;

    @Value("${alipay.app-id}")
    public void setAppId(String appId) {
        AlipayConfig.appId = appId;
    }

    @Value("${alipay.subject}")
    public void setSubject(String subject) {
        AlipayConfig.subject = subject;
    }

    @Value("${alipay.merchant-private-key}")
    public void setMerchantPrivateKey(String merchantPrivateKey){
        AlipayConfig.merchantPrivateKey = merchantPrivateKey;
    }

    @Value("${alipay.alipay-public-key}")
    public void setAlipayPublicKey(String alipayPublicKey) {
        AlipayConfig.alipayPublicKey = alipayPublicKey;
    }

    @Value("${alipay.notify-url}")
    public void setNotifyUrl(String notifyUrl) {
        AlipayConfig.notifyUrl = notifyUrl;
    }

    /**
     * 获取配置参数
     * @return
     */
    public static Config getOptions() {
        Config config = new Config();
        config.protocol = "https";
        config.gatewayHost = "openapi.alipay.com";
        config.signType = "RSA2";

        config.appId = AlipayConfig.appId;

        // 为避免私钥随源码泄露,推荐从文件中读取私钥字符串而不是写入源码中
        //<-- 请填写您的应用私钥,例如:MIIEvQIBADANB ... ... -->
        config.merchantPrivateKey = AlipayConfig.merchantPrivateKey;

        //注:证书文件路径支持设置为文件系统中的路径或CLASS_PATH中的路径,优先从文件系统中加载,加载失败后会继续尝试从CLASS_PATH中加载
        //config.merchantCertPath = "<-- 请填写您的应用公钥证书文件路径,例如:/foo/appCertPublicKey_2019051064521003.crt -->";
        //config.alipayCertPath = "<-- 请填写您的支付宝公钥证书文件路径,例如:/foo/alipayCertPublicKey_RSA2.crt -->";
        //config.alipayRootCertPath = "<-- 请填写您的支付宝根证书文件路径,例如:/foo/alipayRootCert.crt -->";

        //注:如果采用非证书模式,则无需赋值上面的三个证书路径,改为赋值如下的支付宝公钥字符串即可
        //"<-- 请填写您的支付宝公钥,例如:MIIBIjANBg... -->"
        config.alipayPublicKey = AlipayConfig.alipayPublicKey;

        //可设置异步通知接收服务地址(可选)
        config.notifyUrl = AlipayConfig.notifyUrl;

        //可设置AES密钥,调用AES加解密相关接口时需要(可选)
        //config.encryptKey = "<-- 请填写您的AES密钥,例如:aa4BtZ4tspm2wnXLb1ThQA== -->";

        return config;
    }

}

serviceimpl

package com.meeno.zhengcaiyun.pay.service.impl;

import com.alipay.easysdk.factory.Factory;
import com.alipay.easysdk.kernel.util.ResponseChecker;
import com.alipay.easysdk.payment.page.models.AlipayTradePagePayResponse;
import com.meeno.common.utils.IdUtils;
import com.meeno.zhengcaiyun.pay.config.AlipayConfig;
import com.meeno.zhengcaiyun.pay.service.AlipayService;
import com.meenoframework.common.filter.ThreadLocalClient;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional(rollbackFor = Exception.class)
public class AlipayServiceImpl implements AlipayService {


    @Override
    public String paymentPage() {
        Long userId = ThreadLocalClient.get().getId();
        // 1. 设置参数(全局只需设置一次)
        Factory.setOptions(AlipayConfig.getOptions());
        try {
            // 2. 发起API调用(以创建当面付收款二维码为例)
            AlipayTradePagePayResponse response = Factory.Payment.Page().pay("政采云", IdUtils.getOrderNo(userId), "1.0", null);
            /*AlipayTradePrecreateResponse response = Factory.Payment.FaceToFace()
                    .preCreate("Apple iPhone11 128G", "2234567890", "5799.00");*/
            // 3. 处理响应或异常
            if (ResponseChecker.success(response)) {
                System.out.println("调用成功");
                return response.getBody();
            } else {
                //System.err.println("调用失败,原因:" + response.msg + "," + response.subMsg);
                System.err.println("调用失败!");
            }
        } catch (Exception e) {
            System.err.println("调用遭遇异常,原因:" + e.getMessage());
            throw new RuntimeException(e.getMessage(), e);
        }
        return null;
    }
}

AlipayController


package com.meeno.zhengcaiyun.pay.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import com.alipay.easysdk.factory.Factory;
import com.alipay.easysdk.kernel.Config;
import com.alipay.easysdk.kernel.util.ResponseChecker;
import com.alipay.easysdk.payment.facetoface.models.AlipayTradePrecreateResponse;
import com.alipay.easysdk.payment.page.models.AlipayTradePagePayResponse;
import com.meeno.common.ResultUtil;
import com.meeno.common.utils.IdUtils;
import com.meeno.zhengcaiyun.pay.config.AlipayConfig;
import com.meeno.zhengcaiyun.pay.service.AlipayService;
import com.meenoframework.common.filter.ThreadLocalClient;
import com.meenoframework.util.ResponseBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 网站支付
 */
@RestController
@RequestMapping("alipay")
public class AlipayController {


    @Autowired
    private AlipayService alipayService;

    /**
     * 调用支付
     * @return
     */
    @RequestMapping("paymentPage.action")
    public ResponseBean paymentPage(){
        String result = this.alipayService.paymentPage();
        return ResultUtil.success(result);
    }





}

IdUtils.java

package com.meeno.common.utils;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;

/**
 * id工具类
 */
public class IdUtils {

    /**
     * 获取订单唯一标识
     * @param userId
     * @return
     */
    public static String getOrderNo(Long userId){
        SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMddHHmmss");
        String dateStr=sdf.format(new Date());
        String result="";
        Random random=new Random();
        for(int i=0;i<3;i++){
            result+=random.nextInt(10);
        }
        if(userId == null){
            return dateStr+result;
        }
        return dateStr+userId+result;
    }

}

posted on 2020-12-28 18:19  公众号/架构师与哈苏  阅读(250)  评论(0编辑  收藏  举报