如何使用Python正确调用Steam InitTxn?
我正在为我的Steam游戏进行应用内购买。在我的服务器上,我使用的是Python 3。我尝试进行一个HTTPS请求,代码如下:
conn = http.client.HTTPSConnection("partner.steam-api.com")
orderid = uuid.uuid4().int & (1<<64)-1
print("orderid = ", orderid)
key = "xxxxxxxxxxxxxxxxxxx" # omitted for security reason
steamid = "xxxxxxxxxxxxxxxxxxx" # omitted for security reason
pid = "testItem1"
appid = "480"
itemcount = 1
currency = 'CNY'
amount = 350
description = 'testing_description'
urlSandbox = "/ISteamMicroTxnSandbox/"
s = f'{urlSandbox}InitTxn/v3/?key={key}&orderid={orderid}&appid={appid}&steamid={steamid}&itemcount={itemcount}¤cy={currency}&itemid[0]={pid}&qty[0]={1}&amount[0]={amount}&description[0]={description}'
print("s = ", s)
conn.request('POST', s)
r = conn.getresponse()
print("InitTxn result = ", r.read())
我在控制台检查了s,结果是:
s = /ISteamMicroTxnSandbox/InitTxn/v3/?key=xxxxxxx&orderid=11506775749761176415&appid=480&steamid=xxxxxxxxxxxx&itemcount=1¤cy=CNY&itemid[0]=testItem1&qty[0]=1&amount[0]=350&description[0]=testing_description
但是我收到了一个错误的请求响应:
InitTxn result = b"<html><head><title>Bad Request</title></head><body><h1>Bad Request</h1>Required parameter 'orderid' is missing</body></html>"
该怎么解决这个问题呢?谢谢!
顺便说一下,我几乎是用同样的方法来调用GetUserInfo,只是更改了参数,并把POST请求换成了GET请求,这样是可以正常工作的。
我刚刚了解到应该把参数放在POST请求里。所以我把代码改成了如下,但仍然收到“缺少必需的参数'orderid'”的错误。
params = {
'key': key,
'orderid': orderid,
'appid': appid,
'steamid': steamid,
'itemcount': itemcount,
'currency': currency,
'pid': pid,
'qty[0]': 1,
'amount[0]': amount,
'description[0]': description
}
s = urllib.parse.urlencode(params)
# In console: s = key=xxxxx&orderid=9231307508782239594&appid=480&steamid=xxx&itemcount=1¤cy=CNY&pid=testItem1&qty%5B0%5D=1&amount%5B0%5D=350&description%5B0%5D=testing_description
print("s = ", s)
conn.request('POST', url=f'{urlSandbox}InitTxn/v3/', body=s)
==== 更新 ====
格式问题已经解决。请看下面的答案。
1 个回答
0
我在请求头中漏掉了content-type
这一部分,还有语言设置。另外,itemid应该是uint32类型。
最后的代码示例:
conn = http.client.HTTPSConnection("partner.steam-api.com")
headers = {'Content-Type': 'application/x-www-form-urlencoded'}
orderid = uuid.uuid4().int & (1<<64)-1
print("orderid = ", orderid)
key = "xxxxxxxxxxxxxxxxxxx" # omitted for security reason
steamid = "xxxxxxxxxxxxxxxxxxx" # omitted for security reason
itemid = 100001
appid = "480"
itemcount = 1
currency = 'CNY'
amount = 350
language = 'zh-CN'
description = 'testing_description'
urlSandbox = "/ISteamMicroTxnSandbox/"
s = f'key={key}&orderid={orderid}&appid={appid}&steamid={steamid}&itemcount={itemcount}&language={language}¤cy={currency}&itemid[0]={itemid}&qty[0]={1}&amount[0]={amount}&description[0]={description}'
conn.request('POST', url=f'{urlSandbox}InitTxn/v3/', headers=headers, body=s)
r = conn.getresponse()
print("InitTxn result = ", r.read())