"on_session" vs "off_session" in Stripe - python

I can set on_session and off_session for payment_intent_data.setup_future_usage and payment_method_options.card.setup_future_usage as shown below. *I use Python:
checkout_session = stripe.checkout.Session.create(
# ...
payment_intent_data={
"setup_future_usage": "on_session" # Here
},
payment_method_options={
"card": {
"setup_future_usage": "on_session" # Here
},
},
# ...
)
checkout_session = stripe.checkout.Session.create(
# ...
payment_intent_data={
"setup_future_usage": "off_session" # Here
},
payment_method_options={
"card": {
"setup_future_usage": "off_session" # Here
}
},
# ...
)
But, I cannot exactly understand what are on_session and off_session even though I read Optimizing cards for future payments on Stripe Doc.
So, what are on_session and off_session?

Off-session payments refers to payments where the customer isn’t present (on your website or application) at the time of payment.
For example, when you sign up for a Subscription on the merchant's website and provide your card details for the first payment - you're on-session.
Subsequent payments where your card is auto-debited - you're off-session.

"On_session" and "off_session" refer to the usage of a saved payment method for future transactions. "On_session" means the payment method is stored for future use after the current transaction is complete. "Off_session" means the payment method is not stored for future use and can only be used for the current transaction.

Related

Accept international stripe payments in flask from India

I have tried stripe but the problem is that in the docs they have listed that for accepting international payments from India, I have to be registered and also I need to add billing address, name of the customer and the payment intent. They have provided documentation on how to add names and payment intent, but I don't know how to implement the provided code in my application.
So, pls tell me how to do it...
Just in case you, this is my checkout code
#app.route('/create-checkout-session', methods=['POST'])
def create_checkout_session():
session = stripe.checkout.Session.create(
payment_method_types=['card'],
line_items=[{
'price_data': {
'currency': 'usd',
'product_data': {
'name': 'T-shirt',
},
'unit_amount': 2000,
},
'quantity': 1,
}],
mode='payment',
success_url=redirect("success.html"),
cancel_url=redirect("cancel.html"),
)
If you're using Stripe Checkout you don't need to change your code; Checkout will collect the required information from your customer (name and billing address) on the Checkout page.
Edited respons
This is how you can add other optional params:
#bp.route('/create-checkout-session')
def create_checkout_session():
domain_url = 'http://localhost:5000/'
stripe.api_key = current_app.config['STRIPE_SECRET_KEY']
try:
checkout_session = stripe.checkout.Session.create(
success_url=domain_url + 'success',
cancel_url=domain_url + 'cancelled',
payment_method_types=['card'],
billing_address_collection='required',
mode='payment',
customer='customer_id',
line_items=[
{
# using the price api takes care of the product well
# rather than having to specify name, currency etc
'quantity': 1,
'price': 'price_1IYgbtFWpU2KHaPLODAVgoKU'
}
],
payment_intent_data=[
{
# Place your data here
'param-key': 'value',
# ...
}
]
)
# your return statement
except Exception as e:
# your return statement
You can do this for the other params

How can I access a nested JSON attribute in python?

How do I access the description field in my request payload?
REQUEST PAYLOAD:
data = { "other_details" :{
"my_story":true,
"preferences":false,
"profile_photo":false,
},
"experience_detail":[
{
"description":"Location: Indan\nCurrent job
responsibilities:\n\n• To manage, interpret,
and integrate inspection and function test data associated
with pressure relief
devices\n• Collection and Managing the database of
inspection/test records\n",
"employer_name":"Wood Group",
"end_date": "2020-04-28",
"id": "30dbe99d0c55435ea3d5119ece0ac873",
"is_current_employer": true,
"job_title": "Integrity Engineer",
"start_date": "2013-11-25"
},
{
"description":"Location: Indian\nCurrent job
responsibilities:\n\n• To manage, interpret,
and integrate inspection and function test data
associated with pressure relief devices\n•
Collection and Managing the database of
inspection/test records\n",
"employer_name":"QUESS CORP.",
"end_date": "2020-04-28",
"id": "30dbe99d0c55435ea3d5119ece0ac873",
"is_current_employer": true,
"job_title": "Integrity Engineer",
"start_date": "2013-11-25"
}
]
}
I tried a few ways, but they didn't work.
Attempt 1:
def index():
data = json.loads(request.data)
clean_description = (data['other_details']
['experience_detail']['description'])
Output:
clean_description = (data['other_details']['experience_detail']['description'])
**TypeError**: list indices must be integers or slices, not str
Attempt 2:
def index():
data = json.loads(request.data)
clean_description = (data['other_details']['experience_detail'])
Output:
[
{
"description":"Location: Australia\nCurrent job responsibilities:\n\n• To manage, interpret, and integrate inspection and function test data associated with pressure relief devices\n• Collection and Managing the database of inspection/test records\n• Pressure Relief Device (PRD) Inspection Report review/approval and recommendation\n• Compliance check on inspection reports in accordance with the scope and approve and/or send for re-review\n• Database management using Meridium, SAP and other Document Control Databases",
"employer_name":"Wood Group",
"end_date":"2020-04-28",
"id":"30dbe99d0c55435ea3d5119ece0ac873",
"is_current_employer":true,
"job_title":"Integrity Engineer",
"start_date":"2013-11-25"
},
{
"description":"Location: Australia\n\nResponsibilities:\n• Experience in pressure relief device sizing and selection\n• Exposure to Upstream Facilities Engineering activities\n• Experience with SharePoint for document management\n• Experience with Meridium",
"employer_name":"Jacobs Engineering",
"end_date":"2013-10-25",
"id":"7d8afe3cadaa4aee842bb4d8b000f5c7",
"is_current_employer":false,
"job_title":"Integrity Engineer",
"start_date":"2011-11-25"
}
]
It is displaying all the fields but I just need the description field.
Image of payload:

