Java调用支付宝支付接口

这是一个简单的java调用支付宝支付接口的例子,代码较为原始,采用jsp+servlet模式,可根据业务场景项目框架稍做更改。

应用环境:沙箱(入驻开发不需要营业执照,但正式线上不可使用,下载沙箱支付宝进行测试),pc端支付(手机端略有不同)

前期工作:配置好沙箱环境(官方文档),关于私钥,公钥,以及验证算法等名词详见官方文档,下载沙箱板支付宝app,官方会提供一个测试账号。

案例结构:

                                    Java调用支付宝支付接口_第1张图片

直接贴代码(有些官方demo稍做更改可直接复制使用):

AlipayConfig.java:

package com.alipay.config;

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

/* *
 *类名:AlipayConfig
 *功能:基础配置类
 *详细:设置帐户有关信息及返回路径
 *修改日期:2017-04-05
 *说明:
 *以下代码只是为了方便商户测试而提供的样例代码,商户可以根据自己网站的需要,按照技术文档编写,并非一定要使用该代码。
 *该代码仅供学习和研究支付宝接口使用,只是提供一个参考。
 */

public class AlipayConfig {
	
//↓↓↓↓↓↓↓↓↓↓请在这里配置您的基本信息↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓

	// 应用ID,您的APPID,收款账号既是您的APPID对应支付宝账号
	public static String app_id = "2016091000482028";
	
	// 商户私钥,您的PKCS8格式RSA2私钥
    public static String merchant_private_key = "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQC3vBJZWEdUco822cAvmiuZvuNdQifDLbxZ2+6jgGCYLTWkYa5OrSnisSrv9R0yMr0GfXp3jfi7zOTi/jL3Iwk83r0xWGUSMcYKZvQBfn41htQRQZ9IlgB3faW3WDLnDavEleNwLuug/11w/E+PHMK+7nJjAUWu4xXIcuZHHJBnpjMkJ3qceeomplTPygrmEsT+I586c0n2eXH091meH3QS2cANaWGmQoKqtUuzD7F61Os03M2+SmDzieu7EYhtlg80jzXjFvoasI1UcAoQMgJIcbo0pyUDQ/ArRmpiPRJyd7+UgqjkAGPMFWfV0jWTwc428Iq6qgcBWrIKDmmtd0vbAgMBAAECggEACWW9KoSxYUhautt4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ashSkOd2BSE0Z9xMZqW9J2T2MMnWyXv0ubTKz/WmiCCLdjVuMuooUOEIMy+1K56E47XUUl2tZewbX1oZIkjROkOsEk0djbRh1UzdtvtRTqn2U+Rh04e3zQG691cg0=";
	
	// 支付宝公钥,查看地址:https://openhome.alipay.com/platform/keyManage.htm 对应APPID下的支付宝公钥。
    public static String alipay_public_key = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAyrCb/E84SZePt87PZhpdY6H2OlyHIUTlClAneKk/tn6LfhaAMLYE8xHDi4ZdwcYi8kYhZ0dscz4FwVAdEgO3nN56U5lpC88SJYV7+fQn0n2hj6Dlp4z7pKUSCljt3YZDNYRh3NHviDDR3QTSadOqbRxoCxQ3PRCzGMN6sojWWVKmCxXkgyMNvSkFgWerPsv7imkr2a8gzOaYyDcbjco1P7W2H7IBtIuk5JF9DMkXp0cseuGFsVhXxUfQHiOgTJl9MB/XV+/V2S94Q8sCFzj5OvhAqkJAPQWMwuECfhqEl8LE9QRvjbxkne9VWeM3Ce3bzHO4cg8OAECYGptMWfz9wQIDAQAB";

	// 服务器异步通知页面路径  需http://格式的完整路径,不能加?id=123这类自定义参数,必须外网可以正常访问
	public static String notify_url = "http://工程公网访问地址/alipay.trade.page.pay-JAVA-UTF-8/notify_url.jsp";

	// 页面跳转同步通知页面路径 需http://格式的完整路径,不能加?id=123这类自定义参数,必须外网可以正常访问
	public static String return_url = "http://工程公网访问地址/alipay.trade.page.pay-JAVA-UTF-8/return_url.jsp";

