PayPal:Python Incoming JSON request does not map to API request - python

Am trying to integrate paypal sdk in my website using the paypal-python-SDK. When I type the item_list manually like this:
{"name": "Sparzy", "sku": "music beat", "price": "25.0", "currency": "USD", "quantity": 1}
But when I try to add it in form of a variable e.g.
itemlist = {"name": "Sparzy", "sku": "music beat", "price": "25.0", "currency": "USD", "quantity": 1}
I get the following error:
Payment Error: {u'message': u'Incoming JSON request does not map to API request', u'debug_id': u'394fa35b1b301', u'name': u'MALFORMED_REQUEST', u'information_link': u'https://developer.paypal.com/webapps/developer/docs/api/#MALFORMED_REQUEST'}
I really need it as a variable so that I can dynamically generate the list when a user add producs to cart. Thanks for your help.

I think you are trying to use dictonnary as JSON. Both syntaxes are similar but dictionnaries are Python structure while JSON is a data format.
In comments you said use your itemlist dictionnary like:
"transactions": [{
"item_list": { "items": [ itemlist ] },
"amount": { "total": total, "currency": "USD" },
"description": "This is the payment transaction description."
}]
If this is your entiere JSON data you want to send, you can do something like:
dict_data = "transactions": [{
"item_list": { "items": [ itemlist ] },
"amount": { "total": total, "currency": "USD" },
"description": "This is the payment transaction description."
}])
json_data = json.dumps(dict_data)
json.dumps() take a structure and parse it in JSON formatted string.
If you are doing something like:
json_data = "transactions": [{
"item_list": { "items": [ json.dumps(itemlist) ] },
"amount": { "total": total, "currency": "USD" },
"description": "This is the payment transaction description."
}])
You are wrong because element transacations:item_list will be a list of strings and not a list of dicts.
It's important to understand that JSON is just a way to format a structure, you could parse you dict in XML in the exact same way by example.
So be sure to compute data you want to send in a dictionnary first, then, at the really end, parse the whole data in JSON string.

Related

Best practices when pulling API data that is being updated/changed repeatedly

currently I'm pulling data from the Quickbooks online API, parsing it and storing it into a database. My problem is, right now with the small amount of data I am pulling I am just deleting my db tables and repopulating the tables with the updated - is there any way I can do this more optimally?
QuickBooks provides an API that is exactly what you're looking for. It's called Change Data Capture and is a common pattern for time-based updates like you're describing.
If you refer to Intuit's docs they tell you all about it:
https://developer.intuit.com/app/developer/qbo/docs/learn/explore-the-quickbooks-online-api/change-data-capture
Basically you make requests like this, providing a date/time you want data changed since:
https://quickbooks.api.intuit.com/v3/company/<realmId>/cdc?entities=<entityList>&changedSince=<dateTime>
And you get back a list of changed objects that you can then update your local database with:
{
"CDCResponse": [{
"QueryResponse": [{
"Customer": [{
...
"Id": "63",
...
},
{
...
"Id": "99",
...
}],
"startPosition": 1,
"maxResults": 2
},
{
"Estimate": [{
...
"Id": "34",
...
},
{
...
"Id": "123",
...
},
{
"domain": "QBO",
"status": "Deleted",
"Id": "979",
"MetaData": {
"LastUpdatedTime": "2015-12-23T12:55:50-08:00"
}
}],
"startPosition": 1,
"maxResults": 3,
"totalCount": 5
}]
}],
"time": "2015-12-23T10:00:01-07:00"
}

Python: Parse json data from a list with the same name

So I have the next json and I want to get just the github link and the twitter one without taking the foursquare and gravatar one.
Also this in not all, sometimes the json data can change and if doesn't find a foursquare url, github will become first and twitter the second one. With the other ones (github or twitter) will be the same.
How can I get the github and twitter url if they are not in the same position as in this json?
{ "socialProfiles": [
{
"type": "foursquare",
"typeId": "foursquare",
"typeName": "Foursquare",
"url": "https://foursquare.com/user/somerandomuser",
"id": "554225246246"
},
{
"type": "github",
"typeId": "github",
"typeName": "Github",
"url": "https://github.com/somerandomuser",
"username": "somerandomuser"
},
{
"type": "gravatar",
"typeId": "gravatar",
"typeName": "Gravatar",
"url": "https://gravatar.com/somerandomuser",
"username": "somerandomuser",
"id": "132341667"
},
{
"bio": " This is a bio of a random user",
"followers": 543,
"following": 222,
"type": "twitter",
"typeId": "twitter",
"typeName": "Twitter",
"url": "https://twitter.com/somerandomuser",
"username": "somerandomuser",
"id": "41414515335"
}
]
}
you can use dict comprehension to create another dict only with the urls that you need, in this case twitter and github
search = ['github', 'twitter']
urls = {dct['type']: dct['url'] for dct in data.get('socialProfiles', []) if dct['type'] in search}
print(urls)
Output
{
'github': 'https://github.com/somerandomuser',
'twitter': 'https://twitter.com/somerandomuser'
}
And after that you can get the url that you need.
print(urls['github'])
# Output
# https://github.com/somerandomuser
Using a simple iteration.
Ex:
checkList = ["twitter", "github"]
for i in data["socialProfiles"]:
if i["typeId"] in checkList: #Check if typeid is in your check-list
print(i["url"])
Output:
https://github.com/somerandomuser
https://twitter.com/somerandomuser
data is your dictionary.
for social_profile in data["socialProfiles"]:
for link in social_profile:
if link['typeId'] == "twitter" or link['typeId'] == "github":
print (link["url"])

Parse JSON file with Python

I trying to import a nested JSON file. I am using Python 3.0
The JSON file looks like this
"funds": [
{
"branch": "****",
"controlDigits": "**",
"accountNumber": "7605390244",
"balance": {
"amount": "71.1",
"currency": "EUR"
},
"fundName": "Eurobits Funds 0",
"webAlias": "Eurobits Funds 0",
"performance": "4.41",
"performanceDescription": "",
"yield": {
"amount": "0.0",
"currency": "EUR"
},
"quantity": "10.00",
"valueDate": "30/03/2017",
"transactions": [
{
"operationType": "1",
"operationDescription": "MOVILIZACION HACIA DENTRO",
"operationDate": "30/03/2017",
"fundName": "B EVOLUCION PRUDEN",
"quantity": "-809.27",
"unitPrice": "7.98",
"operationAmount": {
"amount": "-6457.97",
"currency": "EUR"
}
}
]
}
]
I am using this code:
from pandas.io.json import json_normalize
data_json = open("prueba.json",mode='r', encoding="utf8").read().replace('\n', '').replace('\t', '')
data_python = json.loads(data_json)
json_normalize(data_python['funds'])
this code works fine but field transaction is not expanded
In order to expand transactions I have tried this:
json_normalize(data_python,['funds','transactions'])
The information from transactions is expanded but I loose the other information
Besides that, the field amount looks like this:
{'amount': '1.00', 'currency': ''}
and I am not able to get it into separate fields
My question is how can I combine all the information into a single dataframe?
Try d['funds'][0]['transactions'] instead, where d is the name of your dictionary.

Getting item names from Square Connect API

I am wondering how to get this item description / information from transactions on Square. For me, even using:
'/v2/locations/{0}/transactions/{1}'.format(LOC_ID, tid)
Does not return any item names, instead I get completely anonymous/useless information:
{
"transaction": {
"id": "BZDxxxxxx",
"location_id": "3PBxxxxx",
"created_at": "2016-10-14T22:55:33Z",
"tenders": [
{
"id": "VJO1rxxxxx",
"location_id": "3PBxxxx",
"transaction_id": "BZDxxxxxx",
"created_at": "2016-10-14T22:55:31Z",
"amount_money": {
"amount": 2800,
"currency": "USD"
},
"processing_fee_money": {
"amount": 0,
"currency": "USD"
},
"type": "OTHER"
}
],
"product": "REGISTER",
"client_id": "1E7xxxx"
}
}
How do I go from what is returned above to the item name that is shown on the website transaction list?
You can itemize your transactions with the Orders Endpoints Have you tried using the /v1/{location_id}/payments endpoint? You can get some more information about the items there.
https://docs.connect.squareup.com/api/connect/v1/#updatingorderstate

Python .get nested Json values

I have a json file with the following example json entry:
{
"title": "Test prod",
"leafPage": true,
"type": "product",
"product": {
"title": "test product",
"offerPrice": "$19.95",
"offerPriceDetails": {
"amount": 19.95,
"text": "$19.95",
"symbol": "$"
},
"media": [
{
"link": "http://www.test.com/cool.jpg",
"primary": true,
"type": "image",
"xpath": "/html[1]/body[1]/div[1]/div[3]/div[2]/div[1]/div[1]/div[1]/div[1]/a[1]/img[1]"
}
],
"availability": true
},
"human_language": "en",
"url": "http://www.test.com"
}
I can post via python script this to my test server perfectly when I use:
"text": entry.get("title"),
"url": entry.get("url"),
"type": entry.get("type"),
However I cannot get the following nested item to upload the values, how do I structure the python json call to get a nested python json entry?
Ive tried the below without success, I need to have it as .get because there are different fields currently in the json file and it errors out without the .get call.
"Amount": entry.get("product"("offerPrice"))
Any help on how to structure the nested json entry would be very much appreciated.
You need to do:
"Amount": entry.get("product", {}).get("offerPrice")
entry.get("product", {}) returns a product dictionary (or an empty dictionary if there is no product key).

Categories