JAVA development Alipay interface (sandbox environment)

Step Description

1. First go to the ants gold dress Developer Center  https://openhome.alipay.com/platform/home.htm  registered merchant account.

2. The developer certification, and generate a public key, private use RSARSA signature verification check tool.

3.pom profile com.alipay.sdk rely introduced.

4. Access guide sandbox environment (as is the sandbox test environment, scan code using a mobile phone payments also need to download the sandbox version of Alipay APP).

5.Alipay configuration class with the payment interface development.

 

 

First, the RSA key

Merchant account registered and certified developer in which not much to say, we can be the next Baidu, it is to use your PayPal account or the account to log scan code, improve personal information, select the type of service (this person is a self-study), after registration may need to wait one hour for review,

But does not affect the use of sandbox test environment, there are pictures below to generate an RSA key generation official links.

 

 

 

Generation of key documents official website: https://docs.open.alipay.com/291/105971
official document speaks very detailed, you can follow the steps to remember to keep public and private keys, the following need to use.

Two, com.alipay.sdk dependence introduction

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

 

 

 

Third, the application sandbox environment

1. Log in Click Select Development Center R & D services.

 

2. Information The following figure shows the application sandbox

 

 

 

Sandbox version APP Download

 

 

 

 

 3. sandbox test account login information below is free to recharge the virtual account balance.

 

 

 

Fourth, the development of interface

1.在config文件下创建AlipayConfig配置类。

package com.app.config;

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

/**
 * Created  on 2019-9-09
 */
public class AlipayConfig {

    // 应用ID,您的APPID,收款账号既是您的APPID对应支付宝账号,开发时使用沙箱提供的APPID,生产环境改成自己的APPID
    public static String APP_ID = "你的沙箱APPID"; //测试

    // 商户私钥,您的PKCS8格式RSA2私钥
   public static String APP_PRIVATE_KEY = "在上面第一步生成的RSA私钥";

    // 支付宝公钥,查看地址:https://openhome.alipay.com/platform/keyManage.htm 对应APPID下的支付宝公钥。
    public static String ALIPAY_PUBLIC_KEY = "在沙箱应用中对应的支付宝公钥";

    // 服务器异步通知页面路径  需http://格式的完整路径,不能加?id=123这类自定义参数,必须外网可以正常访问
    public static String notify_url = "http://localhost:8080/Alipay/notifyUrl";

    // 页面跳转同步通知页面路径 需http://格式的完整路径,不能加?id=123这类自定义参数,必须外网可以正常访问(其实就是支付成功后返回的页面)
    public static String return_url = "http://localhost:8080/Alipay/returnUrl";
    // 签名方式
    public static String sign_type = "RSA2";

    // 字符编码格式
    public static String CHARSET = "UTF-8";

    // 支付宝网关,这是沙箱的网关
    public static String gatewayUrl = "https://openapi.alipaydev.com/gateway.do"; //测试

    // 支付宝网关
    public static String log_path = "E:\\";

    /**
     * 写日志,方便测试(看网站需求,也可以改成把记录存入数据库)
     * @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();
                }
            }
        }
    }
}

2.后台代码

 

 

 

package com.app.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.app.config.AlipayConfig;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * Created by  on 2019-9-09.
 */
@Controller
@RequestMapping(value="/Alipay")
public class AlipayController {
    /**
     * 购物车
     *
     * @return
     */
    @RequestMapping(value = "/Shopcart")
    public String Shopcart() {
        return  "pay";
    }

