首先如标题,本文章详细讲解支付宝当面付的下单(alipay.trade.precreate),基于原生java,不依赖官方SDK,虽然官方sdk包可能功能比较全,但是往往你用不到里面所有的功能,且不好理解里面的代码(也没时间细看),不如通过自己亲自手写,按需实现各个接口的功能。
先看下官方扫码支付api列表支付宝开放平台文档

打开alipay.trade.precreate(统一收单线下交易预创建),通常第三方api接口参数分为公共参数和请求参数,公共参数的申请和获取这里就不作详解,如不懂获取的可以评论留言。我会给大家一一解答。
开发前先读一遍文档,熟悉哪些参数必输,了解下参数的格式等,下面进入正题。
1、组装公共参数
Map commonMap = this.initCommon("alipay.trade.precreate", callBack + onlineOrder.getChannelId());
private Map initCommon(String method, String notifyUrl) { Map commonMap = new HashMap<>(16); commonMap.put("app_id", "201610250*******"); commonMap.put("method", method); commonMap.put("charset", "utf-8"); commonMap.put("sign_type", "RSA2"); // yyyy-MM-dd HH:mm:ss commonMap.put("timestamp", DateUtils.formatByDateTimePattern()); commonMap.put("version", "1.0"); // 接收异步通知的地址 commonMap.put("notify_url", notifyUrl); return commonMap; }
appId这里打了马赛克,method就是你需要执行的支付宝接口方法,charset字符编码,sign_type签名方式,timestamp时间戳,version版本号,notify_url异步通知地址(没有的话可以不传)。
2、biz_content内容参数组织
Map bizContent = new HashMap<>(16); bizContent.put("out_trade_no", onlineOrder.getId()); bizContent.put("total_amount", onlineOrder.getAmount()); bizContent.put("subject", onlineOrder.getGoodsName()); bizContent.put("body", onlineOrder.getGoodsName());
之后我们将biz_content内容添加到公共参数的map中
commonMap.put("biz_content", JSON.toJSONString(bizContent));
3、排序拼接参数为之后的签名做准备
String paramStr = StringUtils.alipaySortParam(commonMap);
public static String alipaySortParam(Map paraMap) { List> list = new ArrayList<>(paraMap.entrySet()); list.sort(Comparator.comparing(o -> (o.getKey()))); StringBuilder buf = new StringBuilder(); int i = list.size(); int j = 1; for (Map.Entry item : list) { if (StringUtils.isNotBlank(item.getValue())) { buf.append(item.getKey()).append("=").append(item.getValue()); if (i != j) { buf.append("&"); } } j++; } return buf.toString(); }
4、接下来rsa签名
commonMap.put("sign", RsaUtils.sign(privateKey, paramStr));
public static String sign(String key, String requestData) { String signature = null; byte[] signed = null; try { PrivateKey privateKey = getPrivateKey(key); Signature Sign = Signature.getInstance(SIGNATURE_ALGORITHM); Sign.initSign(privateKey); Sign.update(requestData.getBytes()); signed = Sign.sign(); signature = Base64.getEncoder().encodeToString(signed); } catch (Exception e) { log.error("Exception", e); } return signature; }
将签名参数添加到公共参数commonMap中,接下来就可以请求支付宝网关地址发送请求罗。
5、发送http请求
String result = OkHttp.doPost(gatewayUrl, commonMap);
这里我使用okhttp工具类发送,需要这个工具类的可以私信。
顺便上一个支付成功的截图(如下)

如果给你带来帮助,请帮忙转发留言吧,闲时分享心得。
版权声明:本文为weixin_42554151原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。