Unrecognized token 'transaction_id' in PayPal request - paypal

I feel like theres just some syntax I'm doing wrong on my part and can't find any solutions.
url = 'https://api-m.paypal.com/v1/shipping/trackers/%s-%s' % (paypal_transaction_token, tracking_number)
print("url is", url)
headers = {
'Content-Type' : 'application/json',
'Authorization' : 'Bearer %s' % access_token,
}
print('headders here', headers)
data = {
"transaction_id": "%s" % paypal_transaction_token,
"tracking_number":"%s" % tracking_number,
"status": "%s" % status,
"carrier": "%s" % carrier
}
print("data", data)
response = requests.put(url, headers=headers, data=data)
The error I keep receiving is Unrecognized token 'transaction_id' and if I remove transaction_id I just get the same error for whichever data param is first.
According to the docs, this is all correct so I assume its on my code that is wrong:
https://developer.paypal.com/docs/tracking/integrate/#update-or-cancel-tracking-information
https://developer.paypal.com/docs/api/tracking/v1/
What in my code is wrong?
I have tried without the %s as well.

The error I keep receiving is Unrecognized token 'transaction_id' and if I remove transaction_id I just get the same error for whichever data param is first.
requests.put will form encode the data, while the PayPal API
accepts JSON. Do:
data=json.dumps(data)

Related

no_file_data error when using Slack API upload

I'm getting this error {"ok":false,"error":"no_file_data"} when I try to call the slack API to upload. I already have the specified file in ./log.
robot.respond /upload (.*)/i, (res) ->
app_name = res.match[1]
request = require("request")
fs = require("fs")
channel_name = res.message.room
data = {
channels: channel_name,
filename: "#{app_name}.txt",
file: fs.createReadStream("./log/#{app_name}.txt"),
}
robot.http("https://slack.com/api/files.upload")
.headers(Authorization: 'Bearer slack-token', 'Content-Type': 'application/json')
.post(data) (err, httpRes, body) ->
if err
res.send "#{err}"
return
res.send "#{body}"
This does not work, because the API method files.upload does not support the content type application/json posts.
For your case you need to post as multipart/form-data, with one part containing the file data and one part containing the API parameters including the token.

Trying to run code in IBM Cloud Functions

I have following code I am trying to run in IBM function to get billing data out:
iam_token = 'Bearer eyJraWQiOiIyMDE3MTAzMC0wM****'
def processResourceInstanceUsage(account_id, billMonth):
METERING_HOST = "https://metering-reporting.ng.bluemix.net"
USAGE_URL = "/v4/accounts/"+account_id + \
"/resource_instances/usage/"+billMonth+"?_limit=100&_names=true"
url = METERING_HOST+USAGE_URL
headers = {
"Authorization": "{}".format(iam_token),
"Accept": "application/json",
"Content-Type": "application/json"
}
response = requests.get(url, headers=headers)
print("\n\nResource instance usage for first 100 items")
return response.json()
processResourceInstanceUsage('*****', '11')
For some reason, I keep on getting 201 unauthorized error. I tried creating iam_token many times. It still gives the same error.
There are few things that should be taken care in the code you provided.
The month you are passing is wrong. It should be in YYYY-MM format.
account_id should be the id next to your Account name when you run ibmcloud target
For IAM token, run this command ibmcloud iam oauth_tokens. If you want to generate access token using your Platform API Key, refer to this link. The word Bearer is not required as this is not an authorization token.
Once you have all this in place, create an IBM Cloud function (Python 3), add the below code, pass the account_id and token and invoke the action to see the result . IBM Cloud function expects a dictionary as an input/parameter and JSON as response
import sys
import requests
def main(dict):
METERING_HOST="https://metering-reporting.ng.bluemix.net"
account_id="3d40d89730XXXXXXX"
billMonth="2018-10"
iam_token="<IAM_TOKEN> or <ACCESS_TOKEN>"
USAGE_URL="/v4/accounts/"+account_id+"/resource_instances/usage/"+billMonth+"?_limit=100&_names=true"
url=METERING_HOST+USAGE_URL
headers = {
"Authorization": "{}".format(iam_token),
"Accept": "application/json",
"Content-Type": "application/json"
}
response=requests.get(url, headers=headers)
print ("\n\nResource instance usage for first 100 items")
return { 'message': response.json() }
This worked for me and returned a JSON with region-wise billing data.
Reference: https://stackoverflow.com/a/52333233/1432067

Error while generating access_token using Ebay 's REST API - Python requests

