IDEA+SpringBoot+支付宝沙箱支付

一:环境配置参数
1.下载支付宝官方提供的支付demo,https://docs.open.alipay.com/270/106291/
IDEA+SpringBoot+支付宝沙箱支付_第1张图片
我们下载java版本然后解压就可以看到项目结构:
IDEA+SpringBoot+支付宝沙箱支付_第2张图片
红色框里面,是需要我们去支付宝开发平台去申请配置的信息:
免费注册蚂蚁金服开发者账号:
注册地址:https://developers.alipay.com/developmentAccess/developmentAccess.htm

申请步骤:
IDEA+SpringBoot+支付宝沙箱支付_第3张图片
用支付宝账号申请注册
IDEA+SpringBoot+支付宝沙箱支付_第4张图片
获得appId[配置文件必要]
IDEA+SpringBoot+支付宝沙箱支付_第5张图片
IDEA+SpringBoot+支付宝沙箱支付_第6张图片
IDEA+SpringBoot+支付宝沙箱支付_第7张图片
此处私钥为配置文件必要:
IDEA+SpringBoot+支付宝沙箱支付_第8张图片
IDEA+SpringBoot+支付宝沙箱支付_第9张图片
IDEA+SpringBoot+支付宝沙箱支付_第10张图片
这里会得到配置文件支付宝公钥:
IDEA+SpringBoot+支付宝沙箱支付_第11张图片
IDEA+SpringBoot+支付宝沙箱支付_第12张图片
配置文件需要的参数我们已经得到了

二:SpringBoot接入支付
1.创建springboot项目
结构如下(自定义):
IDEA+SpringBoot+支付宝沙箱支付_第13张图片
pom.xml文件中导入依赖:

<dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!-- https://mvnrepository.com/artifact/com.alipay.sdk/alipay-sdk-java -->
        <dependency>
            <groupId>com.alipay.sdk</groupId>
            <artifactId>alipay-sdk-java</artifactId>
            <version>3.7.110.ALL</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.33</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
    </dependencies>

配置文件alipay.properties:

#应用ID,您的APPID,收款账号既是您的APPID对应支付宝账号
app_id=202100011xxxxx
#商户私钥,您的PKCS8格式RSA2私钥
merchant_private_key=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
#支付宝公钥,查看地址:https://openhome.alipay.com/platform/keyManage.htm 对应APPID下的支付宝公钥。
alipay_public_key=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
#服务器异步通知页面路径  需http://格式的完整路径,不能加?id=123这类自定义参数,必须外网可以正常访问
notify_url=http://localhost:8080/alipay/static/notify_url.jsp
#页面跳转同步通知页面路径 需http://格式的完整路径,不能加?id=123这类自定义参数,必须外网可以正常访问
return_url=http://localhost:8080/alipay/static/return_url.jsp
#签名方式
sign_type=RSA2
#字符编码格
charset=utf-8
#支付宝网关
gatewayUrl=https://openapi.alipaydev.com/gateway.do
# 支付宝网关
log_path="C:\\"

创建实体类

package com.lax.alipay.bean;

import lombok.Data;
import lombok.experimental.Accessors;

@Data
@Accessors(chain = true)
public class AlipayBean {
    /*商户订单号,必填*/
    private String out_trade_no;
    /*订单名称,必填*/
    private String subject;
    /*付款金额,必填*/
    private StringBuffer total_amount;
    /*商品描述,可空*/
    private String body;
    /*超时时间参数*/
    private String timeout_express = "10m";
    private String product_code = "FAST_INSTANT_TRADE_PAY";
}

创建业务接口:

package com.lax.alipay.service;

import com.alipay.api.AlipayApiException;
import com.lax.alipay.bean.AlipayBean;

public interface PayService {
    String aliPay(AlipayBean alipayBean) throws AlipayApiException;
}

书写业务接口实现类:

package com.lax.alipay.service.impl;

import com.alipay.api.AlipayApiException;
import com.lax.alipay.bean.AlipayBean;
import com.lax.alipay.config.AlipayUtil;
import com.lax.alipay.service.PayService;

import org.springframework.stereotype.Service;

@Service
public class PayServiceImpl implements PayService {
    @Override
    public String aliPay(AlipayBean alipayBean) throws AlipayApiException {
        return AlipayUtil.connect(alipayBean);
    }
}

控制器:

package com.lax.alipay.controller;

import com.alipay.api.AlipayApiException;
        import com.lax.alipay.bean.AlipayBean;
        import com.lax.alipay.service.PayService;
        import org.springframework.beans.factory.annotation.Autowired;
        import org.springframework.web.bind.annotation.PostMapping;
        import org.springframework.web.bind.annotation.RequestMapping;
        import org.springframework.web.bind.annotation.RestController;
@RestController()
@RequestMapping("/order")
public class OrderController {
        @Autowired
        private PayService payService;//调用支付服务   
        @PostMapping(value = "alipay")
        public String alipay(String out_trade_no, String subject, String total_amount, String body) throws AlipayApiException {
                return payService.aliPay(new AlipayBean()
                        .setBody(body)
                        .setOut_trade_no(out_trade_no)
                        .setTotal_amount(new StringBuffer().append(total_amount))
                        .setSubject(subject));
        }
}

