您的位置:首页 > 编程语言 > Java开发

java对接支付宝(一)-即时到账支付

2018-01-25 11:52 585 查看

一、前期准备工作

1、与支付宝签订有效合同,并被支付宝审批通过。

2、下载支付宝需要的工具包,可以在支付宝官网下载,也可以下载我提供的,地址:点击打开链接

3、把下载的工具包解压,放入项目中。

二、配置信息

1、创建一个alipay_config.properties文件

#################################################  \u652F\u4ED8\u5B9D\u5206\u9875\u67E5\u8BE2\u8D26\u5355\u914D\u7F6E  #####################################################

partner=*****************

key=*********************

alipay_gateway_new=https\://mapi.alipay.com/gateway.do?

sign_type=MD5

log_path=C\:\\

input_charset=utf-8

seller_id=*****************

https_verify_url=https\://mapi.alipay.com/gateway.do?service\=notify_verify&

notify_url=http://192.168.3.65:8080/fwas.pay.web/payNotify/notify/ALIPAY

return_url=http://192.168.3.65:8080/fwas.pay.web/payNotify/result/ALIPAY

payment_type=1

service=create_direct_pay_by_user

refund_notify_url=http://192.168.3.65:8080/fwas.pay.web/payNotify/refundNotify/REFUND

dback_notify_url=http://192.168.3.65:8080/fwas.pay.web/payNotify/dbackNotify/REFUND

accountDir = D:/account
2、这里展示一下AlipayConfigUtil.java文件,工具包里面有

package com.foriseland.fsoa.pay.alipay.config;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.io.IOException;
import java.util.Properties;

/**
*类名:AlipayConfigUtil
*功能:基础配置类
*详细:设置帐户有关信息及返回路径
*/
public class AlipayConfigUtil {

private static final Log LOG = LogFactory.getLog(AlipayConfigUtil.class);

/**
* 通过静态代码块读取上传文件的验证格式配置文件,静态代码块只执行一次(单例)
*/
private static Properties properties = new Properties();

/** 私有构造方法 **/
private AlipayConfigUtil(){}

static{
try {
// 从类路径下读取属性文件
properties.load(AlipayConfigUtil.class.getClassLoader().getResourceAsStream("alipay_config.properties"));
} catch (IOException e) {
LOG.error(e);
}
}

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

// 支付宝网关
public static final String alipay_gateway_new = (String) properties.get("alipay_gateway_new");

// 合作身份者ID,签约账号,以2088开头由16位纯数字组成的字符串,查看地址:https://b.alipay.com/order/pidAndKey.htm
public static final String partner = (String) properties.get("partner");

// 收款支付宝账号,以2088开头由16位纯数字组成的字符串,一般情况下收款账号就是签约账号
public static final String seller_id = (String) properties.get("seller_id");

// MD5密钥,安全检验码,由数字和字母组成的32位字符串,查看地址:https://b.alipay.com/order/pidAndKey.htm
/*public static final String key = (String) properties.get("key");*/
public static String key = (String) properties.get("key");

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

// 页面跳转同步通知页面路径 需http://格式的完整路径,不能加?id=123这类自定义参数,必须外网可以正常访问
public static final String return_url = (String) properties.get("return_url");

// 签名方式
public static final String sign_type = (String) properties.get("sign_type");

// 调试用,创建TXT日志文件夹路径,见AlipayCore.java类中的logResult(String sWord)打印方法。
public static final String log_path = (String) properties.get("log_path");

// 字符编码格式 目前支持 gbk 或 utf-8
public static final String input_charset = (String) properties.get("input_charset");

// 支付类型 ,无需修改
public static final String payment_type = (String) properties.get("payment_type");

// 调用的接口名,无需修改
public static final String service = (String) properties.get("service");

// 退款异步通知地址
public static final String refund_notify_url = (String) properties.get("refund_notify_url");

// 充值异步通知地址
public static final String dback_notify_url = (String) properties.get("dback_notify_url");

// 账单保存路径
public static final String accountDir = (String) properties.get("accountDir");

// 获取key
public static void getKeyData(String strKey){
key = strKey;
}

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

//↓↓↓↓↓↓↓↓↓↓ 请在这里配置防钓鱼信息,如果没开通防钓鱼功能,为空即可 ↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓

// 防钓鱼时间戳  若要使用请调用类文件submit中的query_timestamp函数
public static final String anti_phishing_key = "";

// 客户端的IP地址 非局域网的外网IP地址,如:221.0.0.1
public static final String exter_invoke_ip = "";

//↑↑↑↑↑↑↑↑↑↑请在这里配置防钓鱼信息,如果没开通防钓鱼功能,为空即可 ↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑

}

三、代码实现

3、jsp页面展示