    /**
     * 结算界面
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/PayPage")
    public String  payController (HttpServletRequest request, HttpServletResponse response) throws IOException {
        //获得初始化的AlipayClient
        AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.APP_ID, AlipayConfig.APP_PRIVATE_KEY, "json", AlipayConfig.CHARSET, AlipayConfig.ALIPAY_PUBLIC_KEY, AlipayConfig.sign_type);

        //设置请求参数
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        alipayRequest.setReturnUrl(AlipayConfig.return_url);
        alipayRequest.setNotifyUrl(AlipayConfig.notify_url);

        //商户订单号,商户网站订单系统中唯一订单号,必填

        String out_trade_no = request.getParameter("Order");
        //付款金额,必填  ShopName
        String total_amount = request.getParameter("Money");
        //订单名称,必填
        String subject = request.getParameter("Name");
        //商品描述,可空
        String body =request.getParameter("购物测试");
        // 该笔订单允许的最晚付款时间,逾期将关闭交易。取值范围:1m~15d。m-分钟,h-小时,d-天,1c-当天(1c-当天的情况下,无论交易何时创建,都在0点关闭)。 该参数数值不接受小数点, 如 1.5h,可转换为 90m。
        String timeout_express = "1c";
        alipayRequest.setBizContent("{\"out_trade_no\":\"" + out_trade_no + "\","
                + "\"total_amount\":\"" + total_amount + "\","
                + "\"subject\":\"" + subject + "\","
                + "\"body\":\"" + body + "\","
                + "\"timeout_express\":\""+ timeout_express +"\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
        //请求
        String url = "";
        try {
            url = alipayClient.pageExecute(alipayRequest).getBody(); //调用SDK生成表单

               /* response.setContentType("text/html;charset=" + AlipayConfig.CHARSET);

                response.getWriter().write(url); // 直接将完整的表单html输出到页面
                response.getWriter().flush();
                response.getWriter().close();*/

        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        System.out.println(url);
        return url;
    }

    /**
     * 同步跳转
     *
     * @param request
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping("/returnUrl")
    public ModelAndView returnUrl(HttpServletRequest request) throws Exception {
        ModelAndView mav = new ModelAndView();

        // 获取支付宝GET过来反馈信息(官方固定代码)
        Map<String, String> params = new HashMap<String, String>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (Iterator<String> 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] + ",";
            }
            params.put(name, valueStr);
        }
        boolean signVerified = AlipaySignature.rsaCheckV1(params, AlipayConfig.ALIPAY_PUBLIC_KEY, AlipayConfig.CHARSET, AlipayConfig.sign_type); // 调用SDK验证签名

        // 返回界面
        if (signVerified) {
            System.out.println("前往支付成功页面");
            mav.setViewName("Shopcart");
        } else {
            System.out.println("前往支付失败页面");
            mav.setViewName("failReturn");
        }
        return mav;
    }

    /**
     * 支付宝服务器异步通知
     *
     * @param request
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping("/notifyUrl")
    public void notifyUrl(HttpServletRequest request) throws Exception {
        // 获取支付宝GET过来反馈信息
        Map<String, String> params = new HashMap<String, String>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (Iterator<String> 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] + ",";
            }
            params.put(name, valueStr);
        }

        boolean signVerified = AlipaySignature.rsaCheckV1(params, AlipayConfig.ALIPAY_PUBLIC_KEY, AlipayConfig.CHARSET, AlipayConfig.sign_type); // 调用SDK验证签名

        if (signVerified) { // 验证成功 更新订单信息
            System.out.println("异步通知成功");
            // 商户订单号
            String out_trade_no = request.getParameter("out_trade_no");
            // 交易状态
            String trade_status = request.getParameter("trade_status");
            // 修改数据库
        } else {
            System.out.println("异步通知失败");
        }
    }
}

3.前台页面html(页面比较lo,大家测试做个参考)

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">

    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title>沙箱下单测试</title>
    </head>

    <body>
        <div>
            <form action="http://localhost:8080/Alipay/PayPage" method="post">
                <div>
                    订单号:<input name="Order" value="20592155879901" ></input>
                </div>
                <div>
            商品名称:<input name="Name"  value="笔记本电脑"></input>
                </div>
                <div>
            金额:<input name="Money" value="99.99"></input></div>
            <input type="submit" value="提交订单"></input>
            </form>

        </div>

    </body>
</html>

4. Test results

Enter the web page: locahost: 8080 / Alipay / Shopcart 

 

 

 

 After clicking submit will automatically jump to the payment order interface, available sandbox version of Alipay APP scan payment, payment can also log in directly

 

 

 

 Sandbox effect payment account

 

 

 

If you need a formal environment, only need to replace a formal APPID, and formal Alipay gateway on the line .......

But it seems to have formally signed business registration and uploading required business license, you may be interested in the next test ...

 

Guess you like

Origin www.cnblogs.com/zh01/p/11512269.html