	// 签名方式
	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 = "C:\\";


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

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

AlipayServlet.java:

package com.alipay.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alipay.util.AlipayUtil;

public class AlipayServlet extends HttpServlet {
	
	private static final long serialVersionUID = 1L;
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		//商户订单号,商户网站订单系统中唯一订单号,必填
		String orderId = new String(request.getParameter("WIDout_trade_no").getBytes("ISO-8859-1"),"UTF-8");
		//付款金额,必填
		String money = new String(request.getParameter("WIDtotal_amount").getBytes("ISO-8859-1"),"UTF-8");
		//订单名称,必填
		String name = new String(request.getParameter("WIDsubject").getBytes("ISO-8859-1"),"UTF-8");
		//商品描述,可空
		String info = new String(request.getParameter("WIDbody").getBytes("ISO-8859-1"),"UTF-8");
		
		try {
			String result = AlipayUtil.pay(response, money, info, name, orderId);
			request.setAttribute("result", result);
			System.out.println(result);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		request.getRequestDispatcher("/hello.jsp").forward(request,response);
	}

	
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		this.doGet(request, response);
	}

} 


AlipayUtil.java:

package com.alipay.util;

import javax.servlet.http.HttpServletResponse;

import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.config.AlipayConfig;

public class AlipayUtil {

	public static String pay(HttpServletResponse response,String money,String info,String name,String orderId) throws Exception{
		//获得初始化的AlipayClient
		AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id, AlipayConfig.merchant_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);
		
		/*AlipayTradeAppPayModel model = new AlipayTradeAppPayModel();
        model.setBody(name);		//名称
        model.setSubject(info);		//描述
        model.setOutTradeNo(orderId);//订单id
        model.setTimeoutExpress("30m");	//描述
        model.setTotalAmount(money);	//金额
        //model.setPassbackParams( "2" );
        model.setProductCode("FAST_INSTANT_TRADE_PAY");
        alipayRequest.setBizModel(model);
        alipayRequest.setNotifyUrl(AlipayConfig.notify_url);*/
		
		/*//商户订单号,商户网站订单系统中唯一订单号,必填
		String out_trade_no = new String(request.getParameter("WIDout_trade_no").getBytes("ISO-8859-1"),"UTF-8");
		//付款金额,必填
		String total_amount = new String(request.getParameter("WIDtotal_amount").getBytes("ISO-8859-1"),"UTF-8");
		//订单名称,必填
		String subject = new String(request.getParameter("WIDsubject").getBytes("ISO-8859-1"),"UTF-8");
		//商品描述,可空
		String body = new String(request.getParameter("WIDbody").getBytes("ISO-8859-1"),"UTF-8");*/
		
		alipayRequest.setBizContent("{\"out_trade_no\":\""+ orderId +"\"," 
				+ "\"total_amount\":\""+ money +"\"," 
				+ "\"subject\":\""+ name +"\"," 
				+ "\"body\":\""+ info +"\"," 
				+ "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
		
		//若想给BizContent增加其他可选请求参数,以增加自定义超时时间参数timeout_express来举例说明
		//alipayRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\"," 
		//		+ "\"total_amount\":\""+ total_amount +"\"," 
		//		+ "\"subject\":\""+ subject +"\"," 
		//		+ "\"body\":\""+ body +"\"," 
		//		+ "\"timeout_express\":\"10m\"," 
		//		+ "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
		//请求参数可查阅【电脑网站支付的API文档-alipay.trade.page.pay-请求参数】章节
		
		//请求
		String result = alipayClient.pageExecute(alipayRequest).getBody();
		
		//返回
		return result;
	}
}

hello.jsp

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>




Insert title here


${result }

index.jsp:(官方demo,只修改了form表单里的action让其跳转到后台,代码较长就不贴了)

web.xml:配置下servlet请求即可。

Java调用支付宝支付接口_第2张图片

点击付款,跳转至支付宝支付页面

Java调用支付宝支付接口_第3张图片

使用沙箱版支付宝登录官方提供的账号进行扫一扫付款,可能输入交易密码时系统会出错,多试几次。

Java调用支付宝支付接口_第4张图片

支付成功后会跳转至预先设定的页面,在config.java里面:

Java调用支付宝支付接口_第5张图片

需要是部署到服务器的项目url(外网能访问到的)。


查询,退款等代码类似,再次就不一一列举了。


你可能感兴趣的:(Java)