支付宝密钥及文件生成方式

1、申请 支付宝开放平台

1.1 、在开放平台的控制台中添加应用

支付宝密钥及文件生成方式_第1张图片

 1.2、创建应用之后添加应用的支付能力

支付宝密钥及文件生成方式_第2张图片

 1.3、点击应用信息

支付宝密钥及文件生成方式_第3张图片

 

设置接口加签方式(密钥/证书),当然如果不涉及到账户支出则设置密钥方式即可,涉及到退款提现的话就申请证书方式,建议使用证书方式

1.4、下载支付宝开发助手

支付宝密钥及文件生成方式_第4张图片

生成公私密钥,配置开发信息中接口加密方式,需要证书模式,则直接点击获取CSR文件获取公私密钥和证书,密钥模式配置之后记得复制支付宝公钥

2、申请支付宝商家中心

开通对应的支付产品

支付宝密钥及文件生成方式_第5张图片

  涉及提现的话需要申请

支付宝密钥及文件生成方式_第6张图片

 3、开发代码(以证书方式):


    com.alipay.sdk
    alipay-sdk-java
    4.9.124.ALL

alipay:
  appCertPath: appCertPublicKey_appid.crt
  # 证书方式回调解析数据使用
  alipayCertPath: alipayCertPublicKey_RSA2.crt
  alipayRootCertPath: alipayRootCert.crt
  test: 2022年3月27日15:48:07
  appId: appid
  # 密钥方式回调解析数据使用
  alipaypublickey: 
  publicKey: 
  privateKey: 
  serverUrl: https://openapi.alipay.com/gateway.do
  format: json
  charset: utf-8
  signType: RSA2
  notifyUrl: http://test.test.top/cli/ali/pay/notify
  version: 1.0
  identityType: ALIPAY_LOGON_ID
 
/**
 * 获取yml参数实体
 */
@Data
@Component
@ConfigurationProperties(prefix="alipay")
public class AliConfig {
 
    private  String test;
    private  String appId;
    private  String serverUrl;
    private  String privateKey;
    private  String publicKey;
    private  String alipayPublicKey;
    private  String appCertPath;
    private  String alipayCertPath;
    private  String identityType;
    private  String alipayRootCertPath;
    private  String format;
    private  String charset;
    private  String signType;
    private  String notifyUrl;
    private  String version;
 
    // 证书方式初始化
    public AlipayClient initAlipayClient() throws AlipayApiException {
        System.out.println(test);
        //构造client
        CertAlipayRequest certAlipayRequest = new CertAlipayRequest();
        certAlipayRequest.setServerUrl(serverUrl);
        //设置应用Id
        certAlipayRequest.setAppId(appId);
        //设置应用私钥
        certAlipayRequest.setPrivateKey(privateKey);
        //设置请求格式,固定值json
        certAlipayRequest.setFormat(format);
        //设置字符集
        certAlipayRequest.setCharset(charset);
        //设置签名类型
        certAlipayRequest.setSignType(signType);
        //设置应用公钥证书路径
        certAlipayRequest.setCertPath(appCertPath);
        //设置支付宝公钥证书路径
        certAlipayRequest.setAlipayPublicCertPath(alipayCertPath);
        //设置支付宝根证书路径
        certAlipayRequest.setRootCertPath(alipayRootCertPath);
        // 1:实例化支付
        AlipayClient alipayClient = new DefaultAlipayClient(certAlipayRequest);
        return alipayClient;
    }
    // 密钥方式初始化
    public AlipayClient client() {
        return new DefaultAlipayClient(serverUrl, appId, privateKey, format, charset, publicKey, signType);
    }
}