配置文件读取工具类:

package com.lax.alipay.config;
import org.springframework.beans.factory.config.PropertiesFactoryBean;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.stereotype.Component;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

/* 应用启动加载文件*/
@Component
public class PropertiesConfig implements ApplicationListener {
    //保存加载配置参数
    private static Map<String, String> aliPropertiesMap = new HashMap<String, String>();
    //获取配置参数值
    public static String getKey(String key) {
        return aliPropertiesMap.get(key);
    }
    //监听启动完成,执行配置加载到aliPropertiesMap
    public void onApplicationEvent(ApplicationEvent event) {
        if (event instanceof ApplicationReadyEvent) {
            this.init(aliPropertiesMap);//应用启动加载
        }
    }
    //初始化加载aliPropertiesMap
    public void init(Map<String, String> map) {
        // 获得PathMatchingResourcePatternResolver对象
        PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        try {
            //加载resource文件(也可以加载resources)
            Resource resources = resolver.getResource("classpath:config/alipay.properties");
            PropertiesFactoryBean config = new PropertiesFactoryBean();
            config.setLocation(resources);
            config.afterPropertiesSet();
            Properties prop = config.getObject();
            //循环遍历所有得键值对并且存入集合
            for (String key : prop.stringPropertyNames()) {
                map.put(key, (String) prop.get(key));
            }
        } catch (Exception e) {
            new Exception("配置文件加载失败");
        }
    }
}

AlipayUtil工具类:

package com.lax.alipay.config;

import com.alibaba.fastjson.JSON;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.lax.alipay.bean.AlipayBean;

public class AlipayUtil {
    public static String connect(AlipayBean alipayBean) throws AlipayApiException {
        //1、获得初始化的AlipayClient
        AlipayClient alipayClient = new DefaultAlipayClient(
                PropertiesConfig.getKey("gatewayUrl"),//支付宝网关
                PropertiesConfig.getKey("app_id"),//appid
                PropertiesConfig.getKey("merchant_private_key"),//商户私钥
                "json",
                PropertiesConfig.getKey("charset"),//字符编码格式
                PropertiesConfig.getKey("alipay_public_key"),//支付宝公钥
                PropertiesConfig.getKey("sign_type")//签名方式
        );
        //2、设置请求参数
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        //页面跳转同步通知页面路径
        alipayRequest.setReturnUrl(PropertiesConfig.getKey("return_url"));
        // 服务器异步通知页面路径
        alipayRequest.setNotifyUrl(PropertiesConfig.getKey("notify_url"));
        //封装参数
        alipayRequest.setBizContent(JSON.toJSONString(alipayBean));

        //3、请求支付宝进行付款,并获取支付结果
        String result = alipayClient.pageExecute(alipayRequest).getBody();

        //返回付款信息
        return result;
    }
}

index.HTML支付页面:


<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>支付宝电脑网站支付title>
    <style>
        * {
            margin: 0;
            padding: 0;
        }
        ul, ol {
            list-style: none;
        }
        body {
            font-family: "Helvetica Neue", Helvetica, Arial, "Lucida Grande",
            sans-serif;
        }
        .tab-head {
            margin-left: 120px;
            margin-bottom: 10px;
        }
        .tab-content {
            clear: left;
            display: none;
        }
        h2 {
            border-bottom: solid #02aaf1 2px;
            width: 200px;
            height: 25px;
            margin: 0;
            float: left;
            text-align: center;
            font-size: 16px;
        }
        .selected {
            color: #FFFFFF;
            background-color: #02aaf1;
        }
        .show {
            clear: left;
            display: block;
        }
        .hidden {
            display: none;
        }
        .new-btn-login-sp {
            padding: 1px;
            display: inline-block;
            width: 75%;
        }
        .new-btn-login {
            background-color: #02aaf1;
            color: #FFFFFF;
            font-weight: bold;
            border: none;
            width: 100%;
            height: 30px;
            border-radius: 5px;
            font-size: 16px;
        }
        #main {
            width: 100%;
            margin: 0 auto;
            font-size: 14px;
        }
        .red-star {
            color: #f00;
            width: 10px;
            display: inline-block;
        }
        .null-star {
            color: #fff;
        }
        .content {
            margin-top: 5px;
        }
        .content dt {
            width: 100px;
            display: inline-block;
            float: left;
            margin-left: 20px;
            color: #666;
            font-size: 13px;
            margin-top: 8px;
        }
        .content dd {
            margin-left: 120px;
            margin-bottom: 5px;
        }
        .content dd input {
            width: 85%;
            height: 28px;
            border: 0;
            -webkit-border-radius: 0;
            -webkit-appearance: none;
        }
        #foot {
            margin-top: 10px;
            position: absolute;
            bottom: 15px;
            width: 100%;
        }
        .foot-ul {
            width: 100%;
        }
        .foot-ul li {
            width: 100%;
            text-align: center;
            color: #666;
        }
        .note-help {
            color: #999999;
            font-size: 12px;
            line-height: 130%;
            margin-top: 5px;
            width: 100%;
            display: block;
        }
        #btn-dd {
            margin: 20px;
            text-align: center;
        }
        .foot-ul {
            width: 100%;
        }
        .one_line {
            display: block;
            height: 1px;
            border: 0;
            border-top: 1px solid #eeeeee;
            width: 100%;
            margin-left: 20px;
        }
        .am-header {
            display: -webkit-box;
            display: -ms-flexbox;
            display: box;
            width: 100%;
            position: relative;
            padding: 7px 0;
            -webkit-box-sizing: border-box;
            -ms-box-sizing: border-box;
            box-sizing: border-box;
            background: #1D222D;
            height: 50px;
            text-align: center;
            -webkit-box-pack: center;
            -ms-flex-pack: center;
            box-pack: center;
            -webkit-box-align: center;
            -ms-flex-align: center;
            box-align: center;
        }
        .am-header h1 {
            -webkit-box-flex: 1;
            -ms-flex: 1;
            box-flex: 1;
            line-height: 18px;
            text-align: center;
            font-size: 18px;
            font-weight: 300;
            color: #fff;
        }
    style>