<!-- 支付宝 -->
<form id="submitFormAlipay"  class="alipayform" method="POST" target="_blank">
<input id="orderNo" name="orderNo" type="hidden" value="1510795680804" />
<input id="orderAmount" name="orderAmount" type="hidden" value="0.01" />
<input id="productName" name="productName" type="hidden" value="测试" />
</form>
<input type="button" class="subbtn" onclick="javascript:doPayMoney();" value ="立即支付">
<script type="text/javascript">
 function doPayMoney(){
    $("#submitFormAlipay").attr("action","<%=basePath%>/scanPay/alipayInitPay.do").submit();
 }
</script>
4、Controller层发起支付

/**
* @Description: pc支付宝支付
* @author lc
*/
@RequestMapping("/alipayInitPay")
public void alipayInitPay(HttpServletRequest request,HttpServletResponse response) {
try {
// 订单号
String orderNo = request.getParameter("orderNo");
// 订单金额
String orderAmount = request.getParameter("orderAmount");
// 订单商品名称
String productName = request.getParameter("productName");

// 把请求参数打包成数组
Map<String, String> sParaTemp = new HashMap<>();
sParaTemp.put("service", AlipayConfigUtil.service);
sParaTemp.put("partner", AlipayConfigUtil.partner);
sParaTemp.put("seller_id", AlipayConfigUtil.seller_id);
sParaTemp.put("_input_charset", AlipayConfigUtil.input_charset);
sParaTemp.put("payment_type", AlipayConfigUtil.payment_type);
sParaTemp.put("notify_url", AlipayConfigUtil.notify_url);
sParaTemp.put("return_url", AlipayConfigUtil.return_url);
sParaTemp.put("anti_phishing_key", AlipayConfigUtil.anti_phishing_key);
sParaTemp.put("exter_invoke_ip", AlipayConfigUtil.exter_invoke_ip);
sParaTemp.put("out_trade_no", orderNo);
sParaTemp.put("subject", productName);
sParaTemp.put("total_fee", orderAmount);
//            sParaTemp.put("body", body);
sParaTemp.put("qr_pay_mode", "2");
// 建立支付请求
String form = AlipaySubmit.buildRequest(sParaTemp, "get", "确认");
response.setContentType("text/html;charset=" + AlipayConfigUtil.input_charset);
// 直接将完整的表单html输出到页面
response.getWriter().write(form);
response.getWriter().flush();
response.getWriter().close();
} catch (IOException e) {
logger.error("生成订单失败(AliPay):" + e.getMessage());
e.printStackTrace();
}
}
5、支付成功后同步通知
/**
* pc支付宝同步通知
* @param payWayCode
* @param httpServletRequest
* @param model
* @return
* @throws Exception
*/
@RequestMapping("/result/{payWayCode}")
public String result(@PathVariable("payWayCode") String payWayCode, HttpServletRequest httpServletRequest , Model model) throws Exception {
Map<String,String> resultMap = new HashMap<String,String>();
Map requestParams = httpServletRequest.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] + ",";
}
//乱码解决,这段代码在出现乱码时使用。如果mysign和sign不相等也可以使用这段代码转化
valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
//支付宝账号
valueStr = new String(valueStr);
resultMap.put(name, valueStr);
}
if(AlipayNotify.verify(resultMap)) {
logger.debug("支付宝签名成功返回结果:" + resultMap);
}else {
logger.debug("支付宝签名失败返回结果:" + resultMap);
}
// 页面成功提示
return "gateway";
}

6、支付成功后异步通知

/** pc支付宝支付异步通知
* @param payWayCode
* @param httpServletRequest
* @param httpServletResponse
* @throws Exception
*/
@RequestMapping("/notify/{payWayCode}")
public void notify(@PathVariable("payWayCode")String payWayCode , HttpServletRequest httpServletRequest , HttpServletResponse httpServletResponse) throws Exception {
String encoding ="";
String str = "fail";
Map<String , String> notifyMap = new HashMap<String , String >();
Map<String, String[]> requestParams = httpServletRequest.getParameterMap();
notifyMap = this.parseNotifyMsg(requestParams);
// 1、签名
if(AlipayNotify.verify(resultMap)) {
// 异步通知业务操作
str = "success";
// 回馈信息
httpServletResponse.getWriter().print(str);
}else {
logger.debug("签名失败返回结果:" + notifyMap);
}
}

7、解析支付宝发来的请求

/**
* @Description: 解析支付宝发来的请求
* @author lc
* @param requestParams
* @param
*/
public static Map<String , String> parseNotifyMsg(Map<String, String[]> requestParams){
Map<String,String> params = new HashMap<String,String>();
for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) {
String name = (String) iter.next();
String[] values = 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);
}
return params;
}
注意:通知的时候需要注意,同步通知只做页面跳转提示,异步通知做自己的业务处理,异步通知业务处理成功后回馈success即可,失败可以不用处理。

支付宝即时到账至此结束,下期在更新其他,有不对的地方,不明白的地方,尽可提出,一起改善和进步。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: