一.支付宝
1.1申请应用
在蚂蚁金服申请一个app应用
1.1.1按照文档申请应用
- 支付宝配置类.
public class AlipayConfig {
//商家账号sqqpls0340@sandbox.com
//商户UID2088102177177706
//登录密码111111
//1.商户appid
//沙箱
//public static String APPID = "2016092300579934";
// public static String APPID = "2088102177177706";
public static String APPID = "2016092500591638";
//2.私钥 pkcs8格式的
//沙箱
// public static String RSA_PRIVATE_KEY ="MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQDOhHLgvX+iEekYcJfV8Ewxy2JruNdInft1btuS9cCsB/Ou7HfZd+dSAU6jJOmbMwnaBKJLpiH3tEnXeS0ISAkj00SE0cl+mZfdDheB2Y33J/5cpsj+Yy8SXVMqDmhFc9eNIcnmUrKkwgYWKGSjygy4FQbCNajJeidq5cwbzSR4niJdAvDzv0KXwJzovY7tTahpJyNBGi6oed4yzRqgVyA5mKFfLYZAvdP1GqkR97wWa8qWPiZpIfrV1RlfZFNfao3DCM6LYU/hD/Hq00vYLHMd1QepistWZTLXTJFVvY5jEFTLMd84xQwRFxBo2F7fQo2U7lZVBi7u5I+bBCXMlvOZAgMBAAECggEAeHTE1NVzJsMvpLO3vG+m4bxxscdkutR7IWoB5Nw2/6C7wCHpXg0T/b8JcRtMrtu8OVBOobVLRsH/+BCT9aqeuii2ZIpA7vkDnUpk57ZPmgPX147o2YhcomeQ5Iz2wNvqtEUrEI7X6EXLaw0wdmCZvp11Db5irvHzH+TdgrHLPhZhyjQwVXdSqxMqfaO97hu41sgJYlbwUhZz2okHCoWDrJOpoFRI1Owmo6FdSXC1xED91MwP7mXYaQDmyq0exlmPC35ahFchtvkdT/M2wqjCBrWVnXYV7pu5FgyoEGdEZS2UpxzSNLFdy2bzhbSp9oWnsgBspoJ250MXaY5OeJ2aoQKBgQD1EtHNqoWb0oAKUWrH21G0p49T2/BU0Yke+wXbm1Zzv6uH+6OeMT41hGGIK20yXqhJRn1DYPXl3+PuRRwd2R02e6LIVGqDnIGEvDs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ULhvfWwX2WbhD1e2SvjhF0311G02tz9JtxYEjj1PRWcIVZyCZWYV9zFPfsktnu4A209nDZHM3ULHkaNq2nfAKp135/uswpsSmTymNvE5A8ar9WkHkcynOiIlwGf+bSchOrhVs6rNMnxiGAQas9qI9ldBBn8NBoAaSRHhjqi2vlWHYAvGtrVZdc+fYGIda4VqQIDAQAB";
// public static String ALIPAY_PUBLIC_KEY = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAiQ3tw+Q+eHwnRUk+elBKtjnEXnr2wCGTehMT6PrpDGP4KguKDXcllOPLiM1rVG1W//Bwra5I0wQdDcoiArFRkuTw1stOZ3dHdEJvOtvpCPeqAX2QrX2uCNllvEU8wPrINAPC+/MrIzQyXZWn6TjstAQtUuQ5VsZdnnenVedKYS8flxtN/hpO6v6ZRHEfo2emGwNWCfMIDq85FTpUGTvUMW/HzVY6fcoD4ciUi2kazkL9cp5F5VQnpQUQGV03PRbOFMBwd3Qak0vX6GU1R5NOM8VsQdQPxM9ckH869HcSLOitKKMw48Qf/XAZH0nuSGqP73JKy3kic7XWHTt9HPHMUwIDAQAB";
public static String ALIPAY_PUBLIC_KEY = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAtpkqE+FuRC1DMJ6Frw6QJy5gOHjme8RIHbRu7jEigGXqxcyOAT7yChk6bgd9ukjB6bLgGLArXRtDLD4Ch+hfH7jRvKSSxWLRQjafzO8ko5txNyCoDNemSXTy7x769IUnFgVa6hVOXbRQLFeCDNqPj5n3E8r7JT2JsSsAOTSyv5lkkKO1V2MxKW6gHdTAdlDXYjwRyUdYZouYvpluH1SR1kAOdt+LydE0o9Upb4mBHZLrT7K/3gUDNG2qUxKCsUFcL98hrH2ipuSDqSJV9yGgpLV6b0oRX/OXrGvg4OdY4svukZpgtTPFJV/Aw+aX7SGIwr+LkD9h0ahMHDI29F0uJQIDAQAB";
// 4.服务器异步通知页面路径 需http://或者https://格式的完整路径,不能加?id=123这类自定义参数,必须外网可以正常访问
// public static String notify_url = "http://192.168.0.128:7001/gen/app/notify_url.do";
public static String notify_url = "http://47.97.173.149:80/gen/app/notify_url";
//5.页面跳转同步通知页面路径 需http://或者https://格式的完整路径,不能加?id=123这类自定义参数,必须外网可以正常访问 商户可以自定义同步跳转地址
public static String return_url = "http://www.baidu.com"; //支付成功后返回的页面
// 6.请求支付宝的网关地址
// public static String URL = "https://openapi.alipay.com/gateway.do";
public static String URL = "https://openapi.alipaydev.com/gateway.do"; //沙箱环境
// 7.编码
public static String CHARSET = "utf-8";
// 8.返回格式
public static String FORMAT = "json";
// 9.加密类型
public static String SIGNTYPE = "RSA2";
}
1.1.2 后台方法
/**
* 获取支付宝加签后台的订单信息字符串
* golds 需要付的钱,giveGolds:得到的金币
*
* @param
* @return
*/
@RequestMapping(value = "alipay", method = RequestMethod.POST)
public String getAliPayOrderStr(HttpServletRequest request, HttpServletResponse response, String uid, String golds, String giveGolds, String loginName, String ispc) {
//最终返回加签之后的,app需要传给支付宝app的订单信息字符串
String orderString = "";
//生成订单编号(纳秒数+登录名后4位)
String orderId = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + (int) System.nanoTime() + loginName.substring(loginName.length() - 4, loginName.length());
//创建订单信息(业务数据)
OrderManage record = new OrderManage();
record.setId(orderId);
record.setUserId(uid);
record.setCreateTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
record.setCoinNumber(Integer.parseInt(giveGolds));
record.setGiveCoin(0);
record.setOrderCoin(Integer.parseInt(golds));
record.setOrderType("1");//0是 微信 1是支付宝
record.setOrderDetail("未付款");
record.setIspc(ispc); // 是否购买pc端服务 0:否 ,1:是
try {
//实例化客户端(参数:网关地址、商户appid、商户私钥、格式、编码、支付宝公钥、加密类型),为了取得预付订单信息
AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.URL, AlipayConfig.APPID,
AlipayConfig.RSA_PRIVATE_KEY, AlipayConfig.FORMAT, AlipayConfig.CHARSET,
AlipayConfig.ALIPAY_PUBLIC_KEY, AlipayConfig.SIGNTYPE);
//实例化具体API对应的request类,类名称和接口名称对应,当前调用接口名称:alipay.trade.app.pay
AlipayTradeAppPayRequest ali_request = new AlipayTradeAppPayRequest();
//SDK已经封装掉了公共参数,这里只需要传入业务参数。以下方法为sdk的model入参方式
AlipayTradeAppPayModel model = new AlipayTradeAppPayModel();
//业务参数传入,可以传很多,参考API
//model.setPassbackParams(URLEncoder.encode(request.getBody().toString())); //公用参数(附加数据)
model.setBody("具体描述"); //对一笔交易的具体描述信息。如果是多种商品,请将商品描述字符串累加传给body。
model.setSubject("购买金币"); //商品名称
model.setOutTradeNo(orderId); //商户订单号(自动生成)
// model.setTimeoutExpress("30m"); //交易超时时间
model.setTotalAmount(golds); //支付金额
model.setProductCode("QUICK_MSECURITY_PAY"); //销售产品码(固定值)
ali_request.setBizModel(model);
ali_request.setNotifyUrl(AlipayConfig.notify_url); //异步回调地址(后台)
ali_request.setReturnUrl(AlipayConfig.return_url); //同步回调地址(APP)
// 这里和普通的接口调用不同,使用的是sdkExecute
AlipayTradeAppPayResponse alipayTradeAppPayResponse = alipayClient.sdkExecute(ali_request); //返回支付宝订单信息(预处理)
orderString = alipayTradeAppPayResponse.getBody();//就是orderString 可以直接给APP请求,无需再做处理。
orderManageService.insertSelective(record);//创建新的商户支付宝订单
logger.info("orderString:"+orderString);
} catch (AlipayApiException e) {
e.printStackTrace();
logger.info("与支付宝交互出错,未能生成订单,请检查代码!");
}
return orderString;
}
/**
* 支付宝支付成功后.异步请求该接口
*
* @param request
* @return
* @throws IOException
*/
@RequestMapping(value = "notify_url", method = RequestMethod.POST)
@ResponseBody
public String notify(HttpServletRequest request, HttpServletResponse response) throws IOException {
logger.info("==================支付宝异步返回支付结果开始");
//1.从支付宝回调的request域中取值
//获取支付宝返回的参数集合
Map<String, String[]> aliParams = request.getParameterMap();
logger.info("=========支付宝参数集合=========:" + aliParams);
//用以存放转化后的参数集合
Map<String, String> conversionParams = new HashMap<String, String>();
for (Iterator<String> iter = aliParams.keySet().iterator(); iter.hasNext(); ) {
String key = iter.next();
String[] values = aliParams.get(key);
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"), "uft-8");
conversionParams.put(key, valueStr);
}
logger.info("==================返回参数集合:" + conversionParams);
String status = this.alinotify(conversionParams);
return status;
}
/**
* 支付宝异步请求逻辑处理
*
* @param
* @return
* @throws IOException
*/
public String alinotify(Map<String, String> conversionParams) {
logger.info("==================支付宝异步请求逻辑处理");
//签名验证(对支付宝返回的数据验证,确定是支付宝返回的)
boolean signVerified = false;
try {
//调用SDK验证签名
signVerified = AlipaySignature.rsaCheckV1(conversionParams, AlipayConfig.ALIPAY_PUBLIC_KEY, AlipayConfig.CHARSET, AlipayConfig.SIGNTYPE);
logger.info("=========验签结果========="+signVerified);
} catch (AlipayApiException e) {
logger.info("==================验签失败 !");
e.printStackTrace();
}
//对验签进行处理
if (signVerified) {
//验签通过
logger.info("==================验签通过");
//获取需要保存的数据
String appId = conversionParams.get("app_id");//支付宝分配给开发者的应用Id
String notifyTime = conversionParams.get("notify_time");//通知时间:yyyy-MM-dd HH:mm:ss
String gmtCreate = conversionParams.get("gmt_create");//交易创建时间:yyyy-MM-dd HH:mm:ss
String gmtPayment = conversionParams.get("gmt_payment");//交易付款时间
String gmtRefund = conversionParams.get("gmt_refund");//交易退款时间
String gmtClose = conversionParams.get("gmt_close");//交易结束时间
String tradeNo = conversionParams.get("trade_no");//支付宝的交易号
String outTradeNo = conversionParams.get("out_trade_no");//获取商户之前传给支付宝的订单号(商户系统的唯一订单号)
String outBizNo = conversionParams.get("out_biz_no");//商户业务号(商户业务ID,主要是退款通知中返回退款申请的流水号)
String buyerLogonId = conversionParams.get("buyer_logon_id");//买家支付宝账号
String sellerId = conversionParams.get("seller_id");//卖家支付宝用户号
String sellerEmail = conversionParams.get("seller_email");//卖家支付宝账号
String totalAmount = conversionParams.get("total_amount");//订单金额:本次交易支付的订单金额,单位为人民币(元)
String receiptAmount = conversionParams.get("receipt_amount");//实收金额:商家在交易中实际收到的款项,单位为元
String invoiceAmount = conversionParams.get("invoice_amount");//开票金额:用户在交易中支付的可开发票的金额
String buyerPayAmount = conversionParams.get("buyer_pay_amount");//付款金额:用户在交易中支付的金额
String tradeStatus = conversionParams.get("trade_status");// 获取交易状态
logger.info("========交易状态=========="+tradeStatus);
//支付宝官方建议校验的值(out_trade_no、total_amount、sellerId、app_id)
logger.info("========订单号:=========="+outTradeNo);
OrderManage order = orderManageService.selectByPrimaryKey1(outTradeNo);//获取订单信息
logger.info("========订单信息:=========="+order);
logger.info("========订单金额:=========="+totalAmount);
logger.info("========商户appid:=========="+appId);
float totalAmountFloat = Float.parseFloat(totalAmount);
float orderCoinFloat = Float.parseFloat(order.getOrderCoin().toString());
logger.info("========totalAmountFloat=========="+totalAmountFloat);
logger.info("========orderCoinFloat=========="+orderCoinFloat);
if (order != null && totalAmountFloat == orderCoinFloat && AlipayConfig.APPID.equals(appId)) {
//修改数据库支付宝订单表(因为要保存每次支付宝返回的信息到数据库里,以便以后查证)
String golds = userService.getCoinCount(order.getUserId());//获得用户之前的金币数
OrderManage record = new OrderManage();
record.setId(outTradeNo);
// record.setOrderDetail("交易成功");
record.setOrderStatus("0");
int coins = Integer.parseInt(golds) + order.getCoinNumber() + order.getGiveCoin();
record.setAfterCoin(coins);
switch (tradeStatus) // 判断交易结果
{
case "TRADE_FINISHED": // 交易结束并不可退款
record.setOrderDetail("交易结束并不可退款");
break;
case "TRADE_SUCCESS": // 交易支付成功
record.setOrderDetail("交易支付成功");
break;
case "TRADE_CLOSED": // 未付款交易超时关闭或支付完成后全额退款
record.setOrderDetail("未付款交易超时关闭或支付完成后全额退款");
break;
case "WAIT_BUYER_PAY": // 交易创建并等待买家付款
record.setOrderDetail("交易创建并等待买家付款");
break;
default:
break;
}
int returnResult = orderManageService.updateByPrimaryKeySelective(record); //更新交易表中状态
if (tradeStatus.equals("TRADE_SUCCESS")) { //只处理支付成功的订单: 修改交易表状态,支付成功
logger.info("========支付成功==========");
if (returnResult > 0) {
if(order.getIspc()!=null&&order.getIspc().equals("1")){ //购买pc端服务
//新增通知信息
Notice notice = new Notice();
notice.setId(UUID.randomUUID().toString().replace("-", ""));
notice.setUserId(order.getUserId());
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
notice.setCreateDate(df.format(new Date()));
notice.setStatus("0");
notice.setAdminStatus("0");
notice.setType("1");
//UserUtils us = new UserUtils();
//User user = us.get(order.getUserId());
User user = userService.selectByPrimaryKey(order.getUserId());
logger.info("========用户对象==========="+user);
notice.setAdminMessage(user.getName()+"已购买pc端服务,请为他开通权限!");
notice.setPersonMessage("您已购买pc端服务,若未开通,请与管理员联系.");
noticeService.insertNotice(notice);
}
userService.updateUserCoin(order.getUserId(), coins + "");//更新用户的金币数
CoinInfo info = new CoinInfo();
info.setId(UUID.randomUUID().toString().replace("-", ""));
info.setUserId(order.getUserId());
info.setDelFlag("0");
info.setNumber("+" + (order.getCoinNumber() + order.getGiveCoin()));
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
info.setTime(df.format(new Date()));
info.setTitle(GoldRule.USER_GET);
info.setContent(GoldRule.USER_PAYSHOP);
userCoinService.insertSelective(info);//新增金币详情
logger.info("========新增金币详情==========");
return "success";
} else {
return "fail";
}
} else {
return "fail";
}
} else {
logger.info("==================支付宝官方建议校验的值(out_trade_no、total_amount、app_id),不一致!返回fail");
return "fail";
}
} else { //验签不通过
logger.info("==================验签不通过 !");
return "fail";
}
}
/**
* 向支付宝发起订单查询请求
*
* @param
* @return
* @throws IOException
*/
@RequestMapping(value = "/checkAlipay", method = RequestMethod.POST)
public String checkAlipay(String outTradeNo) {
System.out.println("==================向支付宝发起查询,查询商户订单号为:" + outTradeNo);
try {
//实例化客户端(参数:网关地址、商户appid、商户私钥、格式、编码、支付宝公钥、加密类型)
AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.URL, AlipayConfig.APPID,
AlipayConfig.RSA_PRIVATE_KEY, AlipayConfig.FORMAT, AlipayConfig.CHARSET,
AlipayConfig.ALIPAY_PUBLIC_KEY, AlipayConfig.SIGNTYPE);
AlipayTradeQueryRequest alipayTradeQueryRequest = new AlipayTradeQueryRequest();
alipayTradeQueryRequest.setBizContent("{" +
"\"out_trade_no\":\"" + outTradeNo + "\"" +
"}");
AlipayTradeQueryResponse alipayTradeQueryResponse = alipayClient.execute(alipayTradeQueryRequest);
if (alipayTradeQueryResponse.isSuccess()) {
OrderManage order = orderManageService.selectByPrimaryKey1(outTradeNo);//获取订单信息
//修改数据库支付宝订单表
String golds = userService.getCoinCount(order.getUserId());//获得用户之前的金币数
order.setId(alipayTradeQueryResponse.getTradeNo());//订单id
order.setOrderStatus("0");
int coins = Integer.parseInt(golds) + order.getCoinNumber() + order.getGiveCoin();
order.setAfterCoin(coins);
order.setOrderCoin(Integer.parseInt(alipayTradeQueryResponse.getTotalAmount()));//订单金额
switch (alipayTradeQueryResponse.getTradeStatus()) // 判断交易结果
{
case "TRADE_FINISHED": // 交易结束并不可退款
order.setOrderDetail("交易结束并不可退款");
break;
case "TRADE_SUCCESS": // 交易支付成功
order.setOrderDetail("交易支付成功");
break;
case "TRADE_CLOSED": // 未付款交易超时关闭或支付完成后全额退款
order.setOrderDetail("未付款交易超时关闭或支付完成后全额退款");
break;
case "WAIT_BUYER_PAY": // 交易创建并等待买家付款
order.setOrderDetail("交易创建并等待买家付款");
break;
default:
break;
}
orderManageService.updateByPrimaryKeySelective(order); //更新表记录
return order.getOrderDetail();
} else {
System.out.println("==================调用支付宝查询接口失败!");
}
} catch (AlipayApiException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "0";
}