Real data elements from JSON

I am trying to extract data elements from json url link using python.Below is the code. It is working partially when I try to extract elements
response = urllib.request.urlopen(url)
data = json.loads(response.read())
print("planId",data[0]["planId"]) #Gives result as planId PWR93173MBE1
print("postcode",data[0]["postcode"]) # Gives result as postcode 2000
print("tariffType", data[0]["tariffType"]) This gives me error.
Also, if I want to extract other elements such as PlanType and other fields in Fees, how can I do it?
[
{
"planData":{
"planType":"M",
"tariffType":"SR",
"contract":[
{
"pricingModel":"SR",
"benefitPeriod":"Ongoing",
"coolingOffDays":10,
"additionalFeeInformation":"This offer provides access to wholesale prices, utilises your Powerbank to smooth wholesale market volatility and Powerwatch to warn of higher prices. For more information on this and any other standard fees, visit our website www.powerclub.com.au",
"fee":[
{
"description":"Annual Membership payable each year for each of your business premises taking supply.",
"amount":79,
"feeType":"MBSF",
"percent":0,
"feeTerm":"A"
},
{
"description":"Cost for providing a paper bill",
"amount":2.5,
"feeType":"PBF",
"percent":0,
"feeTerm":"F"
},
{
"description":"Disconnection fee",
"amount":59.08,
"feeType":"DiscoF",
"percent":0,
"feeTerm":"F"
},
{
"description":"Reconnection Fee",
"amount":59.08,
"feeType":"RecoF",
"percent":0,
"feeTerm":"F"
},
{
"description":"Meter Read - Requested by Customer",
"amount":12.55,
"feeType":"OF",
"percent":0,
"feeTerm":"F"
}
],
"planId":"PWR93173MBE1",
"planType":"E#B#PWR93173MBE1",
"postcode":2000
}
]
The tariffType property sits inside the planData property, so you need to do something like
print("tariffType", data[0]["planData"]["tariffType"])
You forgot to nest, correct should be:
print("tariffType", data[0]["planData"]["tariffType"])

paypal monthly subscription plan settings for first day of the month and making monthly recurring payment - django python

I am using Django paypalrestsdk for PayPal
https://github.com/paypal/PayPal-Python-SDK
And I would like to setup a monthly subscription plan.
Every beginning of the month, the buyer will be charged USD100.
This is my billing plan code I have made:
billing_plan = paypalrestsdk.BillingPlan({
"name": "Monthly Billing Plan",
"description": "Monthly Plan",
"merchant_preferences": {
"auto_bill_amount": "yes",
"cancel_url": "http://localhost:8000/payment_billing_agreement_cancel",
"initial_fail_amount_action": "continue",
"max_fail_attempts": "0",
"return_url": "http://localhost:8000/payment_billing_agreement_execute",
"setup_fee": {
"currency": "USD",
"value": "100"
}
},
"payment_definitions": [
{
"amount": {
"currency": "USD",
"value": "100"
},
"cycles": "0",
"frequency": "MONTH",
"frequency_interval": "1",
"name": "Monthly Payment",
"type": "REGULAR"
}
],
"type": "INFINITE"
})
It is not clear to me if it is charging on the first day of the month or the last day of the month? Should I have the setup so it's charged immediately? My intention is charging is done on the first day of the month.
I am seeing this in the sandbox of the buyer:
Preapproved payment USD100
What does this mean, is he charged already USD100 or preapproved and charged on the last day of the month?
Based on this, it seems like its charged right away. meaning it should show USD200 right? (setup + monthly but its showing only USD100)
https://developer.paypal.com/docs/classic/paypal-payments-standard/integration-guide/subscription_billing_cycles/
I've used this flow so far:
create billing plan
activate billing plan
create billing agreement
execute billing agreement
(is this correct? it shows pre-approved but is this really charged, if not what other steps should be taken to charge it properly)
To clarify, the main question is how do you set up monthly billing with PayPal (and to set the charging cycle, whether it's beginning of the month or end)? (in this example, its using django python)
UPDATE:
On a recommendation #john-moutafis, I'ved now have setup USD100, and recurring start date is set 1 month later for USD111
billing_agreement = paypalrestsdk.BillingAgreement({
"name": "Monthly Billing Agreement",
"description": "Monthly Payment Agreement",
"start_date": arrow.utcnow().shift(months=+1).datetime.strftime('%Y-%m-%dT%H:%M:%SZ'),
"plan": {
"id": billing_plan.id
},
"payer": {
"payment_method": "paypal"
}
})
Here is paypal screenshots, why is there no info on amount and why is it preapproved without recurring info ?
https://imgur.com/a/Sp7JdVC
Paypal will automatically try to keep the billing date the same for every month (where applicable, as stated in the linked resource).
You can state the starting date of a billing agreement as stated in this example, by specifying a start_datefield. Here I use the arrow module, to conveniently calculate the first day of the next month:
import arrow
billing_plan = paypalrestsdk.BillingPlan({
"name": "Monthly Billing Plan",
"description": "Monthly Plan",
"start_date": arrow.utcnow().shift(months=+1).replace(day=1).isoformat(),
"merchant_preferences": {
...
"setup_fee": {
"currency": "USD",
"value": "100"
}
}
...
})
The initial subscription fee should be handled by the setup_fee field!
EDIT after question update:
On the merchant_preferences field of your plan, you are setting auto_bill_amount to yes.
By taking a look at the documentation on merchant_preferences we can see that:
auto_bill_amount enum
Indicates whether PayPal automatically bills the outstanding balance in the next billing cycle. The outstanding balance is the total amount of any previously failed scheduled payments. Value is:
NO. PayPal does not automatically bill the customer the outstanding >balance.
YES. PayPal automatically bills the customer the outstanding balance.
Possible values: YES, NO.
Default: NO.

Podio: How do I use the Item.update-method in Python 3?

There is no example code for the Podio API for Python but this is the example code written for Ruby:
Podio::Item.update(210606, {
:fields => {
'title' => 'The API documentation is much more funny',
'business_value' => { :value => 20000, :currency => 'EUR' },
'due_date' => { :start => '2011-05-06 11:27:20', :end =>
5.days.from_now.to_s(:db) }
}
})
I can't for the life of me figure out how to translate this to Python 3. I've tried using dictionaries, dicts inside lists, referencing the field with both their field-id and their names etc. But it never actually updates anything.
This is my failed attempt at translating the above to Python code (with different fields since the fields in my 'Bugs (API example) app' aren't the same as in the example code):
newValues = {'fields':{'title': "This is my title",'description_of_problem':
"the not work"}}
try:
podio.Item.update(629783395, newValues['fields'])
print('updating was successful')
except:
print('updating was not successful')
With podio being:
podio = api.OAuthClient(
client_id,
client_secret,
username,
password,
)
The 'fields' part in my code doesn't make any sense really, but I couldn't figure out what else to do with that part of the Ruby code, I suspect that is the issue. The program always prints 'updating was successful' as if the Item.update method was successfully called, but as I said it doesn't actually update anything in Podio. Can anyone see what's wrong?
I'd just follow the Item update API, and pass in a dictionary that matches the request section there:
{
"revision": The revision of the item that is being updated. This is optional,
"external_id": The new external_id of the item,
"fields": The values for each field, see the create item operation for details,
"file_ids": The list of attachments,
"tags": The list of tags,
"reminder": Optional reminder on this task
{
"remind_delta": Minutes (integer) to remind before the due date
},
"recurrence": The recurrence for the task, if any,
{
"name": The name of the recurrence, "weekly", "monthly" or "yearly",
"config": The configuration for the recurrence, depends on the type
{
"days": List of weekdays ("monday", "tuesday", etc) (for "weekly"),
"repeat_on": When to repeat, "day_of_week" or "day_of_month" (for "monthly")
},
"step": The step size, 1 or more,
"until": The latest date the recurrence should take place
},
"linked_account_id": The linked account to use for meetings,
"ref" The reference of the item
{
"type": The type of reference,
"id": The id of the reference
}
}
The documentation further points to the item creation API for further examples. Note how that object has a "fields" key in the outermost mapping.
All the Ruby documentation does is build that mapping as a Ruby hash (in Python, a dict) with the entries that need updating; :field is an immutable string (called a symbol) that defines a key in that hash pointing to a nested hash. The Python implementation for the update method just converts that dictionary to a JSON post body.
A direct translation of the Ruby code to Python is:
from datetime import datetime, timedelta
podio.item.update(210606, {
'fields': {
'title': 'The API documentation is much more funny',
'business_value': {'value': 20000, 'currency': 'EUR'},
'due_date': {
'start': '2011-05-06 11:27:20',
'end': (datetime.now() + timedelta(days=5)).strftime('%Y-%m-%d %H:%M:%S')}
}
})
What you did wrong in your case is not include the 'fields' key in the outermost dictionary; you unwrapped the outermost dictionary and only posted the nested dictionary under 'fields'. Instead, include that outer dictionary:
newValues = {
'fields': {
'title': "This is my title",
'description_of_problem': "the not work"
}
}
podio.Item.update(629783395, newValues)

Categories