In my python project I have to implement paypal recurring payments.
I have installed the paypal sdk and created a file to create a PayPal payment page, like this:
import paypalrestsdk
from paypalrestsdk import BillingPlan
from paypalrestsdk import BillingAgreement
from paypalrestsdk import Payment
import webbrowser
from urllib import parse
paypalrestsdk.configure({
'mode': 'sandbox', # sandbox or live
'client_id': <my app client id>,
'client_secret': <my app secret>})
def create_bill():
billing_plan = BillingPlan({
"name": "Plan with Regular and Trial Payment Definitions",
"description": "Plan with regular and trial payment definitions.",
"type": "INFINITE",
"payment_definitions": [
{
"name": "Regular payment definition",
"type": "REGULAR",
"frequency": "MONTH",
"frequency_interval": "1",
"amount": {
"value": "100",
"currency": "USD"
},
"cycles": "0",
"charge_models": [
{
"type": "SHIPPING",
"amount": {
"value": "10",
"currency": "USD"
}
},
{
"type": "TAX",
"amount": {
"value": "12",
"currency": "USD"
}
}
]
},
{
"name": "Trial payment definition",
"type": "TRIAL",
"frequency": "WEEK",
"frequency_interval": "5",
"amount": {
"value": "9.19",
"currency": "USD"
},
"cycles": "2",
"charge_models": [
{
"type": "SHIPPING",
"amount": {
"value": "1",
"currency": "USD"
}
},
{
"type": "TAX",
"amount": {
"value": "2",
"currency": "USD"
}
}
]
}
],
"merchant_preferences": {
"setup_fee": {
"value": "1",
"currency": "USD"
},
"return_url": "https://example.com",
"cancel_url": "https://example.com/cancel",
"auto_bill_amount": "YES",
"initial_fail_amount_action": "CONTINUE",
"max_fail_attempts": "0"
}
})
# Create billing plan
if billing_plan.create():
print("Billing Plan [%s] created successfully" % billing_plan.id)
# Activate billing plan
if billing_plan.activate():
billing_plan = BillingPlan.find(billing_plan.id)
print("Billing Plan [%s] state changed to %s" % (billing_plan.id, billing_plan.state))
return billing_plan
else:
print(billing_plan.error)
else:
print(billing_plan.error)
def create_agreement(ret_bil):
billing_agreement = BillingAgreement({
"name": "Fast Speed Agreement",
"description": "Agreement for Fast Speed Plan",
"start_date": "2018-03-29T00:37:04Z",
"plan": {
"id": str(ret_bil.id)
},
"payer": {
"payment_method": "paypal"
},
"shipping_address": {
"line1": "StayBr111idge Suites",
"line2": "Cro12ok Street",
"city": "San Jose",
"state": "CA",
"postal_code": "95112",
"country_code": "US"
}
})
if billing_agreement.create():
# Extract redirect url
for link in billing_agreement.links:
if link.method == "REDIRECT":
# Capture redirect url
redirect_url = str(link.href)
# REDIRECT USER TO redirect_url
webbrowser.open(redirect_url)
else:
print(billing_agreement.error)
if __name__ == "__main__":
create_agreement(create_bill())
But when I run the code above, Paypal starts with agreement description but I can't see the item details and description defined in the BilingPlan (I expected to see the detail about items, trial period, amount, recurrence etc)
Is there something wrong in my code? This is the first time I implement Paypal in my project; have I written my code correctly to implement recurrent payments?
So many Thanks in advance
PayPal will not show the recurring period, amount and service details.
You have to show that in your website's page and proceed to PayPal.
Related
My main goal is to get all today meetings in a sharepoint site (using python)
What i already do:
Filter meetings properly and get the specific fields
?$filter=fields/fRecurrence eq 1 and fields/EndDate ge '2022-11-08 18:00:00'&$expand=fields($select=Title,EventDate,EndDate,fRecurrence,RecurrenceData,EventType, Duration,TimeZone)
Request all meetings with all needed info, inclusive RecurrenceData (XLM)
There is the HTTP request and a response sample (some items and info as been removed):
REQUEST:
https://graph.microsoft.com/v1.0/sites/[SITE]/sites/[SITE]/lists/[ID]/items?$filter=fields/fRecurrence eq 1 and fields/EndDate ge '2022-11-08 18:00:00'&$expand=fields($select=Title,EventDate,EndDate,fRecurrence,RecurrenceData,Eventype, Duration,TimeZone)
RESPONSE:
"#odata.context": "https://graph.microsoft.com/v1.0/$metadata#sites('[SITE]')/sites('[SITE]')/lists('[ID]')/items(fields(Title,EventDate,EndDate,fRecurrence,RecurrenceData,EventType,Duration,TimeZone,RecurrenceID,UniqueId))",
"value": [
{
"#odata.etag": "[TAG]",
"createdDateTime": "2019-09-09T17:42:40Z",
"eTag": "[TAG]",
"id": "2065",
"lastModifiedDateTime": "2019-09-10T08:51:34Z",
"webUrl": "https://[BUISNESS COMPANY].sharepoint.com/teams/[THINGS]/[THINGS]/Lists/[ROOM NAME]/2022_.000",
"createdBy": {
"user": {
"email": "[USER]",
"id": "[UID]",
"displayName": "[USER NAME]"
}
},
"lastModifiedBy": {
"user": {
"email": "[USER]",
"id": "[UID]",
"displayName": "[USER NAME]"
}
},
"parentReference": {
"id": "[ID]",
"siteId": "[BUISNESS COMPANY].sharepoint.com,[UID],[UID]"
},
"contentType": {
"id": "[THINGS]",
"name": "Event"
},
"https://graph.microsoft.com/v1.0/$metadata#sites('[SITE]')/sites('[SITE]')/lists('[ID]')/items(fields(Title,EventDate,EndDate,fRecurrence,RecurrenceData,EventType,Duration,TimeZone,RecurrenceID,UniqueId))/$entity",
"fields": {
"#odata.etag": "[TAG]",
"Title": "TITLE",
"EventDate": "2019-12-10T10:00:00Z",
"EndDate": "2169-09-12T10:00:00Z",
"fRecurrence": true,
"EventType": 1,
"Duration": 3600,
"RecurrenceData": "<recurrence><rule><firstDayOfWeek>mo</firstDayOfWeek><repeat><monthlyByDay tu=\"TRUE\" weekdayOfMonth=\"second\" monthFrequency=\"3\" /></repeat><repeatForever>FALSE</repeatForever></rule></recurrence>",
"TimeZone": [THINGS],
"UniqueId": "[UID]"
}
}, {...}, {...}, ... ]
In "EventDate": "2019-12-10T10:00:00Z" and the "EndDate": "2169-09-12T10:00:00Z" we have the start and end date of the "event", however this event is recurent, and have some "rules" -> RecurrenceData.
QUESTIONS:
HOW CAN I PARSE THE RULES (using python) TO KNOW IF WE HAVE THIS MEETING TODAY (2022-11-08 18:00:00) OR NOT;
2)OR, HOW CAN I MEKE A REQUEST TO THE SERVER AND RECEVE ONLY THE TODAYS MEETINGS (DOESN'T METTER IF RECURENT OR NOT)
Maybe usefull links:
In C#
Sherepoint recurrence data schema
I've been working on an integration to create a dialog for a Slack bot that uses python 3, AWS API Gateway, and AWS Lambda. I'm currently working on the Slack side for integration versus the end purpose of my function.
I can get my bot running with some responses if I remove the dialog and just have it chat with the user from the tutorials here and here, however once I add a dialog into the mix the bot no longer responds. I've tried basing my code off the the example code from the Slack API's github but it doesn't help. I would appreciate any guidance on how to do this using python 3.
Code below:
import os
import logging
import urllib
import boto3
from slackclient import SlackClient
LOGGER = logging.getLogger()
LOGGER.setLevel(logging.DEBUG)
# Grab the Bot OAuth token from the environment + slack verification
BOT_TOKEN = os.environ["BOT_TOKEN"]
SLACK_VERIFICATION_TOKEN = os.environ["SLACK_VERIFICATION_TOKEN"]
slack_client = SlackClient(BOT_TOKEN)
SLACK_URL = "https://slack.com/api/dialog.open"
def lambda_handler(data, context):
''' Entry point for API Gateway '''
slack_event = data['event']
if "bot_id" in slack_event:
logging.warn("Ignore bot event")
else:
channel_id = slack_event["channel"]
support_form = slack_client.api_call(
"dialog.open",
trigger_id = slack_event["trigger_id"],
dialog = {
"title": "AWS Support Ticket",
"submit_label": "Submit",
"callback_id": "support_form",
"elements": [
{
"label": "Subject",
"type": "text",
"name": "subject",
"placeholder": "Support Case Subject"
},
{
"label": "Description",
"type": "textarea",
"name": "body",
"placeholder": "Describe the issue you would like to open a support case about"
},
{
"type": "select",
"label": "What is your issue type?",
"name": "issueType",
"options": [
{
"label": "Customer Service",
"value": "customerservice"
},
{
"label": "Technical",
"value": "technical"
}
]
},
{
"label": "What is your severity level?",
"type": "select",
"name": "serverity",
"options": [
{
"label": "5 - General Guidance",
"value": "5"
},
{
"label": "4 - System Impaired",
"value": "4"
},
{
"label": "3 - Production System Impaired",
"value": "3"
},
{
"label": "2 - Production System Down",
"value": "2"
},
{
"label": "1 - Business-critical System Down",
"value": "1"
}
]
},
{
"label": "Service Code",
"type": "text",
"name": "serviceCode"
},
{
"label": "Category Code",
"type": "text",
"name": "categoryCode"
},
{
"label": "Please choose your language",
"type": "select",
"name": "language",
"options": [
{
"label": "English",
"value": "english"
},
{
"label": "Japanese",
"value": "japanese"
}
]
},
{
"label": "What is your attachement set id?",
"type": "text",
"name": "attachementSetId"
},
{
"label": "Please enter the emails you want cc'd on this case:",
"type": "textarea",
"name": "ccEmailAddresses"
}
]
}
})
data = urllib.parse.urlencode(
(
("token", BOT_TOKEN),
("channel", channel_id),
("dialog", support_form)
)
)
# Construct the HTTP request that will be sent to the Slack API.
request = urllib.request.Request(
SLACK_URL,
data=data,
method="POST"
)
# Add a header mentioning that the text is URL-encoded.
request.add_header(
"Content-Type",
"application/x-www-form-urlencoded"
)
# Fire off the request!
urllib.request.urlopen(request).read()
# Everything went fine.
return "200 OK"
I am trying to integrate paypal with my django app using paypalrestsdk
https://github.com/paypal/PayPal-Python-SDK
I use the same code to generate payment request
views.py:
def payment_create(request):
paypalrestsdk.configure({
"mode": "sandbox", # sandbox or live
"client_id": "xxxxx",
"client_secret": "xxxxxx" })
payment = paypalrestsdk.Payment({
"intent": "sale",
"payer": {
"payment_method": "paypal"},
"redirect_urls": {
"return_url": "http://localhost:3000/payment/execute",
"cancel_url": "http://localhost:3000/"},
"transactions": [{
"item_list": {
"items": [{
"name": "item",
"sku": "item",
"price": "5.00",
"currency": "USD",
"quantity": 1}]},
"amount": {
"total": "5.00",
"currency": "USD"},
"description": "This is the payment transaction description."}]})
if payment.create():
print("Payment created successfully")
else:
print(payment.error)
however it produced this error:
ValueError at /payment/
The view somecomapp.views.payment_create didn't return an HttpResponse object. It returned None instead.
The question is what is the problem with this and how to generate a proper paypal payment with django ?
this HttpResponseRedirect fix the problem:
def payment_create(request):
paypalrestsdk.configure({
"mode": "sandbox", # sandbox or live
"client_id": "xxxxx",
"client_secret": "xxxxxx" })
payment = paypalrestsdk.Payment({
"intent": "sale",
"payer": {
"payment_method": "paypal"},
"redirect_urls": {
"return_url": "http://localhost:3000/payment/execute",
"cancel_url": "http://localhost:3000/"},
"transactions": [{
"item_list": {
"items": [{
"name": "item",
"sku": "item",
"price": "5.00",
"currency": "USD",
"quantity": 1}]},
"amount": {
"total": "5.00",
"currency": "USD"},
"description": "This is the payment transaction description."}]})
if payment.create():
print("Payment created successfully")
for link in payment.links:
if link.rel == "approval_url":
# Convert to str to avoid Google App Engine Unicode issue
# https://github.com/paypal/rest-api-sdk-python/pull/58
approval_url = str(link.href)
print("Redirect for approval: %s" % (approval_url))
return HttpResponseRedirect(approval_url)
else:
print(payment.error)
I have a response object that I am receiving from an api call. The response has several objects that are returned in a single call. What I want to do is grab information from each of the objects returned and store them in varialbes to use them within the application. I know to grab info from a json response when it returns a single objects but I am getting confused with multiples objects... I know how to automate the iteration process through something like a forloop... it wont iterate.
here is a sample response that I am getting:
I want to grab the _id from both items.
{
'user':"<class 'synapse_pay_rest.models.users.user.User'>(id=..622d)",
'json':{
'_id':'..6e80',
'_links':{
'self':{
'href':'https://uat-api.synapsefi.com/v3.1/users/..22d/nodes/..56e80'
}
},
'allowed':'CREDIT-AND-DEBIT',
'client':{
'id':'..26a34',
'name':'Charlie Brown LLC'
},
'extra':{
'note':None,
'other':{
},
'supp_id':''
},
'info':{
'account_num':'8902',
'address':'PO BOX 85139, RICHMOND, VA, US',
'balance':{
'amount':'750.00',
'currency':'USD'
},
'bank_long_name':'CAPITAL ONE N.A.',
'bank_name':'CAPITAL ONE N.A.',
'class':'SAVINGS',
'match_info':{
'email_match':'not_found',
'name_match':'not_found',
'phonenumber_match':'not_found'
},
'name_on_account':' ',
'nickname':'SynapsePay Test Savings Account - 8902',
'routing_num':'6110',
'type':'BUSINESS'
},
<class 'synapse_pay_rest.models.nodes.ach_us_node.AchUsNode'>({
'user':"<class 'synapse_pay_rest.models.users.user.User'>(id=..622d)",
'json':{
'_id':'..56e83',
'_links':{
'self':{
'href':'https://uat-api.synapsefi.com/v3.1/users/..d622d/nodes/..6e83'
}
},
'allowed':'CREDIT-AND-DEBIT',
'client':{
'id':'599378ec6aef1b0021026a34',
'name':'Charlie Brown LLC'
},
'extra':{
'note':None,
'other':{
},
'supp_id':''
},
'info':{
'account_num':'8901',
'address':'PO BOX 85139, RICHMOND, VA, US',
'balance':{
'amount':'800.00',
'currency':'USD'
},
'bank_long_name':'CAPITAL ONE N.A.',
'bank_name':'CAPITAL ONE N.A.',
'class':'CHECKING',
'match_info':{
'email_match':'not_found',
'name_match':'not_found',
'phonenumber_match':'not_found'
},
'name_on_account':' ',
'nickname':'SynapsePay Test Checking Account - 8901',
'routing_num':'6110',
'type':'BUSINESS'
},
})
Here is the code that I have:
It wont grab any values...
the iteration needs to be done to the nodes variable which is hte json response object.
def listedLinkAccounts(request):
currentUser = loggedInUser(request)
currentProfile = Profile.objects.get(user = currentUser)
user_id = currentProfile.synapse_id
synapseUser = SynapseUser.by_id(client, str(user_id))
options = {
'page':1,
'per_page':20,
'type': 'ACH-US',
}
nodes = Node.all(synapseUser, **options)
print(nodes)
response = nodes
_id = response["_id"]
print(_id)
return nodes
here is a sample api response from the api documenation:
{
"error_code": "0",
"http_code": "200",
"limit": 20,
"node_count": 5,
"nodes": [
{
"_id": "594e5c694d1d62002f17e3dc",
"_links": {
"self": {
"href": "https://uat-api.synapsefi.com/v3.1/users/594e0fa2838454002ea317a0/nodes/594e5c694d1d62002f17e3dc"
}
},
"allowed": "CREDIT-AND-DEBIT",
"client": {
"id": "589acd9ecb3cd400fa75ac06",
"name": "SynapseFI"
},
"extra": {
"other": {},
"supp_id": "ABC124"
},
"info": {
"account_num": "7443",
"address": "PLACE DE LA REPUBLIQUE 4 CROIX 59170 FR",
"balance": {
"amount": "0.00",
"currency": "USD"
},
"bank_long_name": "3 SUISSES INTERNATIONAL",
"bank_name": "3 SUISSES INTERNATIONAL",
"name_on_account": " ",
"nickname": "Some Account"
},
"is_active": true,
"timeline": [
{
"date": 1498307689471,
"note": "Node created."
},
{
"date": 1498307690130,
"note": "Unable to send micro deposits as node type is not ACH-US."
}
],
"type": "WIRE-INT",
"user_id": "594e0fa2838454002ea317a0"
},
{
...
},
{
...
},
...
],
"page": 1,
"page_count": 1,
"success": true
}
I'm trying to get all the locations that a company in LinkedIn has, but it seems that it's limiting to only 5. What are the params that I need to change to increase the number of locations returned?
For example, my company, Slalom Consulting, has about 15 locations, but it's only returning 5. I can't get that second '_total' to increase above 5.
app.get_companies(company_ids=[166000], selectors=['name', 'locations'], params={})
{
"_total": 1,
"values": [
{
"_key": "166000",
"locations": {
"_total": 5,
"values": [
{
"contactInfo": {
"fax": "",
"phone1": "206 483 5700"
},
"address": {
"postalCode": "98104",
"city": "Seattle",
"street1": "Suite 1900"
}
},
{
"contactInfo": {
"fax": "310-322-6888",
"phone1": "310-322-6800"
},
"address": {
"postalCode": "90245",
"city": "El Segundo",
"street1": "Suite 600"
}
},
{
"contactInfo": {
"fax": "415-593-3451",
"phone1": "415-593-3450"
},
"address": {
"postalCode": "94105",
"city": "San Francisco",
"street1": "Suite 1550"
}
},
{
"contactInfo": {
"fax": "972-294-7301",
"phone1": "972-294-7300"
},
"address": {
"postalCode": "75024",
"city": "Plano",
"street1": "Suite 480"
}
},
{
"contactInfo": {
"fax": "312.329.0461",
"phone1": "312.329.0401"
},
"address": {
"postalCode": "60601",
"city": "Chicago",
"street1": "Suite 5300"
}
}
]
},
"name": "Slalom Consulting"
}
]
}
I know that I need to add some params, but not sure what I need to do to get locations more than 5.
from linkedin import linkedin
import json
import csv
##start connection to LinkedIn
CONSUMER_KEY = 'xxx'
CONSUMER_SECRET = 'xxx'
USER_TOKEN = 'xxx'
USER_SECRET = 'xxx'
RETURN_URL = '' # Not required for developer authentication
# Instantiate the developer authentication class
auth = linkedin.LinkedInDeveloperAuthentication(CONSUMER_KEY, CONSUMER_SECRET, USER_TOKEN, USER_SECRET,RETURN_URL, permissions=linkedin.PERMISSIONS.enums.values())
app = linkedin.LinkedInApplication(auth)
co = app.get_companies(company_ids=[166000], selectors=['name', 'locations'], params={})
print co