PayPal Adaptive Payments - Preapproval request results in "Invalid request" error - python

I can't figure out what's happening with my Preapproval HTTP POST request. I'm just trying to do a basic call to PayPal's Adaptive Payments API, the Preapproval call specifically. And the PayPal error 580001 "Invalid request" is not that helpful in itself.
Request Headers (based on my Sandbox's account credentials, which I changed to xxx):
{
'X-PAYPAL-REQUEST-DATA-FORMAT': 'JSON',
'X-PAYPAL-SECURITY-PASSWORD': 'xxx',
'X-PAYPAL-RESPONSE-DATA-FORMAT': 'JSON',
'X-PAYPAL-SECURITY-SIGNATURE': 'xxx',
'X-PAYPAL-SECURITY-USERID': 'xx',
'X-PAYPAL-APPLICATION-ID': 'APP-80W284485P519543T'
}
My request payload (HTTP POST, body encoded in JSON):
{
"requireInstantFundingSource": "TRUE",
"returnUrl": "http://www.google.com/?paypal=ok",
"maxTotalAmountOfAllPayments": 1002,
"maxNumberOfPaymentsPerPeriod": 1,
"endingDate": "2014-03-14T16:49:36+0000",
"requestEnvelope.errorLanguage": "en_US",
"clientDetails.applicationId": "XXX",
"cancelUrl": "http://www.google.com/paypal=cancel",
"startingDate": "2013-09-15T16:49:36+0000",
"feesPayer": "PRIMARYRECEIVER",
"currencyCode": "SEK"
}
The above POST body is posted to:
https://svcs.sandbox.paypal.com/AdaptivePayments/Preapproval
Response from Paypal ("prettified" for understanding):
{
"responseEnvelope": {
"ack": "Failure",
"timestamp": "2013-09-10T09:56:43.031-07:00",
"build": "6941298",
"correlationId": "26d55e6bfcaa0"
},
"error": [
{
"category": "Application",
"domain": "PLATFORM",
"severity": "Error",
"message": "Invalid request: {0}",
"subdomain": "Application",
"errorId": "580001"
}
]
}
Any feedback is appreciated.

OK fixed. How?
Fix #1
The arguments requestEnvelope.errorLanguage and clientDetails.applicationId need to be "JSONified" into objects on their own, such as:
"requestEnvelope": {
"errorLanguage": "en_US"
},
and
"clientDetails": {
"applicationId": "APP-XXXXXXXXXXXXX"
},
respectively.
Fix #2
Date formats; date format should be of the form 2014-03-15T20:14:38.007+00:00 and not 2014-03-14T20:14:38+0000 as I was passing. Note the milliseconds, and the timezone with the colon in the utc offset.
Next time an Invalid request comes up the parameters I'm passing will be the first thing to look at.

Related

Microsoft Graph - Create Teams API Returns "Bind requests not supported for containment navigation property ."

I'm new to Microsoft Teams, I'm trying to create a team using the following API
https://graph.microsoft.com/beta/teams
I'm using the following snippet of Python code to create the team.
url = "https://graph.microsoft.com/beta/teams"
headers = {'Authorization': 'Bearer ' + token, 'Content-Type': 'application/json'}
data = {
"template#odata.bind": "https://graph.microsoft.com/beta/teamsTemplates('standard')",
"displayName": "FIRST TEAM",
"description": "FIRST TEAM",
"members#odata.bind": [
{
"#odata.type": "#microsoft.graph.aadUserConversationMember",
"roles": '[owner]',
"userId": "3c0d3719-6c92-4646-af05-f02df80242db"
}
]
}
response = requests.post(url, headers=headers, data=json.dumps(data))
I receive the following response.
b'{\r\n "error": {\r\n "code": "BadRequest",\r\n "message": "Bind requests not supported for containment navigation property.",\r\n "innerError": {\r\n "date": "2020-10-12T16:58:45",\r\n "request-id": "2063aba7-43f2-4024-912c-e7402bb1d6ba",\r\n "client-request-id": "2063aba7-43f2-4024-912c-e7402bb1d6ba"\r\n }\r\n }\r\n}'
I'd like to know what I'm doing wrong, I tried to learn more about the error message Bind requests not supported for containment navigation property but couldn't find anything helpful.
Can someone please help me understand what the error means and if possible what is wrong with the request itself ?
I found the answer, I had to modify data as follows.
data = {
"template#odata.bind": r"https://graph.microsoft.com/beta/teamsTemplates('standard')",
"displayName": "FIRST TEAM",
"description": "FIRST TEAM",
"members": [
{
"#odata.type": "#microsoft.graph.aadUserConversationMember",
"roles": ["owner"],
"userId": "3b0d3719-6c92-4646-af05-f02df80242db"
}
]
}
If you can't tell the key has to be members
This was discovered through trial and error though I'm not sure why.

Sentiment Analysis using Google Cloud API in Python giving error

I'm trying to perform sentiment analysis using google NLP cloud API.
Below is my code
import requests
url = "https://language.googleapis.com/v1/documents:analyzeSentiment"
myobj = {
"key": "XYZ",
"document":{
"type":"PLAIN_TEXT",
"language": "EN",
"content":"'Lawrence of Arabia' is a highly rated film biography about British Lieutenant T. E. Lawrence. Peter O'Toole plays Lawrence in the film."
},
"encodingType":"UTF8",
"Content-Type": "application/json"
}
x = requests.post(url, data = myobj)
print(x.text)
But it is giving me error
{
"error": {
"code": 400,
"message": "Invalid JSON payload received. Unknown name \"Content-Type\": Cannot bind query parameter. Field 'Content-Type' could not be found in request message.\nInvalid JSON payload received. Unknown name \"document\": Cannot bind query parameter. 'document' is a message type. Parameters can only be bound to primitive types.",
"status": "INVALID_ARGUMENT",
"details": [
{
"#type": "type.googleapis.com/google.rpc.BadRequest",
"fieldViolations": [
{
"description": "Invalid JSON payload received. Unknown name \"Content-Type\": Cannot bind query parameter. Field 'Content-Type' could not be found in request message."
},
{
"description": "Invalid JSON payload received. Unknown name \"document\": Cannot bind query parameter. 'document' is a message type. Parameters can only be bound to primitive types."
}
]
}
]
}
}
Does anybody know why it is happening? Will appreciate any help. Thanks.
Use the json parameter instead of data:
x = requests.post(url, json=myobj)

SQS, Lambda & SES param undefined

I had this stack setup and working perfectly before, however, all of a sudden I am seeing a strange error in my CloudWatch.
This is my function (Python) for posting a message to SQS (which triggers a lambda function to send an email with SES):
def post_email(data, creatingUser=None):
sqs = boto3.client("sqs", region_name=settings.AWS_REGION)
# Send message to SQS queue
response = sqs.send_message(
QueueUrl=settings.QUEUE_EMAIL,
DelaySeconds=10,
MessageAttributes={
"ToAddress": {"DataType": "String", "StringValue": data.get("ToAddress")},
"Subject": {"DataType": "String", "StringValue": data.get("Subject")},
"Source": {
"DataType": "String",
"StringValue": data.get("Source", "ANS <noreply#ansfire.net"),
},
},
MessageBody=(data.get("BodyText"))
# When SQS pulls this message off, need to ensure that the email was
# actually delivered, if so create a notification
)
I print the params out and it is setting the above attributes correctly, however when I look in my CloudWatch this is the message:
2020-02-03T20:41:59.847Z f483293f-e48b-56e5-bb85-7f8d6341c0bf INFO {
Destination: { ToAddresses: [ undefined ] },
Message: {
Body: { Text: [Object] },
Subject: { Charset: 'UTF-8', Data: undefined }
},
Source: undefined
}
Any idea of what is going on?
I figured out the error, I needed to get the attributes from the data dictionary prior to calling the send_message function.

Login error 401 while making put request in Python

I'm trying to post a videoId in a youtube playlist using youtube api in python. Below is my code,
import json
from apiclient.discovery import build
import requests
post_url = "https://www.googleapis.com/youtube/v3/playlistItems"
payload = {
'key':"*******",
'part':'snippet',
'playlistId':'****',
'videoId':'****'
}
r = requests.post(post_url, data=json.dumps(payload))
print(r.text)
But now I keep getting below error,
{
"error": {
"errors": [
{
"domain": "global",
"reason": "required",
"message": "Login Required",
"locationType": "header",
"location": "Authorization"
}
],
"code": 401,
"message": "Login Required"
}
}
I've tried getting data by GET request in similar way and I was successful in that. What is wrong with this then?
401 means Unauthorized.
So, you need to pass authentication details.
Examples:
https://developers.google.com/youtube/v3/docs/playlists/list#examples
https://developers.google.com/api-client-library/python/guide/aaa_client_secrets

directline v3 gives error 400

In the Step Sending an Activity to the bot As per the documentation Here,
https://docs.botframework.com/en-us/restapi/directline3/#navtitle
I should pass this as the body content of the post request
{
"type": "message",
"from": {
"id": "user1"
},
"text": "hello"
}
I am using the following parameters to make POST request in python, but its not working.
msg = {"type": "message","channelId": "directline","conversation":{"id": str(convId)},"from":{"id": "test_user1"},"text": "hello"}
header = {"Authorization":"Bearer q1-Tr4sRrAI.cwA.BmE.n7xMxGl-QLoT7qvJ-tNIcwAd69V-KOn5see6ki5tmOM", "Content-Type":"application/json", "Content-Length": "512"}
send2 = "https://directline.botframework.com/v3/directline/conversations/"+str(convId)+"/activities"
rsa1 = requests.post(send2,data=msg, headers=header)
This gives me this error:
{
"error": {
"code": "MissingProperty",
"message": "Invalid or missing activities in HTTP body"
}
}
Before this step everything is working fine.
Edit 1: Even i added content-length as updated in the code, it gives the same error
Edit 2: If i changed the msg to json.dumps(msg)
rsa1 = requests.post(send2,data=json.dumps(msg), headers=header)
I get response:
{u'error': {u'message': u'Failed to send activity: bot returned an error', u'code': u'ServiceError'}}
{
"error": {
"code": "ServiceError",
"message": "Failed to send activity: bot returned an error"
}
}
The directline API is only not working, on skype client everything is working fine.
According to the code that you've posted, your request body looks like this:
{
"type": "message",
"channelId": "directline",
"conversation": {
"id": str(convId)
},
"from": {
"id": "test_user1"
},
"text": "hello"
}
I'd suspect that your error is caused by the fact that the conversation ID value that you're including in the request body is not surrounded with double quotes in the JSON that's sent over the wire.
For simplicity (and to eliminate the error you're receiving), I'd suggest that you try omitting the channelId property and the conversation property from the request body, as I don't believe that either of these properties are necessary (i.e., you are issuing the request to the Direct Line URI, so the Bot Framework knows that Direct Line is the channel, and the conversation ID is already being specified in the request URI). In other words, try this as your request body:
{
"type": "message",
"from": {
"id": "test_user1"
},
"text": "hello"
}
When passing a dictionary to data it gets urlencoded automatically, so the api returns an error as it expects json data.
You can either use the json lib, or preferably pass your dictionary to the json parameter.
Using json.dumps :
rsa1 = requests.post(send2, data=json.dumps(msg), headers=header)
Using requests only :
rsa1 = requests.post(send2, json=msg, headers=header)
Also you don't have to add "Content-Length" in header and if you use the second example you don't have to add "Content-Type" either.

Categories

Resources