支付 

 @Override
    public AnmoResult aliPay(AlipayBean alipayBean) throws AlipayApiException {
        log.info("-----------支付宝支付:{}", JSONObject.toJSONString(alipayBean));
        AlipayClient alipayClient = aliConfig.initAlipayClient();
        AlipayTradeAppPayRequest request = new AlipayTradeAppPayRequest();
        //SDK已经封装掉了公共参数,这里只需要传入业务参数。以下方法为sdk的model入参方式(model和biz_content同时存在的情况下取biz_content)。
        AlipayTradeAppPayModel model = new AlipayTradeAppPayModel();
        model.setBody(alipayBean.getBody());
        model.setSubject(alipayBean.getSubject());
        model.setOutTradeNo(alipayBean.getOut_trade_no());
        model.setTimeoutExpress(alipayBean.getTimeout_express());
        model.setTotalAmount(alipayBean.getTotal_amount());
        model.setProductCode(alipayBean.getProduct_code());
        log.info("------支付封装类数据AlipayTradeAppPayModel:{}", JSONObject.toJSONString(model));
        request.setBizModel(model);
        request.setNotifyUrl(aliConfig.getNotifyUrl());
        request.setApiVersion(aliConfig.getVersion());
        log.info("------支付封装类数据AlipayTradeAppPayRequest:{}", JSONObject.toJSONString(model));
        //这里和普通的接口调用不同,使用的是sdkExecute
        AlipayTradeAppPayResponse response = alipayClient.sdkExecute(request);
        log.info("-----------支付宝同步结果--------------:{}", JSONObject.toJSONString(response));
        if (response.isSuccess()) {
            return AnmoResult.success("预支付请求成功", response.getBody());
        } else {
            return AnmoResult.error("预支付失败");
        }
    }

支付以证书方式为例:支付成功 包含:alipay_root_cert_sn的是预支付成功的,否则只是调通,参数有问题

退款

 @Override
    public AnmoResult alipayRefund(String out_trade_no, String trade_no, String refund_amount, String
            refund_reason, String out_request_no) throws Exception {
        AlipayClient alipayClient = aliConfig.initAlipayClient();
        log.info("-----开始发起退款:orderNo={}", out_trade_no);
        log.info("-----开始发起退款:tradeNo={}", trade_no);
        log.info("-----开始发起退款:refundAmount", refund_amount);
        //订单编号   支付宝交易号不为空
        if (out_trade_no != null && trade_no != null) {
            AlipayTradeRefundRequest alipay_request = new AlipayTradeRefundRequest();
            AlipayTradeRefundModel model = new AlipayTradeRefundModel();
            model.setOutTradeNo(out_trade_no);
            model.setTradeNo(trade_no);
            model.setRefundAmount(refund_amount);
            model.setRefundReason(refund_reason);
            model.setOutRequestNo(out_request_no);
            log.info("-------------退款请求model:{}", JSONObject.toJSONString(model));
            alipay_request.setBizModel(model);
            try {
                log.info("-------------退款请求request:{}", JSONObject.toJSONString(alipay_request));
                AlipayTradeRefundResponse alipay_response = alipayClient.certificateExecute(alipay_request);
                String alipayRefundStr = alipay_response.getBody();
                log.info("-------------退款结果:{}", alipayRefundStr);
                if (alipay_response.isSuccess()) {
                    return AnmoResult.success("退款成功", alipayRefundStr);
                } else {
                    return AnmoResult.error(alipay_response.getSubMsg());
                }
            } catch (AlipayApiException e) {
                e.printStackTrace();
            }
 
        }
 
        return null;
    }

回调

 @RequestMapping(value = "/notify")
    public void notifyOrder(HttpServletRequest request) {
        System.out.println();
        //获取支付宝POST过来反馈信息
        Map params = new HashMap();
        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);
        }
        log.info("---------支付宝异步回调:{}", JSONObject.toJSONString(params));
        //切记密钥方式回调:alipaypublickey是支付宝的公钥,请去open.alipay.com对应应用下查看。
        //boolean AlipaySignature.rsaCheckV1(Map params, String publicKey, String charset, String sign_type)
        try {
            // 证书方式回调 alipayCertPublicKey_RSA2.crt 文件校验签名
            boolean flag = AlipaySignature.rsaCertCheckV1(params, aliConfig.getAlipayCertPath(), aliConfig.getCharset(), aliConfig.getSignType());
            log.info("---------支付宝异步回调验签结果:{}", flag);
            if (flag) {
                String out_trade_no = params.get("out_trade_no");
                String notify_id = params.get("notify_id");
                if (out_trade_no.startsWith(USER_ORDER_BEFORE)) {
                    appUserOrderService.notifys(out_trade_no,notify_id);
                }
            }
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
    }

你可能感兴趣的:(java,java)