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
Related
I added the adjustable quantity for Stripe's check out session call. I understand that the fee object is created after the payment.
I'm looking at the application fee object in stripe's documentation and it says it is capped at the final charge amount. How do I retrieve the charge amount or better, quantity during the checkout session?
checkout_session = stripe.checkout.Session.create(
success_url=domain_url + 'success?session_id={CHECKOUT_SESSION_ID}',
cancel_url=domain_url + 'cancelled/',
payment_method_types=['card'],
customer=customer.id,
payment_intent_data={
'application_fee_amount': int(stripe_price * fee_percentage),
'transfer_data': {
'destination': seller.stripe_user_id,
},
},
line_items=[
{
'price_data': {
'currency': currency,
'unit_amount': price,
'product_data': {
'name': title
},
},
'adjustable_quantity': {
'enabled': True,
'minimum': 0,
'maximum': available_quantity,
},
'quantity': 1,
},
],
metadata={
"product_id": product.id,
"client_reference_id": user.id,
},
mode='payment',
)
return JsonResponse({'sessionId': checkout_session['id']})
except Exception as e:
return JsonResponse({'error': str(e)})
Right now the best option is to do the following:
Set payment_method_data.capture_method to manual on the Checkout Session
When the Checkout Session is complete set an application_fee_amount when capturing the funds
This limits you to payment methods that support separate authorization and capture, but it will allow you to set application_fee_amount after the Checkout Session completes.
I am trying to pass multiple parameters to hotel offers using the Amadeus Python SDK but I am getting a 400 error code. How can I include checkInDate and checkOutDate in the request?
here's the code :
amadeus = Client(
client_id = clientID,
client_secret = ClientSecret
)
try:
hotels_by_city = amadeus.shopping.hotel_offers.get(cityCode=citycode,checkInDate=checkindate,checkOutDate=checkoutdate,adults=adults,roomQuantity=rooms)
k = hotels_by_city.data
print(k)
Here an example of how to use the Python SDK to implement Hotel Search and Book:
# Install the Python library from https://pypi.org/project/amadeus
from amadeus import Client, ResponseError
amadeus = Client(
client_id='YOUR_AMADEUS_API_KEY',
client_secret='YOUR_AMADEUS_API_SECRET'
)
try:
# Get list of Hotels by city code
hotels_by_city = amadeus.shopping.hotel_offers.get(cityCode='PAR', checkInDate='2021-01-10', checkOutDate='2021-01-12')
# Get list of offers for a specific hotel
hotel_offers = amadeus.shopping.hotel_offers_by_hotel.get(hotelId = 'HSMADAMI', checkInDate='2021-01-10', checkOutDate='2021-01-12')
# Confirm the availability of a specific offer
offer = hotel_offers.data['offers'][0]['id']
offer_availability = amadeus.shopping.hotel_offer(offer).get()
guests = [{'id': 1, 'name': { 'title': 'MR', 'firstName': 'BOB', 'lastName': 'SMITH' }, 'contact': { 'phone': '+33679278416', 'email': 'bob.smith#email.com'}}]
payments = { 'id': 1, 'method': 'creditCard', 'card': { 'vendorCode': 'VI', 'cardNumber': '4151289722471370', 'expiryDate': '2021-08' } }
hotel_booking = amadeus.booking.hotel_bookings.post(offer, guests, payments)
print(hotel_booking.data)
except ResponseError as error:
raise error
I would like to require the user to enter his phone number in Stripe checkout. I can't seem to find any info on how to do this.
Example Setup:
# This example sets up an endpoint using the Flask framework.
# Watch this video to get started: https://youtu.be/7Ul1vfmsDck.
import os
import stripe
from flask import Flask, jsonify
app = Flask(__name__)
# Set your secret key. Remember to switch to your live secret key in production!
# See your keys here: https://dashboard.stripe.com/account/apikeys
stripe.api_key = 'sk_test_dQV7WggUdL2wzG5zU8fcJ81O'
#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= "https://yoursite.com/success.html",
cancel_url='https://example.com/cancel',
)
return jsonify(id=session.id)
if __name__== '__main__':
app.run(port=4242)
The Checkout Session object itself does not contain a phone number. The best approach would be to create the Customer using your own forms before redirecting to checkout to collect the customer's phone number [1]. Then you provide the Customer ID when creating the session [2].
[1] https://stripe.com/docs/api/customers/create#create_customer-phone
[2] https://stripe.com/docs/api/checkout/sessions/create#create_checkout_session-customer
Add "phone_number_collection" parameter as shown below:
session = stripe.checkout.Session.create(
phone_number_collection={ # Here
'enabled': True, # Here
}, # Here
payment_method_types=['card'],
line_items=[{
'price_data': {
'currency': 'usd',
'product_data': {
'name': 'T-shirt',
},
'unit_amount': 2000,
},
'quantity': 1,
}],
mode='payment',
success_url= "https://example.com/success.html",
cancel_url='https://example.com/cancel',
)
Then, you can enter a phone number as shown below:
I try to implement 2checkout to my django app (Python 3.7 and Django 2.2).
I'm using the Sandox and when I see API logs my orders are successfully passed. I also chose a URL for the Passback and selected Header Redirect in my account settings.
Unfortunately, I don't succeed in getting the redirection works :
I get this error after twocheckout.Charge.authorize(params) if successfully executed:
The view subscriptions.views.subscription_payment didn't return an HttpResponse object. It returned None instead.
When I manually add an HttpResponseRedirect like this:
return HttpResponseRedirect('/payment-success') the GET request is empty because it doesn't come from 2checkout.
I tried to follow this tutorial https://github.com/2Checkout/2checkout-python-tutorial and it doesn't mention any HttpResponseRedirect.
Could you please help me with this issue? It's really frustrating. I'm a beginner developper so maybe I missed something. Please feel free to ask any further information that would be helpful to understand my issue.
Many thanks in advance
I was integrating the API so no need for Passback URL. The question was a non sense :) That's why the tutorial doesn't mention HttpResponseRedirect.
Because it has been asked in the comments, here is the code used to fulfil the need I had at that moment. Hope this could help someone else.
def subscription_payment(request, pk):
property = Property.objects.get(pk=pk)
if request.method == 'POST':
pay_token = request.POST.get('token')
twocheckout.Api.auth_credentials({
'private_key': '######-####-####-####-#######',
'seller_id': '#########',
'mode': 'sandbox' # Uncomment to use Sandbox
})
data = serializers.serialize('json', Profile.objects.filter(user=request.user), fields=(
'address_2', 'city', 'zip_code', 'country', 'phone_number'))
data = json.loads(data)
params = {
'merchantOrderId': request.user.id,
'token': pay_token,
'currency': 'USD',
'billingAddr': {
'name': request.user.get_full_name(),
'addrLine1': data[0]['fields']['address_2'],
'city': data[0]['fields']['city'],
'state': ' ',
'zipCode': data[0]['fields']['zip_code'],
'country': data[0]['fields']['country'],
'email': request.user.email,
'phoneNumber': data[0]['fields']['phone_number'],
},
'lineItems': [
{
'type': 'product',
'name': 'Abonnement mensuel basic',
'recurrence': '1 Month',
'duration': '3 Month',
'tangible': 'N',
'price': '150.00',
'description': '',
'productId': property.id,
}
]
}
try:
result = twocheckout.Charge.authorize(params)
backup_response = json.dumps(result)
print(result.responseCode)
if result.responseCode == 'APPROVED':
offer = Offer.objects.get(type='MONTHLY_BASIC')
user = request.user
payment_data = dict()
payment_data['response_code'] = result.responseCode
payment_data['transaction_id'] = result.transactionId
payment_data['order_number'] = result.orderNumber
payment_data['amount'] = result['lineItems'][0]['price']
payment_data['property_title_bkp'] = property.title
payment_data['backup_response'] = backup_response
Payment.objects.create(
offer=offer,
property=property,
user=user,
initiated_on=timezone.now(),
**payment_data
)
return render(request, 'subscriptions/payment_success.html', payment_data)
except TwocheckoutError as error:
return HttpResponse(error.msg)
I try to use the Google Adwords API, with the official library here : https://github.com/googleads/googleads-python-lib
I use an Manager Account on Google Adwords and want to work with my client's accounts.
I can get all the the Adwords account ID (like 123-456-7891) but I don't know how to pass the account ID to my Google Adwords functions as a parameter.
Here's my main function :
def main(argv):
adwords_client = adwords.AdWordsClient.LoadFromStorage(path="googleads.yaml")
add_campaign(adwords_client)
I see any Account ID parameter in the official samples, as :
import datetime
import uuid
from googleads import adwords
def add_campaign(client):
# Initialize appropriate services.
campaign_service = client.GetService('CampaignService', version='v201809')
budget_service = client.GetService('BudgetService', version='v201809')
# Create a budget, which can be shared by multiple campaigns.
budget = {
'name': 'Interplanetary budget #%s' % uuid.uuid4(),
'amount': {
'microAmount': '50000000'
},
'deliveryMethod': 'STANDARD'
}
budget_operations = [{
'operator': 'ADD',
'operand': budget
}]
# Add the budget.
budget_id = budget_service.mutate(budget_operations)['value'][0][
'budgetId']
# Construct operations and add campaigns.
operations = [{
'operator': 'ADD',
'operand': {
'name': 'Interplanetary Cruise #%s' % uuid.uuid4(),
# Recommendation: Set the campaign to PAUSED when creating it to
# stop the ads from immediately serving. Set to ENABLED once you've
# added targeting and the ads are ready to serve.
'status': 'PAUSED',
'advertisingChannelType': 'SEARCH',
'biddingStrategyConfiguration': {
'biddingStrategyType': 'MANUAL_CPC',
},
'endDate': (datetime.datetime.now() +
datetime.timedelta(365)).strftime('%Y%m%d'),
# Note that only the budgetId is required
'budget': {
'budgetId': budget_id
},
'networkSetting': {
'targetGoogleSearch': 'true',
'targetSearchNetwork': 'true',
'targetContentNetwork': 'false',
'targetPartnerSearchNetwork': 'false'
},
# Optional fields
'startDate': (datetime.datetime.now() +
datetime.timedelta(1)).strftime('%Y%m%d'),
'frequencyCap': {
'impressions': '5',
'timeUnit': 'DAY',
'level': 'ADGROUP'
},
'settings': [
{
'xsi_type': 'GeoTargetTypeSetting',
'positiveGeoTargetType': 'DONT_CARE',
'negativeGeoTargetType': 'DONT_CARE'
}
]
}
}, {
'operator': 'ADD',
'operand': {
'name': 'Interplanetary Cruise banner #%s' % uuid.uuid4(),
'status': 'PAUSED',
'biddingStrategyConfiguration': {
'biddingStrategyType': 'MANUAL_CPC'
},
'endDate': (datetime.datetime.now() +
datetime.timedelta(365)).strftime('%Y%m%d'),
# Note that only the budgetId is required
'budget': {
'budgetId': budget_id
},
'advertisingChannelType': 'DISPLAY'
}
}]
campaigns = campaign_service.mutate(operations)
How can I tell Adwords API in which account I want to add this campaign ?
Thanks for your help !
OK my bad, I missed a documentation method (http://googleads.github.io/googleads-python-lib/googleads.adwords.AdWordsClient-class.html#SetClientCustomerId).
# ID of your customer here
CUSTOMER_SERVICE_ID = '4852XXXXX'
# Load customer account access
client = adwords.AdWordsClient.LoadFromStorage(path="googleads.yaml")
client.SetClientCustomerId(CUSTOMER_SERVICE_ID)
And the customer ID is now associate with the AdwordsClient variable as "client" set as parameters for other functions.