前几天一直在研究java集成支付宝支付,今天就把研究成果分享一下,也便于以后遇到需要集成支付宝支付的时候,可以很快就集成出来。
1.准备一个支付宝账号,登录蚂蚁金服开放平台,按照下图步骤,创建好应用,添加相应需要开发集成的支付功能,搭建好开发环境。
1.1.此处重点讲一下配置应用环境时开发环境的配置,如下图
1.支付网关:图中所示的支付网关是正式环境的支付网关,也就是应用上线以后用真正的支付宝进行支付的应用网关。我们在开发阶段不急集成正式环境
,所以蚂蚁金服特地为我们准备了沙箱环境,沙箱环境的支付网关为https://openapi.alipaydev.com/gateway.do,待应用开发完成,换成正式网关即可。
2.应用网关:我们在生成订单以后,需要调用支付宝进行支付,如果支付成功,支付宝就会主动通知我们自身的系统支付结果,这个应用网关就是我们在调用
支付宝支付时传给支付宝的(支付宝有了他就可以把支付结果通知给我们)。应用网关必须外网可以访问,关于如何把内网转化为外网可以访问,网上有很多
教程,这里不做讲述。
3.授权回调地址:如果我们是服务商,替商家开发集成支付宝支付的时候,需要商家给我们授权,这就好比你用微信或者其他应用的信息登录另一款APP的时候
,会提示需要访问你的一些资料,需要你授权一样,这个地址,就是商家给我们授权以后,支付宝主动通知我们授权结果的地址。授权流程如下图
我们需要拼接授权链接给商户,由商户点击链接进行授权正式环境的授权链接;https://openauth.alipay.com/oauth2/appToAppAuth.htm?app_id=2015101400446982&redirect_uri=http%3A%2F%2Fexample.com
其中app_id为正式环境的app_id,redirect_uri就是上述的授权回调地址沙箱环境的授权链接:https://openauth.alipaydev.com/oauth2/appToAppAuth.htm?app_id=APPID&redirect_uri=REDIRECT_URI
其中app_id为沙箱环境的app_id,redirect_uri就是上述的授权回调地址
通过商家授权以后,最终我们会调用支付宝的接口获取到最终的授权令牌,通过该令牌替商家发起支付宝的下单,支付,退款,查询等请求。
4.接口加签方式:可以参照开放平台上的步骤,去下载加签工具,然后生成自己的私钥和公钥.并将公钥设置到此处,私钥自己严加保存。
2.开发环境搭建好以后,接下来就可以利用开发文档进行开发了.此处只以开发电脑网站支付功能为例进行讲解,其他功能类似。
开放平台上有各个功能的相关demo,下载下来以后集成到代码中即可,比较简单,下载下来demo以后
首先看看配置类
package cn.mrdear.pay.alipay;
import java.io.FileWriter;
import java.io.IOException;
/
类名:AlipayConfig
功能:基础配置类
详细:设置帐户有关信息及返回路径
修改日期:2018-05-29
说明:
以下代码只是为了方便商户测试而提供的样例代码,商户可以根据自己网站的需要,按照技术文档编写,并非一定要使用该代码。
该代码仅供学习和研究支付宝接口使用,只是提供一个参考。
/
public class AliPayConfig {
//↓↓↓↓↓↓↓↓↓↓请在这里配置您的基本信息↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓
// 应用ID,您的APPID,收款账号既是您的APPID对应支付宝账号
public static String app_id = "";
// 商户私钥,您的PKCS8格式RSA2私钥
public static String merchant_private_key = "MIIFvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQDGL8zD8CqRDLxwsA5QKVZqdsyKVIwHF4y2rclIpl5W5BB3caO7oV9f1i/MsLzAsSqHIsuqaidcYQ/bjwEn1Q2nCUcf2VA3HndC2yAj97uD65VMBYDFKvealWyvSfTtJIi4lnObXxJdPDv+4WbrxMgIBdohz/pGON82gAPzcMmZOb8Xxn3JqRe55Pjy6h1IaAPCar3TCqDMfLzrGo03OYr01Tu+aDVk/d32MDW2IbjEXaVrJHCqbIqfri3z6Ny8UisD3FAmb5YnWGscZub/Ese6abPORRzpLuzGxgBUTtPvPy5qfvqxOFaUh2Q+kiZxYobhFCH88yF82J0ddpPiM1i7AgMBAAECggEBAJWcjBX2fgvV84OWRJfbPPNOD4b14GeSLZXSh7sibOFndc7VqOcCIX+1r4v0d+l3VUWCzQEu9dvVIiV7RUIOoinQ5TJz2QxjIWEFDrRYVeR2udQT62vszdKSruN9Dzrec5/1Y/yMvs5HpHr7Kbkeams0D8GqwaK1WDxKU7E5Gddi3mihXiD0X8p7MupAmP2T7xcwm75Jw7OGkfUIIzNDvvZ00aZALuCc5LvsCZHE8UTdIjMbvon5vs9hVzuAQMsyg1LAPxwusIOajlxiBl6WUZOXTwIrHZzzyEdbvg6KNfePSht7zhNIxPPCd5ud7VGZXhQmOaRE7SIOmFU+a4M+Q4ECgYEA5hJQddDAfpUH4VRfw9klHKxdkFQQWufDkCaijZKC/yfR5Z4Ukr8OhTP4VdJo1XzzXLx5RCRjQB8Zk7t7Z4SY/UmxU+VqsPtva2Uw9CHmIUpfS2VB078f087h4gfbgOZHTmdn7r1XSkTi/6cqgWeXfIdU0PT9N51JlEN+fmhLqGECgYEA3IWXcZdY4S2VJmkh5vG0PXO11rn3/w8hsNd/9Kfv4K5kUK1fUDnFDeQGJqAEazkEjzLAZrohi3Ip6aoSOIDx+HR9vvnhzG+rRJ+6Js/nUnzzkzyNrq+1GO5unsyRb9uaSBYvJCHgHY9Xq3B5jcF4v3VTU8ATDHmNI4LOl2MmJpsCgYAurvSok00b4j2RGT+9S6heIxNxH72Z1IE4FL7THzF5eKj8gJEIHcBiguMW9vTSrOHspUmt6/w/nI/iDB7EKIGqk3Np5Jk7hCldj1DZmK9Lff3MHKW4w4U/wzDOXm3Jv/AkFpNePAkkRsoQuejEDTMNz6AELlHbIQ03CmL2X09KwQKBgQCB3b6hK5MxEQoME8/eVKtjoTgOG3jb4Upi/ZYiO6A9vhXfmSpPcaYFlyq0JnpTtsFjn2zFUooct//M1tZiJjXZrqi7BieeoIjJIhObdcZxwpojNH7vyBQreYb1x91CdZ43I7FhYv28CsWDdfpvq+dzQSHwaWYOa6rdpdQKPV6jTwKBgFaDOtJtAfWjaPOICUGhpg3pFTxCmVFWsKK2YuYYDxxkqj2L96v9sVTXmymMFWd9hTu+bhC1RxBl3hYkyKMTmWs2JZgroDFwpg4RNRnN3zQ2XstFSZy2zw95WsNTevch7UlBf3gjQFlMiTT3JY2OC+noiAVKozOJ7f6yFB+9IIAV";
// 支付宝公钥,查看地址:https://openhome.alipay.com/platform/keyManage.htm 对应APPID下的支付宝公钥。
public static String alipay_public_key = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAtqr5LqYeUWPHhvH3fKcblxc1TacHCuB5IMsyvG+BDBSd969zq41juHHMENZ2UM1tGdrx1wdJmdKNTUAGCDKR1W3LlTJs1ZeBGew4e8KHT4v2AZPRzw5W6ua/lIG7nGmkUoTE04of1ZScNsBBIvbcfC07HWagLawIZyW5FrvRAAHE6OfefogLLKhv2a3hdQFyabxwRMiyaUW6LNK7xXPU/P1JzKnuN0Rcu5jB0jWLZXFuknZp/miUddsXVYs3rGF5tASN3h7JskCuijs/qj1tyF/1HnbpILQA2g+aRjg2zjgo50Bzqiy1qIrVu5h/msEiyfx/Wm3oQillfMbwOQ9lEwIDAQAB";
// 服务器异步通知页面路径 需http://格式的完整路径,不能加?id=123这类自定义参数,必须外网可以正常访问
public static String notify_url = "http://xxx/应用名/notify_url";
// 页面跳转同步通知页面路径 需http://格式的完整路径,不能加?id=123这类自定义参数,必须外网可以正常访问
public static String return_url = "http://xxx/应用名/return_url";
// 服务器异步通知页面路径 需http://格式的完整路径,不能加?id=123这类自定义参数,必须外网可以正常访问
//public static String notify_url = "http://xxx/应用名/pay/notify_url";//PC支付时
// 页面跳转同步通知页面路径 需http://格式的完整路径,不能加?id=123这类自定义参数,必须外网可以正常访问
//public static String return_url = "http://xxx/应用名/pay/return_url";//PC支付时
//授权回调地址
public static String auth_return_url = "http://xxx/应用名/auth_return_url";
// 签名方式
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 = "d:\\log";
//↑↑↑↑↑↑↑↑↑↑请在这里配置您的基本信息↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑
/**
* 写日志,方便测试(看网站需求,也可以改成把记录存入数据库)
* @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();
}
}
}
}
}
配置类已加上详细注解,不做过多解释,接下来是controller,集成了下单支付,异步同步回调,订单查询,账单下载,交易退款,退款查询各个接口的调用,拿过来直接用即可
package cn.mrdear.pay.controller;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import cn.mrdear.pay.alipay.AliPayConfig;
import cn.mrdear.pay.model.Orders;
import cn.mrdear.pay.service.OrderService;
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.AlipayDataDataserviceBillDownloadurlQueryRequest;
import com.alipay.api.request.AlipayTradeCloseRequest;
import com.alipay.api.request.AlipayTradeFastpayRefundQueryRequest;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.request.AlipayTradeRefundRequest;
import com.alipay.api.response.AlipayDataDataserviceBillDownloadurlQueryResponse;
import com.alipay.api.response.AlipayTradeCloseResponse;
import com.alipay.api.response.AlipayTradeFastpayRefundQueryResponse;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.alipay.api.response.AlipayTradeRefundResponse;
import com.example.util.IMoocJSONResult;
@Controller
@RequestMapping(“pay”)
public class PcPayController {
private static final Logger logger = LoggerFactory.getLogger(PcPayController.class);
@Autowired
private OrderService orderService;
/**
* 即时到账下单接口
* @param request
* @param response
* @throws AlipayApiException
* @throws IOException
*/
@RequestMapping("payOrder")
public void payOrder(HttpServletRequest req, Model mod, HttpServletResponse rep,
@RequestParam(value = "goodId", required = true)String goodId) throws AlipayApiException, IOException{
logger.debug("进入获取订单信息接口方法");
//系统下单
Orders param = new Orders();
param.setGoodId(goodId);
orderService.alipayOrder(param); //生成订单信息,根据自己项目改动
//获得初始化的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);
//商户订单号,商户网站订单系统中唯一订单号,必填
String out_trade_no = param.getTradeCode();
//付款金额,必填
String total_amount = param.getMoney().toString();
//订单名称,必填
String subject = param.getSubject();
//商品描述,可空
String body = param.getRemark();
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();
rep.setContentType("text/html;charset=" + AliPayConfig.charset);
rep.getWriter().write(result);//直接将完整的表单html输出到页面
rep.getWriter().flush();
rep.getWriter().close();
}
/**
* 同步回调路径return_url
* @param request
* @param response
* @throws AlipayApiException
* @throws UnsupportedEncodingException
*/
@RequestMapping("return_url")
public String returnUrl(HttpServletRequest request, HttpServletResponse response) throws AlipayApiException, UnsupportedEncodingException{
logger.info("进入同步回调路径return_url");
//获取支付宝POST过来反馈信息
Map<String,String> params = new HashMap<String,String>();
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);
}
//切记alipaypublickey是支付宝的公钥,请去open.alipay.com对应应用下查看。
//boolean AlipaySignature.rsaCheckV1(Map<String, String> params, String publicKey, String charset, String sign_type)
boolean signVerified = AlipaySignature.rsaCheckV1(params, AliPayConfig.alipay_public_key, AliPayConfig.charset,AliPayConfig.sign_type);
if(signVerified) {
//商户订单号
String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"),"UTF-8");
//支付宝交易号
String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"),"UTF-8");
//付款金额
String total_amount = new String(request.getParameter("total_amount").getBytes("ISO-8859-1"),"UTF-8");
request.setAttribute("out_trade_no", out_trade_no);
request.setAttribute("trade_no", trade_no);
request.setAttribute("total_amount", total_amount);
logger.info("订单处理:系统订单号" + out_trade_no + "支付宝交易号:" + trade_no);
//系统处理根据支付宝回调更改订单状态或者其他关联表的数据
Orders order = orderService.findOneByTradeCode(out_trade_no);
if(order == null){
signVerified = false;
request.setAttribute("signVerified", signVerified);
request.setAttribute("reason", "商户订单号不存在");
logger.error("系统订单:"+ out_trade_no + "不存在。");
}else{
if(!order.getMoney().toString().equals(total_amount)){
signVerified = false;
request.setAttribute("signVerified", signVerified);
request.setAttribute("reason", "付款金额不对");
return "notify_url";
}
if(order.getTradeStatus() == 1){//判断当前订单是否已处理,避免重复处理
logger.info("系统订单:"+ out_trade_no + "无需重复处理。");
}else{
order.setTradeStatus(1);//修改订单状态为已支付
Date payedAt = new Date();
order.setTransactionId(trade_no);
order.setPayedAt(payedAt);
orderService.payOrder(order);
logger.info("系统订单:"+ out_trade_no + "成功支付。");
}
}
}else{
request.setAttribute("reason", "验签失败");
}
request.setAttribute("signVerified", signVerified);
return "return_url";
}
/**
* 异步回调路径notify_url
* @param request
* @param response
* @throws AlipayApiException
* @throws UnsupportedEncodingException
*/
@RequestMapping("notify_url")
public void notifyUrl(HttpServletRequest request, HttpServletResponse response) throws AlipayApiException, UnsupportedEncodingException{
logger.info("进入异步回调路径notify_url");
//获取支付宝POST过来反馈信息
Map<String,String> params = new HashMap<String,String>();
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);
}
//切记alipaypublickey是支付宝的公钥,请去open.alipay.com对应应用下查看。
//boolean AlipaySignature.rsaCheckV1(Map<String, String> params, String publicKey, String charset, String sign_type)
boolean signVerified = AlipaySignature.rsaCheckV1(params, AliPayConfig.alipay_public_key, AliPayConfig.charset,AliPayConfig.sign_type);
if(signVerified) {
//商户订单号
String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"),"UTF-8");
//支付宝交易号
String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"),"UTF-8");
//付款金额
String total_amount = new String(request.getParameter("total_amount").getBytes("ISO-8859-1"),"UTF-8");
request.setAttribute("out_trade_no", out_trade_no);
request.setAttribute("trade_no", trade_no);
request.setAttribute("total_amount", total_amount);
logger.info("订单处理:系统订单号" + out_trade_no + "支付宝交易号:" + trade_no);
//系统处理根据支付宝回调更改订单状态或者其他关联表的数据
Orders order = orderService.findOneByTradeCode(out_trade_no);
if(order == null){
signVerified = false;
request.setAttribute("signVerified", signVerified);
request.setAttribute("reason", "商户订单号不存在");
logger.error("系统订单:"+ out_trade_no + "不存在。");
}else{
if(!order.getMoney().toString().equals(total_amount)){
signVerified = false;
request.setAttribute("signVerified", signVerified);
request.setAttribute("reason", "付款金额不对");
}
if(order.getTradeStatus() == 1){//判断当前订单是否已处理,避免重复处理
logger.info("系统订单:"+ out_trade_no + "无需重复处理。");
}else{
order.setTradeStatus(1);//修改订单状态为已支付
Date payedAt = new Date();
order.setTransactionId(trade_no);
order.setPayedAt(payedAt);
orderService.payOrder(order);
logger.info("系统订单:"+ out_trade_no + "成功支付。");
}
}
}else{
request.setAttribute("reason", "验签失败");
}
response.setContentType("text/html;charset=" + AliPayConfig.charset);
try {
response.getWriter().write("success");//直接将完整的表单html输出到页面
response.getWriter().flush();
response.getWriter().close();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 支付宝交易查询接口
* @param request
* @param response
* @throws UnsupportedEncodingException
* @throws AlipayApiException
*/
@RequestMapping("queryOrder")
@ResponseBody
public CommonResponse queryOrder(HttpServletRequest req, Model mod, HttpServletResponse rep,
@RequestParam(value = "tradeCode", required = true)String tradeCode,
@RequestParam(value = "tradeNo", required = true)String tradeNo) throws UnsupportedEncodingException, AlipayApiException{
CommonResponse cr = new CommonResponse();
AlipayClient alipayClient = new DefaultAlipayClient(AliPayConfig.gatewayUrl, AliPayConfig.app_id, AliPayConfig.merchant_private_key, "json", AliPayConfig.charset, AliPayConfig.alipay_public_key, AliPayConfig.sign_type); //获得初始化的AlipayClient
AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();//创建API对应的request类
request.setBizContent("{" +
" \"out_trade_no\":\""+tradeCode+"\"," +
" \"trade_no\":\""+tradeNo+"\"" +
" }");//设置业务参数
//根据response中的结果继续业务逻辑处理
String orderString = null;
try {
//调用查询方法
AlipayTradeQueryResponse response = alipayClient.execute(request);//通过alipayClient调用API,获得对应的response类
if(response.isSuccess()){
System.out.println("调用成功");
} else {
System.out.println("调用失败");
}
orderString = response.getBody();//就是orderString 可以直接给客户端请求,无需再做处理。
} catch (AlipayApiException e) {
e.printStackTrace();
}
cr.setData(orderString); //返回orderString
IMoocJSONResult.ok(cr);
return cr;
}
/**
* 支付宝交易退款接口
*/
@RequestMapping("refundOrder")
@ResponseBody
public void refundOrder(HttpServletRequest req,HttpServletResponse rep,
@RequestParam(value = "tradeCode")String tradeCode,
@RequestParam(value = "tradeNo")String tradeNo,
@RequestParam(value = "refundAmount", required = true)String refundAmount,
@RequestParam(value = "refundReason")String refundReason,
@RequestParam(value = "outrequestNo", required = true)String outrequestNo) throws UnsupportedEncodingException, AlipayApiException{
//获得初始化的AlipayClient
AlipayClient alipayClient = new DefaultAlipayClient(AliPayConfig.gatewayUrl, AliPayConfig.app_id, AliPayConfig.merchant_private_key, "json", AliPayConfig.charset, AliPayConfig.alipay_public_key, AliPayConfig.sign_type);
//设置请求参数
AlipayTradeRefundRequest alipayRequest = new AlipayTradeRefundRequest();
alipayRequest.setBizContent("{\"out_trade_no\":\""+ tradeCode +"\","
+ "\"trade_no\":\""+ tradeNo +"\","
+ "\"refund_amount\":\""+ refundAmount +"\","
+ "\"refund_reason\":\""+ refundReason +"\","
+ "\"out_request_no\":\""+ outrequestNo +"\"}");
//请求
AlipayTradeRefundResponse response = alipayClient.execute(alipayRequest);
if(response.isSuccess()){
System.out.println("调用成功");
} else {
System.out.println("调用失败");
}
String result = alipayClient.execute(alipayRequest).getBody();
//输出
try {
rep.getWriter().write(result);//直接将完整的表单html输出到页面
rep.getWriter().flush();
rep.getWriter().close();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 支付宝交易退款查询接口
*/
@RequestMapping("queryrefundOrder")
@ResponseBody
public void queryrefundOrder(HttpServletRequest req,HttpServletResponse rep,
@RequestParam(value = "tradeCode")String tradeCode,
@RequestParam(value = "tradeNo")String tradeNo,
@RequestParam(value = "outrequestNo", required = true)String outrequestNo) throws AlipayApiException, IOException{
//获得初始化的AlipayClient
AlipayClient alipayClient = new DefaultAlipayClient(AliPayConfig.gatewayUrl, AliPayConfig.app_id, AliPayConfig.merchant_private_key, "json", AliPayConfig.charset, AliPayConfig.alipay_public_key, AliPayConfig.sign_type);
//设置请求参数
AlipayTradeFastpayRefundQueryRequest alipayRequest = new AlipayTradeFastpayRefundQueryRequest();
alipayRequest.setBizContent("{\"out_trade_no\":\""+ tradeCode +"\","
+"\"trade_no\":\""+ tradeNo +"\","
+"\"out_request_no\":\""+ outrequestNo +"\"}");
//请求
AlipayTradeFastpayRefundQueryResponse response = alipayClient.execute(alipayRequest);
if(response.isSuccess()){
System.out.println("调用成功");
} else {
System.out.println("调用失败");
}
String result = alipayClient.execute(alipayRequest).getBody();
rep.getWriter().write(result);//直接将完整的表单html输出到页面
rep.getWriter().flush();
rep.getWriter().close();
}
/**
* 即时到账交易关闭接口
*/
@RequestMapping("tradeClose")
@ResponseBody
public void tradeClose(HttpServletRequest req,HttpServletResponse rep,
@RequestParam(value = "tradeCode")String tradeCode,
@RequestParam(value = "tradeNo")String tradeNo) throws AlipayApiException, IOException{
//获得初始化的AlipayClient
AlipayClient alipayClient = new DefaultAlipayClient(AliPayConfig.gatewayUrl, AliPayConfig.app_id, AliPayConfig.merchant_private_key, "json", AliPayConfig.charset, AliPayConfig.alipay_public_key, AliPayConfig.sign_type);
//设置请求参数
AlipayTradeCloseRequest alipayRequest = new AlipayTradeCloseRequest();
alipayRequest.setBizContent("{\"out_trade_no\":\""+ tradeCode +"\"," +"\"trade_no\":\""+ tradeNo +"\"}");
//请求
AlipayTradeCloseResponse response = alipayClient.execute(alipayRequest);
if(response.isSuccess()){
System.out.println("调用成功");
} else {
System.out.println("调用失败");
}
String result = alipayClient.execute(alipayRequest).getBody();
rep.getWriter().write(result);//直接将完整的表单html输出到页面
rep.getWriter().flush();
rep.getWriter().close();
}
/**
* 查询对账单下载地址接口
*/
@RequestMapping("tradedownloadurl")
@ResponseBody
public void tradedownloadurl(HttpServletRequest req,HttpServletResponse rep,
@RequestParam(value = "billtype")String billType,
@RequestParam(value = "billdate")String billDate) throws AlipayApiException, IOException{
//获得初始化的AlipayClient
AlipayClient alipayClient = new DefaultAlipayClient(AliPayConfig.gatewayUrl, AliPayConfig.app_id, AliPayConfig.merchant_private_key, "json", AliPayConfig.charset, AliPayConfig.alipay_public_key, AliPayConfig.sign_type);
AlipayDataDataserviceBillDownloadurlQueryRequest alipayRequest = new AlipayDataDataserviceBillDownloadurlQueryRequest();//创建API对应的request类
alipayRequest.setBizContent("{" +
" \"bill_type\":\"trade\"," +
" \"bill_date\":\""+billDate+"\"" +
" }");//设置业务参数
AlipayDataDataserviceBillDownloadurlQueryResponse response = alipayClient.execute(alipayRequest);
System.out.print(response.getBody());
String urlStr = response.getBillDownloadUrl();
downloadBillurl(urlStr);
}
/**
* 下载账单
*/
public void downloadBillurl(String urlStr){
//指定希望保存的文件路径
String filePath = "d:/logo/fund_bill_20160405.csv";
URL url = null;
HttpURLConnection httpUrlConnection = null;
InputStream fis = null;
FileOutputStream fos = null;
try {
url = new URL(urlStr);
httpUrlConnection = (HttpURLConnection) url.openConnection();
httpUrlConnection.setConnectTimeout(5 * 1000);
httpUrlConnection.setDoInput(true);
httpUrlConnection.setDoOutput(true);
httpUrlConnection.setUseCaches(false);
httpUrlConnection.setRequestMethod("GET");
httpUrlConnection.setRequestProperty("Charsert", "UTF-8");
httpUrlConnection.connect();
fis = httpUrlConnection.getInputStream();
byte[] temp = new byte[1024];
int b;
fos = new FileOutputStream(new File(filePath));
while ((b = fis.read(temp)) != -1) {
fos.write(temp, 0, b);
fos.flush();
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if(fis!=null) fis.close();
if(fos!=null) fos.close();
if(httpUrlConnection!=null) httpUrlConnection.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
到此,集成支付宝的电脑网站支付功能就集成完毕了。总结一下:
其实集成支付宝的支付很简单,基本上只要熟悉开发文档,一步步来,再加上我给出的这两段代码,基本上就可以轻松集成。
下节准备研究一下集成微信支付,微信支付貌似需要商户才能集成,个人不能够集成,这需要研究一下。