I'm trying to use the ebay REST-API for the first. I am simply trying to generate an access_token using the client credentials grant-request. I followed the instructions here https://developer.ebay.com/api-docs/static/oauth-client-credentials-grant.html
HTTP method: POST
URL (Sandbox): https://api.sandbox.ebay.com/identity/v1/oauth2/token
HTTP headers:
Content-Type = application/x-www-form-urlencoded
Authorization = Basic <B64-encoded_oauth_credentials>
Request body (wrapped for readability):
grant_type=client_credentials&
redirect_uri=<RuName-value>&
scope=https://api.ebay.com/oauth/api_scope
I'm getting this error: {'error': 'invalid_client', 'error_description': 'client authentication failed'} and my code looks like this:
path = 'https://api.sandbox.ebay.com/'
app_json = 'application/json'
headers = {
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': base64.b64encode(b'Basic CLIENT_ID:CLIENT_SECRET')
}
payload = 'grant_type=client_credentials&redirect_uri=Searchez&scope=https://api.ebay.com/oauth/api_scope'
def get_oath_token():
url = 'https://api.sandbox.ebay.com/identity/v1/oauth2/token'
r = requests.post(url, headers=headers, data=payload)
print(r.json())
get_oath_token()
What do I have configured incorrectly? Thanks.
You're base64encoding "Basic " and shouldn't be.
The doc says just encode your Client ID + ":" + Client Secret, and leave the word "Basic" and the space that follows it alone.
In your code, i can see sandbox endpoint URI but in the request body scope, you have used production URL, instead of sandbox

How get access_token from body for use in another method

Good afternoon. Slightly confused in the Gatling documentation, I can not find a solution. I want to get a token to use in another method as a header. Here is an example of the first method where I get a token:
exec(
http("HTTP Request auth")
.post("http://blabla:9001/connect/token")
.header("Content-Type","application/x-www-form-urlencoded")
.formParam("grant_type","password")
.formParam("username", "${login}")
.formParam("password", "${password}")
.formParam("client_id","ro.client")
.formParam("client_secret","secret")
.check(status is 200)
.check(header("access_token").saveAs("access_token"))
.check(header("token_type").saveAs("token_type"))
)
Here's the second method, where I want to pass the token:
.exec(
http("HTTP Request createCompany")
.post("/Companies/CreateCompany")
.header("Authorization","${token_type} + ${access_token}")
.check(status is 200)
)
As a result, writes that a token was not found:
Request:
HTTP Request auth: KO header(access_token).find(0).exists, found nothing
But then he writes:
body={"access_token":"7e8c1d997dd92f16a87fa7ffb8a88ab14eb05a8883d78fe8652d072f24b5ca4a","expires_in":31536000,"token_type":"Bearer"}
I guess I find it wrong here:
.check(header("access_token").saveAs("access_token"))
.check(header("token_type").saveAs("token_type"))
The body of the first request is a Json payload, you need to use jsonPath, which is like XPath for Json:
.check(jsonPath("$.access_token").saveAs("access_token"))
.check(jsonPath("$.token_type").saveAs("token_type"))
Also, the header of the second request will print as:
.header("Authorization", "${token_type} + ${access_token}")
=> Authorization: Bearer + 7e8c1d997dd92f16a87fa7ffb8a88ab14eb05a8883d78fe8652d072f24b5ca4a
Unless you really want the extra +, the right header construction might be:
.header("Authorization", "${token_type} ${access_token}")
One way is to do like this ->
exec { session => var access_token ='' ;
your exec code
session.setAll( "token_type" -> access_token );
}
Then token_type is available to use.

Returning result from nested anonymous function in a hubot script

Having never worked with coffescript before, I'm trying to update the hubot script for jenkins integration. In a nutshell I want to call jenkins, get a result from that call and use it in a subsequent call. Based on the existing code in the hubot script I've added the following function:
jenkinsCrumb = (msg) ->
url = process.env.HUBOT_JENKINS_URL
path = "#{url}/crumbIssuer/api/json"
req = msg.http(path)
if process.env.HUBOT_JENKINS_AUTH
auth = new Buffer(process.env.HUBOT_JENKINS_AUTH).toString('base64')
req.headers Authorization: "Basic #{auth}"
req.get() (err, res, body) ->
if err
msg.reply "Jenkins says: #{err}"
else if 200 <= res.statusCode < 400 # Or, not an error code.
msg.reply "#{body}"
body
else if 404 == res.statusCode
msg.reply "Unable to fetch crumb from Jenkins..."
else
msg.reply "Jenkins says: Status #{res.statusCode} #{body}"
When this function is called, the value I want is reported in the variable body. The call to msg.reply properly displays the value in the hubot chat window.
What I would like to do, but can't figure out, is how to have this function return the value of body? I've tried explicitly returning the value of req.get() but it seems that it's returning the full request object.
You can do that by simply adding return body or just body (because of CoffeeScript) to the end of your anonymous function:
jenkinsCrumb = (msg, callback) ->
url = process.env.HUBOT_JENKINS_URL
path = "#{url}/crumbIssuer/api/json"
req = msg.http(path)
if process.env.HUBOT_JENKINS_AUTH
auth = new Buffer(process.env.HUBOT_JENKINS_AUTH).toString('base64')
req.headers Authorization: "Basic #{auth}"
req.get() (err, res, body) ->
if err
msg.reply "Jenkins says: #{err}"
else if 200 <= res.statusCode < 400 # Or, not an error code.
msg.reply "#{body}"
body
else if 404 == res.statusCode
msg.reply "Unable to fetch crumb from Jenkins..."
else
msg.reply "Jenkins says: Status #{res.statusCode} #{body}"
# critical part
callback(body)