Skip to content

Instantly share code, notes, and snippets.

@ZhenhangTung
Last active November 2, 2022 06:55
Show Gist options
  • Save ZhenhangTung/89fe8b2fba62e180e443465dcfb63baa to your computer and use it in GitHub Desktop.
Save ZhenhangTung/89fe8b2fba62e180e443465dcfb63baa to your computer and use it in GitHub Desktop.
How to request JDPay's create order API using backend instead of official recommended method
# 用Ruby来写一下如何用后端请求京东支付的创建订单API,而不是用京东官方文档推荐的使用前端来组成一个Form表单,这样写的优势是能和支付宝形成统一的逻辑。
# 思路适用所有语言。
# 非官方SDK:https://github.com/jasl/wx_pay,目前我公司在使用,但有个TODO是我要修复新用户的redirect,用下面我使用的方案,之前的方案有疏漏。PR会稍后开启。
params = {
# 请按照官方文档组合
}
# url = https://h5pay.jd.com/jdpay/saveOrder or https://wepay.jd.com/jdpay/saveOrder
WEB_BASE_URL = 'https://wepay.jd.com'
H5_BASE_URL = 'https://h5pay.jd.com'
base_url = WEB_BASE_URL
base_url = H5_BASE_URL if is_mobile_pay?
url = URI.parse(url)
http = Net::HTTP.new(url.host, url.port)
http.use_ssl = true
req = Net::HTTP::Post.new(url.to_s)
req.form_data = params
req['Content-Type'] = 'application/x-www-form-urlencoded'
resp = http.request(req)
# 如下是核心,请求京东的支付接口会有302跳转,因此我们可以通过抓取header来获取redirect url,返回给前端
# 但有个痛点是,经过我多次的测试,京东支付返回的header并不统一,并不会都返回完整的URL,因此需要做很多判断来弥补。 @JD的开发同学们,看看能否统一
#
# Examples:
# https://h5pay.jd.com/jdpay/payCashier?tradeNum=xxxx&orderId=xxxx&key=xxx
# payCashier?tradeNum=xxx&ourTradeNum=xxx&key=xxx
# It also could be /jdpay/payCashier?tradeNum=xxx&ourTradeNum=xxxxx&key=xxxx
# Another case could be: login?key=xxxxx or /jdpay/login?tradeNum=xxxx&orderId=xxx&key=xxxx. This is a case that a new user to JDPay, which will require a user to login
redirect_location = resp['location']
# full redirect url
if redirect_location.start_with? base_url
return redirect_location
end
# if location starts with /jdpay, we don't need to add /jdpay to url anymore
if redirect_location.start_with? '/jdpay'
return "#{base_url}#{redirect_location}"
end
"#{base_url}/jdpay/#{redirect_location}"
# 返回给前端,前端redirect到这个URL即可
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment