I have a little problem with making paypal invoices using paypal sdk in my django project. when I trying to execute this code
invoice_id = ''
invoice = Invoice({
"merchant_info": {
"email": '', # You must change this to your sandbox email account
"first_name": str(merchant.first_name),
"last_name": str(merchant.last_name),
"business_name": str(merchant_full_name),
"phone": {
"country_code": "001",
"national_number": str(merchant.phone)
},
"address": {
"line1": str(merchant_address.address),
"city": str(merchant_address.city),
"state": str(merchant_address.state),
"postal_code": str(merchant_address.zip_code),
"country_code": "US"
}
},
"billing_info": [{"email": buyer.paypal_address}],
"items": [
{
"name": "Slab",
"quantity": 1,
"unit_price": {
"currency": "USD",
"value": float(slab.price)
}
}
],
"note": "Invoice for slab",
"payment_term": {
"term_type": "NET_45"
},
"shipping_info": {
"first_name": buyer.first_name,
"last_name": buyer.last_name,
"business_name": str(buyer_full_name),
"phone": {
"country_code": "001",
"national_number": str(buyer.phone)
},
"address": {
"line1": str(buyer_address.address),
"city": str(buyer_address.city),
"state": str(buyer_address.state),
"postal_code": str(buyer_address.zip_code),
"country_code": "US"
}
},
"shipping_cost": {
"amount": {
"currency": "USD",
"value": 0
}
}
})
if invoice.create():
print(json.dumps(invoice.to_dict(), sort_keys=False, indent=4))
invoice_id = invoice['id']
return invoice_id
else:
print(invoice.error)
My server return me those errors
INFO:paypalrestsdk.api:Request[POST]:
https://api.sandbox.paypal.com/v1/oauth2/token
INFO:paypalrestsdk.api:Response[200]: OK, Duration: 1.156739s.
INFO:paypalrestsdk.api:PayPal-Request-Id:
660f7807-961f-4460-bafd-18412b489a91
INFO:paypalrestsdk.api:Request[POST]:
https://api.sandbox.paypal.com/v1/invoicing/invoices
INFO:paypalrestsdk.api:Response[401]: Unauthorized, Duration:
1.213655s. INFO:paypalrestsdk.api:Request[POST]: https://api.sandbox.paypal.com/v1/oauth2/token
INFO:paypalrestsdk.api:Response[200]: OK, Duration: 1.53491s.
As I understand it's a problem with paypal token, right?
You need to authenticate your request:
import requests, base64
# you can only encode byte objects
credentials = b"userid:password"
b64Val = base64.b64encode(credentials)
r=requests.post(api_URL,
headers={"Authorization": "Basic %s" % b64Val},
data=payload)
Related
import xml.etree.ElementTree as ET
from zeep import Client, Settings
from zeep.exceptions import Fault, TransportError, XMLSyntaxError
# Set Connection
settings = Settings(strict=False, xml_huge_tree=True)
client = Client('SCHEMA-WSDLs/RateWS.wsdl', settings=settings)
# Set SOAP headers
headers = {
'UPSSecurity': {
'UsernameToken': {
'Username': 'username',
'Password': 'password'
},
'ServiceAccessToken': {
'AccessLicenseNumber': 'asdasdasdasd'
}
}
}
# Create request dictionary
requestDictionary = {
"RequestOption": "Shop",
"TransactionReference": {
"CustomerContext": "Your Customer Context"
}
}
# Create rate request dictionary
rateRequestDictionary = {
"Package": {
"Dimensions": {
"Height": "10",
"Length": "5",
"UnitOfMeasurement": {
"Code": "IN",
"Description": "inches"
},
"Width": "4"
},
"PackageWeight": {
"UnitOfMeasurement": {
"Code": "Lbs",
"Description": "pounds"
},
"Weight": "1"
},
"PackagingType": {
"Code": "02",
"Description": "shop"
}
},
"Service": {
"Code": "03",#3 – Standard List Rates
"Description": "Service Code"
},
"ShipFrom": {
"Address": {
"AddressLine": [
"1 toronto rd",
],
"City": "North York",
"CountryCode": "CA",
"PostalCode": "M3J1C8",
"StateProvinceCode": "ON"
},
"Name": "Name"
},
"ShipTo": {
"Address": {
"AddressLine": "15 Hillpark Trail",
"City": "Brampton",
"CountryCode": "CA",
"PostalCode": "L6S1R1",
"StateProvinceCode": "ON"
},
"Name": "Name"
},
"Shipper": {
"Address": {
"AddressLine": [
"Street Name",
],
"City": "Toronto",
"CountryCode": "CA",
"PostalCode": "M3J1C8",
"StateProvinceCode": "ON"
},
"Name": "ZTL",
"ShipperNumber": "+66666666"
}
}
# Try operation
try:
response = client.service.ProcessRate(_soapheaders=headers, Request=requestDictionary,
Shipment=rateRequestDictionary)
print(response)
except Fault as error:
print(ET.tostring(error.detail))
//
how can i get the value of the rate from the response.. just the amount to charge and the code like ground, express or others...,
i want to make an HTML page to choose between express and ground with the value beside,
json response in htmlso the user can choose, then the value of the shipping goes to the total charges in the cart...,
im just getting started with json and apis call
.... //
I am using MSGraph Api with Python as a backend and angular as a frontend to pull data but given output is showing in json format with all metadata i want to show specific data from it. How can i do that.
Python Code:
#app.route('/getChannel',methods=['GET','POST'])
def Channels():
token = _get_token_from_cache(app_config.SCOPE)
if not token:
return redirect(url_for("login"))
channel_data = requests.get(
app_config.ChannelURL,
headers={'Authorization': 'Bearer ' + token['access_token']},
).json()['value']
return render_template('team.html',result=channel_data)
json output
[
{
"createdDateTime": "2021-05-08T04:47:39.67Z",
"description": null,
"displayName": "General",
"email": "",
"id": "19:c9f316c845794a21a1ff2ba50be2bb1e#thread.tacv2",
"isFavoriteByDefault": null,
"membershipType": "standard",
"webUrl":
},
{
"createdDateTime": "2021-05-08T05:00:11.348Z",
"description": null,
"displayName": "Developement",
"email": "",
"id": "19:da1aff92f51f416c9390881e2fa70716#thread.tacv2",
"isFavoriteByDefault": true,
"membershipType": "standard",
"webUrl":
},
{
"createdDateTime": "2021-05-09T15:16:46.27Z",
"description": "testing",
"displayName": "channel1",
"email": "",
"id": "19:e81758e4858e4f598d31214282d6c100#thread.tacv2",
"isFavoriteByDefault": false,
"membershipType": "standard",
"webUrl":
}
]
i have a sample json file from a webhook response and i will want to extract just two data set from the JSON how can i do that using python. assuming i want to get the subscription code, and plan code values. thanks in anticipation
"event": "subscription.create",
"data": {
"domain": "test",
"status": "active",
"subscription_code": "SUB_vsyqdmlzble3uii",
"amount": 50000,
"cron_expression": "0 0 28 * *",
"next_payment_date": "2016-05-19T07:00:00.000Z",
"open_invoice": null,
"createdAt": "2016-03-20T00:23:24.000Z",
"plan": {
"name": "Monthly retainer",
"plan_code": "PLN_gx2wn530m0i3w3m",
"description": null,
"amount": 50000,
"interval": "monthly",
"send_invoices": true,
"send_sms": true,
"currency": "NGN"
},
"authorization": {
"authorization_code": "AUTH_96xphygz",
"bin": "539983",
"last4": "7357",
"exp_month": "10",
"exp_year": "2017",
"card_type": "MASTERCARD DEBIT",
"bank": "GTBANK",
"country_code": "NG",
"brand": "MASTERCARD"
},
"customer": {
"first_name": "BoJack",
"last_name": "Horseman",
"email": "bojack#horsinaround.com",
"customer_code": "CUS_xnxdt6s1zg1f4nx",
"phone": "",
"metadata": {},
"risk_action": "default"
},
"created_at": "2016-10-01T10:59:59.000Z"
}
}
You can use the built-in json library. For example:
import json
#if your json is in file
dict_from_file = json.load(open("foo.json"))
#if your json is in a string
dict_from_string = json.loads(string)
Everything with my script runs fine until I try to run it through a for loop. Specifically, when I attempt to index a specific array within the object. Before I get to the The script is intended to grab the delivery date for each tracking number in my list.
This is my script:
import requests
import json
TrackList = ['1Z3X756E0310496105','1ZX0373R0303581450','1ZX0373R0103574417']
url = 'https://onlinetools.ups.com/rest/Track'
para1 = '...beginning of JSON request string...'
para2 = '...end of JSON request string...'
for TrackNum in TrackList:
parameters = para1+TrackNum+para2
resp = requests.post(url = url, data = parameters, verify=False)
data = json.loads(resp.text)
DelDate = data['TrackResponse']['Shipment']['Package'][0]['Activity'][0]['Date']
print(DelDate)
JSON API Response (if needed):
{
"TrackResponse": {
"Response": {
"ResponseStatus": {
"Code": "1",
"Description": "Success"
},
"TransactionReference": {
"CustomerContext": "Analytics Inquiry"
}
},
"Shipment": {
"InquiryNumber": {
"Code": "01",
"Description": "ShipmentIdentificationNumber",
"Value": "1ZX0373R0103574417"
},
"Package": {
"Activity": [
{
"ActivityLocation": {
"Address": {
"City": "OKLAHOMA CITY",
"CountryCode": "US",
"PostalCode": "73128",
"StateProvinceCode": "OK"
},
"Code": "M3",
"Description": "Front Desk",
"SignedForByName": "CUMMINGS"
},
"Date": "20190520",
"Status": {
"Code": "9E",
"Description": "Delivered",
"Type": "D"
},
"Time": "091513"
},
{
"ActivityLocation": {
"Address": {
"City": "Oklahoma City",
"CountryCode": "US",
"StateProvinceCode": "OK"
},
"Description": "Front Desk"
},
"Date": "20190520",
"Status": {
"Code": "OT",
"Description": "Out For Delivery Today",
"Type": "I"
},
"Time": "085943"
},
{
"ActivityLocation": {
"Address": {
"City": "Oklahoma City",
"CountryCode": "US",
"StateProvinceCode": "OK"
},
"Description": "Front Desk"
},
"Date": "20190520",
"Status": {
"Code": "DS",
"Description": "Destination Scan",
"Type": "I"
},
"Time": "011819"
},
{
"ActivityLocation": {
"Address": {
"City": "Oklahoma City",
"CountryCode": "US",
"StateProvinceCode": "OK"
},
"Description": "Front Desk"
},
"Date": "20190519",
"Status": {
"Code": "AR",
"Description": "Arrival Scan",
"Type": "I"
},
"Time": "235100"
},
{
"ActivityLocation": {
"Address": {
"City": "DFW Airport",
"CountryCode": "US",
"StateProvinceCode": "TX"
},
"Description": "Front Desk"
},
"Date": "20190519",
"Status": {
"Code": "DP",
"Description": "Departure Scan",
"Type": "I"
},
"Time": "195500"
},
{
"ActivityLocation": {
"Address": {
"City": "DFW Airport",
"CountryCode": "US",
"StateProvinceCode": "TX"
},
"Description": "Front Desk"
},
"Date": "20190517",
"Status": {
"Code": "OR",
"Description": "Origin Scan",
"Type": "I"
},
"Time": "192938"
},
{
"ActivityLocation": {
"Address": {
"CountryCode": "US"
},
"Description": "Front Desk"
},
"Date": "20190517",
"Status": {
"Code": "MP",
"Description": "Order Processed: Ready for UPS",
"Type": "M"
},
"Time": "184621"
}
],
"PackageWeight": {
"UnitOfMeasurement": {
"Code": "LBS"
},
"Weight": "2.00"
},
"ReferenceNumber": [
{
"Code": "01",
"Value": "8472745558"
},
{
"Code": "01",
"Value": "5637807:1007379402:BN81-17077A:1"
},
{
"Code": "01",
"Value": "5637807"
}
],
"TrackingNumber": "1ZX0373R0103574417"
},
"PickupDate": "20190517",
"Service": {
"Code": "001",
"Description": "UPS Next Day Air"
},
"ShipmentAddress": [
{
"Address": {
"AddressLine": "S 600 ROYAL LN",
"City": "COPPELL",
"CountryCode": "US",
"PostalCode": "750193827",
"StateProvinceCode": "TX"
},
"Type": {
"Code": "01",
"Description": "Shipper Address"
}
},
{
"Address": {
"City": "OKLAHOMA CITY",
"CountryCode": "US",
"PostalCode": "73128",
"StateProvinceCode": "OK"
},
"Type": {
"Code": "02",
"Description": "ShipTo Address"
}
}
],
"ShipmentWeight": {
"UnitOfMeasurement": {
"Code": "LBS"
},
"Weight": "2.00"
},
"ShipperNumber": "X0373R"
}
}
}
Below is the error I receive:
Traceback (most recent call last):
File "/Users/***/Library/Preferences/PyCharmCE2019.1/scratches/UPS_API.py", line 15, in <module>
DelDate = data['TrackResponse']['Shipment']['Package'][0]['Activity'][0]['Date']
KeyError: 0
You're trying to index "Package" at index 0, but it's an object not an array. So you should be accessing ['Package']['Activity']
just take away the [0] because there is no [1] or [2]
I post some JSON to a view. I want to now parse the data and add it to my database.
I need to get the properties name and theme and iterate over the array pages. My JSON is as follows:
{
"name": "xaAX",
"logo": "",
"theme": "b",
"fullSiteLink": "http://www.hello.com",
"pages": [
{
"id": "1364484811734",
"name": "Page Name",
"type": "basic",
"components": {
"img": "",
"text": ""
}
},
{
"name": "Twitter",
"type": "twitter",
"components": {
"twitter": {
"twitter-username": "zzzz"
}
}
}
]
}
Here is what I have so far:
def smartpage_create_ajax(request):
if request.POST:
# get stuff and loop over each page?
return HttpResponse('done')
python provides json to encode/decode json
import json
json_dict = json.loads(request.POST['your_json_data'])
json_dict['pages']
[
{
"id": "1364484811734",
"name": "Page Name",
"type": "basic",
"components": {
"img": "",
"text": ""
}
},
{
"name": "Twitter",
"type": "twitter",
"components": {
"twitter": {
"twitter-username": "zzzz"
}
}
},
}
]