head>
<body text=#000000 bgColor="#ffffff" leftMargin=0 topMargin=4>
<header class="am-header">
    <h1>支付宝电脑网站支付体验入口页h1>
header>
<div id="main">
    <div id="tabhead" class="tab-head">
        <h2 id="tab1" class="selected" name="tab">付 款h2>
        <h2 id="tab2" name="tab">交 易 查 询h2>
        <h2 id="tab3" name="tab">退 款h2>
        <h2 id="tab4" name="tab">退 款 查 询h2>
        <h2 id="tab5" name="tab">交 易 关 闭h2>
    div>
    <form name=alipayment action="/order/alipay" method=post
          target="_blank">
        <div id="body1" class="show" name="divcontent">
            <dl class="content">
                <dt>商户订单号 :dt>
                <dd>
                    <input id="WIDout_trade_no" name="out_trade_no" />
                dd>
                <hr class="one_line">
                <dt>订单名称 :dt>
                <dd>
                    <input id="WIDsubject" name="subject" />
                dd>
                <hr class="one_line">
                <dt>付款金额 :dt>
                <dd>
                    <input id="WIDtotal_amount" name="total_amount" />
                dd>
                <hr class="one_line">
                <dt>商品描述:dt>
                <dd>
                    <input id="WIDbody" name="body" />
                dd>
                <hr class="one_line">
                <dt>dt>
                <dd id="btn-dd">
						<span class="new-btn-login-sp">
							<button class="new-btn-login" type="submit"
                                    style="text-align: center;">付 款button>
						span> <span class="note-help">如果您点击“付款”按钮,即表示您同意该次的执行操作。span>
                dd>
            dl>
        div>
    form>
    <div id="foot">
        <ul class="foot-ul">
            <li>支付宝版权所有 2015-2018 ALIPAY.COMli>
        ul>
    div>
div>
body>
<script language="javascript">
    var tabs = document.getElementsByName('tab');
    var contents = document.getElementsByName('divcontent');

    (function changeTab(tab) {
        for(var i = 0, len = tabs.length; i < len; i++) {
            tabs[i].onmouseover = showTab;
        }
    })();
    function showTab() {
        for(var i = 0, len = tabs.length; i < len; i++) {
            if(tabs[i] === this) {
                tabs[i].className = 'selected';
                contents[i].className = 'show';
            } else {
                tabs[i].className = '';
                contents[i].className = 'tab-content';
            }
        }
    }
    function GetDateNow() {
        var vNow = new Date();
        var sNow = "";
        sNow += String(vNow.getFullYear());
        sNow += String(vNow.getMonth() + 1);
        sNow += String(vNow.getDate());
        sNow += String(vNow.getHours());
        sNow += String(vNow.getMinutes());
        sNow += String(vNow.getSeconds());
        sNow += String(vNow.getMilliseconds());
        // sNow += String("中开卖身");
        document.getElementById("WIDout_trade_no").value =  sNow;
        document.getElementById("WIDsubject").value = "班长卖身假价包邮";
        document.getElementById("WIDtotal_amount").value = "9.90";
    }
    GetDateNow();
script>
html>

然后我们就可以开启服务器去测试啦!
IDEA+SpringBoot+支付宝沙箱支付_第14张图片
IDEA+SpringBoot+支付宝沙箱支付_第15张图片

IDEA+SpringBoot+支付宝沙箱支付_第16张图片
IDEA+SpringBoot+支付宝沙箱支付_第17张图片

IDEA+SpringBoot+支付宝沙箱支付_第18张图片
快去试试吧~

你可能感兴趣的:(IDEA+SpringBoot+支付宝沙箱支付)