basically I've got the following code:
var fs = require('fs');
const request = require("request");
var body = JSON.parse(fs.readFileSync('body.json', 'utf8'));
var options = {
method: 'POST',
uri: 'https://api.pagar.me/core/v5/orders',
headers: {
'Authorization': 'Basic ' + Buffer.from("sk_test_*:").toString('base64'),
'Content-Type': 'application/json'
},
json : body
};
request(options, function(error, response, body) {
console.log(response.body);
});
I've tried to do the following in Python:
import requests
headers = {'Authorization': 'token',
'Content-Type': 'application/json'
}
k = requests.post("https://api.pagar.me/core/v5/orders", headers=headers)
The node code works, but the python only returns 401, so I know the token is right as the node example works, what do I need to do here I'm a newbie.
Related
Using Python, how do I make a request to the shopee API to get a list of products on offer with my affiliate link?
I've made several scripts, but they all have a signature issue or unsupported authentication attempt. Does anyone have a working example of how to do this?
Below are two code examples I made, but they don't work.
Query: productOfferV2 and shopeeOfferV2
code1:
import requests
import time
import hashlib
appID = '18341090114'
secret = 'XMAEHHWQD3OEGQX5P33AFRREJEDSQX76'
# Set the API endpoint URL
url = "https://open-api.affiliate.shopee.com.my/graphql"
payload = """
{
"query": "query Fetch($page:2){
productOfferV2(
listType: 0,
sortType: 2,
page: $page,
limit: 50
) {
nodes {
commissionRate
commission
price
productLink
offerLink
}
}
}",
"operationName": null,
"variables":{
"page":0
}
}
"""
payload = payload.replace('\n', '').replace(':0', f':{2}')
timestamp = int(time.time())
factor = appID+str(timestamp)+payload+secret
signature = hashlib.sha256(factor.encode()).hexdigest()
# Set the request headers
headers = {
'Content-type': 'application/json',
'Authorization': f'SHA256 Credential={appID},Timestamp={timestamp},Signature={factor}'
}
# Send the POST request
response = requests.post(url, payload, headers=headers)
data = response.json()
print(data)
return = error-invalid-signature-python
code2:
import requests
import json
import hmac
import hashlib
appID = '18341090114'
secret = 'XMAEHHWQD3OEGQX5P33AFRREJEDSQX76'
query = '''query { productOfferV2(item_id: ALL) {
offers {
shop_id
item_price
discount_price
offer_id
shop_location
shop_name
}
}
}'''
def generate_signature(query, secret):
signature = hmac.new(secret.encode(), query.encode(), hashlib.sha256).hexdigest()
return signature
signature = generate_signature(query, secret)
url = 'https://open-api.affiliate.shopee.com.my/graphql'
headers = {
'Content-Type': 'application/json',
'Accept': 'application/json',
'Authorization': 'Bearer ' + appID + ':' + signature
}
payload = {
'query': query
}
response = requests.post(url, data=json.dumps(payload), headers=headers)
data = response.json()
print(data)
I'm looking for assistance with translating a piece of sample code written in javascript into something that will work with Python. The sample code is for the 'POST Authenticate' Endpoint of CCH Axcess' Open Integration Kit, which sends a response containing a Security Token
URL: https://api.cchaxcess.com/api/AuthServiceHelp/v1.0/help/operations/Authenticate
Sample Code:
var _restIntegratorKey = "{User Integrator Key}"; // Please use this variable as global variable as all subsequent call required this integrator key to pass
var _restHostUrl = "{host url}"; // i.e. "{Protocol}://{host name}/api"
var request = $.ajax({
url: _restHostUrl + "/AuthService/v1.0/Authenticate",
contentType: "application/json; charset=utf-8",
type: "GET",
dataType: "json"
});
var request = {
UserName: "{username}", // Specify Username
UserSid: "anyone",
Password: "{password}", // Specify Password
Realm: "{accountnumber}" // Specify Account number
};
var request = $.ajax({
url: _restHostUrl + "/AuthService/v1.0/Authenticate",
data: JSON.stringify(request),
beforeSend: _setHttpHeader,
contentType: "application/json",
type: "POST",
dataType: "json"
});
request.done(function (data, textStatus, jqXHR) {
// This method block will be executed on succefull execution of api and will return security token.
// Below statement will store returned security token into browser cookie named: "CchNGAuthToken". you can use any other way to persist this token.
// This security token we required to pass in header for other rest api calls
document.cookie = "CchNGAuthToken=" + data.Token;
});
request.fail(function (jqXHR, textStatus, err) {
// This method block will be executed if API returns any error.
});
// Please keep these below two methods, As both will be used in subsequent call, to get SSOToken from Cookie
// set Security token and integratorkey into request header
function _setHttpHeader(xhr) {
var ssoToken = _getSessionCookie("CchNGAuthToken"); // Read security token from document cookie which we set during authentication rest api call
xhr.setRequestHeader("Security", ssoToken);
xhr.setRequestHeader("IntegratorKey", _restIntegratorKey);
};
// Get session cookie
function _getSessionCookie(name) {
var key = name + "=";
var cookie = "";
if (document.cookie.length > 0) {
var begin = document.cookie.indexOf(key)
if (begin != -1) {
begin += key.length
var end = document.cookie.indexOf(";", begin);
if (end == -1)
end = document.cookie.length;
cookie = unescape(document.cookie.substring(begin, end))
}
}
return cookie;
};
I have an LIC file with the IntegratorKey stored in XML format, like:
<?xml version="1.0"?>
<IntegratorInfo>
<IntegratorKey>XXXXX-XXX-XXX-XXXX</IntegratorKey>
</IntegratorInfo>
I think my primary issue is identifying the values of the 'ssoToken' and '_restIntegratorKey' variables once they're assigned inside the '_setHttpHeader' function.
My attempt:
def getcchauth():
import requests
integratorkey = getintkey()
cookie = getcookie()
authheaders = {
'Security': cookie,
'IntegratorKey': integratorkey,
'content-type': 'application/json; charset=utf-8'
}
cchlogin = {
'UserName':"user",
"UserSid": 'anyone',
'Password': 'password',
'Realm' : '123456',
}
authattempt = requests.post(resthosturl+endpoint, data = cchlogin,
headers=authheaders)
print(authattempt.headers)
def getcookie():
import requests
import json
cookieresponse = requests.get(resthosturl+apiservdir,
headers = headers)
cookieresponse = json.dumps(cookieresponse.headers.__dict__['_store'])
cookieresponse = json.loads(cookieresponse)
cookie = 'CchNGAuthToken=' + cookieresponse['set-cookie'][1].split(';')[0].strip() + ';'
print(cookie)
return cookie
Thanks!
Looks like I'm doing just about everything correct but I keep receiving this error....
Response text error:
response .text {"name":"INVALID_TRACKING_NUMBER","message":"The requested resource ID was not found","debug_id":"12345","details":[{"field":"tracker_id","value":"1234-567890","location":"path","issue":"INVALID_TRACKING_INFO"}],"links":[]}
Response status: <Response [404]>
I'm using a real transaction and a real tracking number.
I'm doing this through python and this is my code:
def paypal_oauth():
url = 'https://api-m.paypal.com/v1/oauth2/token'
headers = {
"Content-Type": "application/json",
"Accept-Language": "en_US",
}
auth = "1234-1234","0987"
data = {"grant_type":"client_credentials"}
response = requests.post(url, headers=headers, data=data, auth=(auth))
return response
def paypal_tracking(paypal_transaction_token, tracking_number, status, carrier):
try:
_paypal_oauth = paypal_oauth()
_paypal_oauth_response = _paypal_oauth.json()
except Exception as e:
print(e)
pass
access_token = _paypal_oauth_response['access_token']
url = 'https://api-m.paypal.com/v1/shipping/trackers/%s-%s/' % (paypal_transaction_token, tracking_number)
# https://api-m.paypal.com/v1/shipping/trackers/1234-567890/
carrier = carrier_code(carrier)
# This grabs carrier from a method and gets back: 'DHL'
headers = {
'Content-Type' : 'application/json',
'Authorization' : 'Bearer %s' % access_token,
}
# {'Content-Type': 'application/json', 'Authorization': 'Bearer 1234'}
data = {
"transaction_id":"%s" % paypal_transaction_token,
"tracking_number":"%s" % tracking_number,
"status": "%s" % status,
"carrier": "%s" % carrier
}
# {'transaction_id': '1234', 'tracking_number': '567890', 'status': 'SHIPPED', 'carrier': 'DHL'}
response = requests.put(url, headers=headers, data=json.dumps(data))
return HttpResponse(status=200)
Anyone with experience in paypal or using API's see my issue?
To add a tracking number (not update), use an HTTP POST request, as documented.
The URL to POST to is https://api-m.sandbox.paypal.com/v1/shipping/trackers-batch , with no additional URL parameters.
The body format is
{
"trackers": [
{
"transaction_id": "8MC585209K746392H",
"tracking_number": "443844607820",
"status": "SHIPPED",
"carrier": "FEDEX"
},
{
"transaction_id": "53Y56775AE587553X",
"tracking_number": "443844607821",
"status": "SHIPPED",
"carrier": "FEDEX"
}
]
}
Note that trackers is an array of JSON object(s).
I have registered at the https://azure.microsoft.com/ru-ru/try/cognitive-services
From there I got an API-key and an endpoint https://api.cognitive.microsoft.com/inkrecognizer
Here is my code:
import requests, json
subs_key = API_KEY
uri_base = 'https://api.cognitive.microsoft.com/inkrecognizer'
headers = {'Content-type': 'application/json',
"Ocp-Apim-Subscription-Key": subs_key}
body = {}
response =requests.request('POST', uri_base, json=body, data=None, headers=headers)
print('Response:')
parsed =json.loads(response.text)
print(json.dumps(parsed, sort_keys=True, indent=2))
However it gives me
Response:
{
"error": {
"code": "404",
"message": "Resource not found"
}
}
What am I doing wrong?
Here how the code should look like:
import requests, json
subs_key = API_KEY
uri_base = 'https://api.cognitive.microsoft.com/inkrecognizer/v1.0-preview/recognize'
headers = {'Content-type': 'application/json',
"Ocp-Apim-Subscription-Key": subs_key}
body = {}
response =requests.request('PUT', uri_base, json=body, data=None, headers=headers)
print('Response:')
parsed =json.loads(response.text)
print(json.dumps(parsed, sort_keys=True, indent=2))
And you will need to add into body 'language' and 'strokes'
GIST
I am currently trying to update a Sharepoint 2013 list.
This is the module that I am using using to accomplish that task. However, when I run the post task I receive the following error:
"b'{"error":{"code":"-1, Microsoft.SharePoint.Client.InvalidClientQueryException","message":{"lang":"en-US","value":"Invalid JSON. A token was not recognized in the JSON content."}}}'"
Any idea of what I am doing wrong?
def update_item(sharepoint_user, sharepoint_password, ad_domain, site_url, sharepoint_listname):
login_user = ad_domain + '\\' + sharepoint_user
auth = HttpNtlmAuth(login_user, sharepoint_password)
sharepoint_url = site_url + '/_api/web/'
sharepoint_contextinfo_url = site_url + '/_api/contextinfo'
headers = {
'accept': 'application/json;odata=verbose',
'content-type': 'application/json;odata=verbose',
'odata': 'verbose',
'X-RequestForceAuthentication': 'true'
}
r = requests.post(sharepoint_contextinfo_url, auth=auth, headers=headers, verify=False)
form_digest_value = r.json()['d']['GetContextWebInformation']['FormDigestValue']
item_id = 4991 # This id is one of the Ids returned by the code above
api_page = sharepoint_url + "lists/GetByTitle('%s')/items(%d)" % (sharepoint_listname, item_id)
update_headers = {
"Accept": "application/json; odata=verbose",
"Content-Type": "application/json; odata=verbose",
"odata": "verbose",
"X-RequestForceAuthentication": "true",
"X-RequestDigest": form_digest_value,
"IF-MATCH": "*",
"X-HTTP-Method": "MERGE"
}
r = requests.post(api_page, {'__metadata': {'type': 'SP.Data.TestListItem'}, 'Title': 'TestUpdated'}, auth=auth, headers=update_headers, verify=False)
if r.status_code == 204:
print(str('Updated'))
else:
print(str(r.status_code))
I used your code for my scenario and fixed the problem.
I also faced the same problem. I think the way that data passed for update is not correct
Pass like below:
json_data = {
"__metadata": { "type": "SP.Data.TasksListItem" },
"Title": "updated title from Python"
}
and pass json_data to requests like below:
r= requests.post(api_page, json.dumps(json_data), auth=auth, headers=update_headers, verify=False).text
Note: I used SP.Data.TasksListItem as it is my type. Use http://SharePointurl/_api/web/lists/getbytitle('name')/ListItemEntityTypeFullName to find the type