调用支付宝第三方支付接口详解(沙箱环境)

首发地址:Java知音

注:这里的支付是沙箱模拟支付

  1. 注册蚂蚁金服开放平台

蚂蚁金服开放平台注册地址
支付宝扫码登陆 -> 注册为自主研发者

点击进入
2. 配置你的沙箱支付宝

配置RSA2密钥
支付宝提供一键生成工具便于开发者生成一对RSA2密钥:https://docs.open.alipay.com/291/105971
该工具使用需要java环境
windows安装java环境:https://blog.csdn.net/edison_03/article/details/79757591
Mac安装java环境:https://www.cnblogs.com/xqx-qyy/p/7659805.html
生成RSA2密钥
注意:生成时一定要选择PKCS8+2048
配置RSA2密钥

将应用网关和回调地址更改为:https://www.alipay.com
AES密钥不用管
然后往下会有支付宝沙箱安卓端工具,下载,以供后续支付使用
进入页面左侧导航栏沙箱账号,沙箱安卓端安装后用买家账号登陆

到这里基本配置就完了,下面进入大家喜欢的代码时间:
3. 新建一个配置类 AlipayConfig.java

package com.alipay.config;

import java.io.FileWriter;
import java.io.IOException;

/* *
 *类名:AlipayConfig
 *作者:有梦想一起实现
 */

public class AlipayConfig{

    // ↓↓↓↓↓↓↓↓↓↓请在这里配置您的基本信息↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓

    // 应用ID,您的APPID,收款账号既是您的APPID对应支付宝账号
    public static String app_id = "APPID";//例:2016082600317257

    // 商户私钥,您的PKCS8格式RSA2私钥
    public static String merchant_private_key = "商户私钥!!!!私钥!!!不是公钥!!!";
    // 支付宝公钥,查看地址:https://openhome.alipay.com/platform/keyManage.htm
    // 对应APPID下的支付宝公钥。
    public static String alipay_public_key = "支付宝公钥,记得是支付宝公钥!!!!!!!支付宝公钥";
    // 服务器异步通知页面路径 需http://格式的完整路径,不能加?id=123这类自定义参数,必须外网可以正常访问
    /**
     * 返回的时候此页面不会返回到用户页面,只会执行你写到控制器里的地址
     */
    public static String notify_url = "你的服务器地址/项目名称/notify_url";
    // 页面跳转同步通知页面路径 需http://格式的完整路径,不能加?id=123这类自定义参数,必须外网可以正常访问
    /**
     * 此页面是同步返回用户页面,也就是用户支付后看到的页面,上面的notify_url是异步返回商家操作,谢谢
     * 要是看不懂就找度娘,或者多读几遍,或者去看支付宝第三方接口API,不看API直接拿去就用,遇坑不怪别人
     */
    public static String return_url = " 你的服务器地址/项目名称/return_url";
    // 签名方式
    public static String sign_type = "RSA2";
    // 字符编码格式
    public static String charset = "gbk";
    // 支付宝网关
    public static String gatewayUrl = "https://openapi.alipaydev.com/gateway.do";
    // 日志地址
    public static String log_path = "D:/logs/";
    // ↑↑↑↑↑↑↑↑↑↑请在这里配置您的基本信息↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑

    /**
     * 写日志,方便测试(看网站需求,也可以改成把记录存入数据库)
     *
     * @param sWord
     *            要写入日志里的文本内容
     */
    public static void logResult(String sWord) {
        FileWriter writer = null;
        try {
            writer = new FileWriter(log_path + "alipay_log_"
                    + System.currentTimeMillis() + ".txt");
            writer.write(sWord);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (writer != null) {
                try {
                    writer.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
如果你是在本地测试,支付完成不会跳转回调页面,那么就需要外网了
推荐一个东西,叫内网穿透,只要你电脑tomcat启动,可以连接外网,就可以使用
---- 内网穿透软件 ----
NATAPP 提供免费的测试足够->https://natapp.cn/
ngrok或者frp以及其他免费开源Google自行了解
  1. 引入依赖包
<dependency>
    <groupId>com.pentahohub.nexus</groupId>
    <artifactId>alipay-sdk-java</artifactId>
    <version>20150820220052</version>
</dependency>

如果上面的依赖失效或者无法使用,依赖下载地址:http://central.maven.org/maven2/com/pentahohub/nexus/alipay-sdk-java/20150820220052/alipay-sdk-java-20150820220052.jar
5. 支付调用的接口

/**
     * 快捷支付调用支付宝支付接口
     * @param model,id,payables, 
     * @throws IOException,AlipayApiException
     * @return Object
     * @author 有梦想一起实现
     */
    @RequestMapping("alipaySum")
    public Object alipayIumpSum(Model model, String payables, String subject, String body, HttpServletResponse response)
            throws Exception {
        // 获得初始化的AlipayClient
        AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfigInfo.gatewayUrl, AlipayConfigInfo.app_id,
                AlipayConfigInfo.merchant_private_key, "json", AlipayConfigInfo.charset,
                AlipayConfigInfo.alipay_public_key, AlipayConfigInfo.sign_type);
        // 设置请求参数
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        alipayRequest.setReturnUrl(AlipayConfigInfo.return_url);
        alipayRequest.setNotifyUrl(AlipayConfigInfo.notify_url2);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        // 商户订单号,商户网站订单系统中唯一订单号,必填
        String out_trade_no = sdf.format(new Date());
        // 付款金额,必填
        String total_amount = payables.replace(",", "");
        alipayRequest.setBizContent("{\"out_trade_no\":\"" + out_trade_no + "\"," + "\"total_amount\":\"" + total_amount
                + "\"," + "\"subject\":\"" + subject + "\"," + "\"body\":\"" + body + "\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
        // 请求
        String result = alipayClient.pageExecute(alipayRequest).getBody();
        // System.out.println(result);
        AlipayConfigInfo.logResult(result);// 记录支付日志
        response.setContentType("text/html; charset=gbk");
        PrintWriter out = response.getWriter();
        out.print(result);
        return null;
    }

参数传入是必须有的,不然会报订单信息有误

如果有其他额外参数,请参考支付宝第三方API文档

  1. 支付完成回调
    这里支付完成会回调两个接口,notify_url和return_url,就是在配置类配置的两个接口
  • notify_url接口->异步回调的后台操作
/**
     * 支付完成回调验证操作
     * @param response,request
     * @throws Exception
     * @return void
     * @author 有梦想一起实现
     */
    @RequestMapping("notify_url")
    public void Notify(HttpServletResponse response, HttpServletRequest request) throws Exception {
        System.out.println("----------------------------notify_url------------------------");
        // 商户订单号
        String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"), "GBK");
        // 付款金额
        String total_amount = new String(request.getParameter("total_amount").getBytes("ISO-8859-1"), "GBK");
        // 支付宝交易号
        String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"), "GBK");
        // 交易说明
        String cus = new String(request.getParameter("body").getBytes("ISO-8859-1"), "GBK");
        // 交易状态
        String trade_status = new String(request.getParameter("trade_status").getBytes("ISO-8859-1"), "GBK");
        if (trade_status.equals("TRADE_SUCCESS")) {//支付成功商家操作
            //下面是我写的一个简单的插入操作,根据你的操作自行编写
            /*Map<Object, Object> map = new HashMap<Object, Object>();
            map.put("cuId", Integer.valueOf(cus));
            RepaymentPlan repaymentPlan = new RepaymentPlan();
            Integer id = Integer.valueOf(out_trade_no);
            double payablesCheck = Double.valueOf(total_amount);
            RepaymentPlan repayCheck = serviceMain.selectByPrimaryKey(id);
            double total = repayCheck.getPayables();
            if (Double.valueOf(total_amount) < repayCheck.getPayables()) {
                map.put("ubalance", total - Double.valueOf(total_amount));
                serviceMain.updateCusMoney(map);
            }
            repaymentPlan.setId(id);
            repaymentPlan.setActualPayment(total);
            repaymentPlan.setRepaymentStatus(1);
            int i = serviceMain.updateByPrimaryKeySelective(repaymentPlan);
            System.out.println("---------------------还款影响行数----------------------------" + i);*/
        }
    }
  • return_url 接口->同步通知返回的是页面
/**
     * 同步通知的页面的Controller
     * 我这边就简单的返回了一个页面
     * @param request,response
     * @throws InterruptedException
     */
    @RequestMapping("return_url")
    public String Return_url() throws InterruptedException {
        return "alipayexit";
    }
  1. 请求支付接口的JSP的页面
<form name=alipayment action=alipay.trade.page.pay.jsp method=post
            target="_blank">
            <div id="body1" class="show" name="divcontent">
                <dl class="content">
                    <dt>商户订单号 :</dt>
                    <dd>
                        <input id="WIDout_trade_no" name="WIDout_trade_no" />
                    </dd>
                    <hr class="one_line">
                    <dt>订单名称 :</dt>
                    <dd>
                        <input id="WIDsubject" name="WIDsubject" />
                    </dd>
                    <hr class="one_line">
                    <dt>付款金额 :</dt>
                    <dd>
                        <input id="WIDtotal_amount" name="WIDtotal_amount" />
                    </dd>
                    <hr class="one_line">
                    <dt>商品描述:</dt>
                    <dd>
                        <input id="WIDbody" name="WIDbody" />
                    </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>
<!--这里的target为_blank是新打开一个窗口-->

支付宝接口的SDK&DEMO地址:https://docs.open.alipay.com/270/106291/

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_38405253/article/details/84316979