curl 요청을 Python 요청 호출로 변환하는 데 문제가 있습니다.
다음은 curl 호출이 어떻게 생겼는지입니다 : (출처 : http://developers.payu.com/en/restapi.html#creating_new_order_api )
curl -X POST https://secure.payu.com/api/v2_1/orders \
-H "Content-Type: application/json" \
-H "Authorization: Bearer 3e5cac39-7e38-4139-8fd6-30adc06a61bd" \
-d '{
"notifyUrl": "https://your.eshop.com/notify",
"customerIp": "127.0.0.1",
"merchantPosId": "145227",
"description": "RTV market",
"currencyCode": "PLN",
"totalAmount": "21000",
"products": [
{
"name": "Wireless Mouse for Laptop",
"unitPrice": "15000",
"quantity": "1"
},
{
"name": "HDMI cable",
"unitPrice": "6000",
"quantity": "1"
}
]
}'
그리고 여기에 내가 요청한 내용이 있습니다.
import json
import requests
headers = {
'Content-Type': 'application/json',
'Authorization': 'Bearer 3e5cac39-7e38-4139-8fd6-30adc06a61bd',
}
data = {
"notifyUrl": "https://your.eshop.com/notify",
"customerIp": "127.0.0.1",
"merchantPosId": "145227",
"description": "RTV market",
"currencyCode": "PLN",
"totalAmount": "21000",
"products": [
{
"name": "Wireless Mouse for Laptop",
"unitPrice": "15000",
"quantity": "1"
},
{
"name": "HDMI cable",
"unitPrice": "6000",
"quantity": "1"
}
]
}
resp2 = requests.post('https://secure.payu.com/api/v2_1/orders', headers=headers, json=data)
print(resp2.json())
응답으로 컬이 출력됩니다.
{"orderId":"V6GRPMNRLR160429GUEST000P01","status":{"statusCode":"SUCCESS"},"redirectUri":"https://secure.payu.com/pl/standard/co/summary?sessionId=HtnLqVtBJ5tcOKG2nX03TKwAXOYtXPHe&merchantPosId=145227&timeStamp=1461948331350&showLoginDialog=false&apiToken=9f31fcd1d0d1c5fde8aa57c2b16b5d6bbdfe81543a5f6a12cd39955a487fdaab"}
반면 파이썬은 다음을 요청합니다.
/usr/local/lib/python2.7/dist-packages/requests/packages/urllib3/util/ssl_.py:315: SNIMissingWarning: An HTTPS request has been made, but the SNI (Subject Name Indication) extension to TLS is not available on this platform. This may cause the server to present an incorrect TLS certificate, which can cause validation failures. For more information, see https://urllib3.readthedocs.org/en/latest/security.html#snimissingwarning.
SNIMissingWarning
/usr/local/lib/python2.7/dist-packages/requests/packages/urllib3/util/ssl_.py:120: InsecurePlatformWarning: A true SSLContext object is not available. This prevents urllib3 from configuring SSL appropriately and may cause certain SSL connections to fail. For more information, see https://urllib3.readthedocs.org/en/latest/security.html#insecureplatformwarning.
InsecurePlatformWarning
Traceback (most recent call last):
File "/home/ubuntu/workspace/src/billing/testapi.py", line 30, in <module>
print(resp2.json())
File "/usr/local/lib/python2.7/dist-packages/requests/models.py", line 808, in json
return complexjson.loads(self.text, **kwargs)
File "/usr/lib/python2.7/dist-packages/simplejson/__init__.py", line 488, in loads
return _default_decoder.decode(s)
File "/usr/lib/python2.7/dist-packages/simplejson/decoder.py", line 370, in decode
obj, end = self.raw_decode(s)
File "/usr/lib/python2.7/dist-packages/simplejson/decoder.py", line 389, in raw_decode
return self.scan_once(s, idx=_w(s, idx).end())
simplejson.scanner.JSONDecodeError: Expecting value: line 8 column 1 (char 7)
누구든지 요청과 함께 작동하지 않는 이유를 알고 있습니까? 감사
사이트 는 Location 헤더를 포함하여 302 상태 코드로 응답합니다 .
>>> resp = requests.post('https://secure.payu.com/api/v2_1/orders', headers=headers, json=data)
>>> resp.history
[<Response [302]>, <Response [302]>]
>>> resp.history[0].headers['location']
'https://secure.payu.com/pl/standard/co/summary?sessionId=rrQ97fR2bxQJhUqCDORCbRa0uA4WlxJi&merchantPosId=145227&timeStamp=1461950205252&showLoginDialog=false&apiToken=f3599eca78ad55a16d84608e69f3ac7458b782598b064b337be07e8bd6c2c1d5'
>>> resp.history[0].text
u'{"orderId":"Z9W2H77TVD160429GUEST000P01","status":{"statusCode":"SUCCESS"},"redirectUri":"https://secure.payu.com/pl/standard/co/summary?sessionId=rrQ97fR2bxQJhUqCDORCbRa0uA4WlxJi&merchantPosId=145227&timeStamp=1461950205252&showLoginDialog=false&apiToken=f3599eca78ad55a16d84608e69f3ac7458b782598b064b337be07e8bd6c2c1d5"}'
response.history
이전 요청이 포함 된 목록 을 보면 리디렉션 기록 (위에서했던 것처럼)을 볼 수 있습니다. resp.history[0]
여기에서 초기 응답이었습니다. 설명서에서 리디렉션 및 기록 을 참조하십시오 .
데이터는 초기 응답에 바로 있습니다 .
사용할 때이 사이트는이 작업을 수행 어떤 Accept-Encoding
헤더; 추가하면 동일한 결과를 얻습니다.
-H "Accept-Encoding: gzip, deflate"
받는 curl
명령 또는 행 (값)와 같은 헤더를 추가하여 제공된 payu.apiari.io 콘솔 (클릭 헤더 다음에, 추가 Accept-Encoding
헤더 및 헤더 값을 추가).
헤더를 지정하는 것이 완벽하게 정상적인 작업 이므로 사이트의 버그로 간주 해야 합니다. 실제로 Python httplib
라이브러리 (에서 간접적으로 사용됨 requests
)는 헤더를 직접 생략하면 해당 헤더에 대한 기본값을 설정 하므로 requests
스위치를 끌 수도 있습니다. 따라서 PayU에 버그로 신고했습니다.
해결 방법으로 response.history[0]
참조를 사용 하거나 더 나은 방법으로 요청에 처음부터 리디렉션을 따르지 않도록 지시 할 수 있습니다 .
>>> resp = requests.post('https://secure.payu.com/api/v2_1/orders', headers=headers, json=data, allow_redirects=False)
>>> resp.json()
{u'orderId': u'NBWTP5WNKK160429GUEST000P01', u'status': {u'statusCode': u'SUCCESS'}, u'redirectUri': u'https://secure.payu.com/pl/standard/co/summary?sessionId=PcvceJHf5En60Dier5gKxCyExiva4qh0&merchantPosId=145227&timeStamp=1461950329704&showLoginDialog=false&apiToken=5962ef901010ca4f8ef6491619217c060f4d53ed0d8e4eadb513d4e0811fc992'}
그러나 302를 무시하면 정상적인 상태 코드를 방해 할 수 있습니다. 302는 추가 보안 정보가 필요함을 나타낼 수 있습니다 .
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다