Cajuu' Cajuu' - 1 month ago 8
Python Question

Adding extra parameters when sending request with django and stripe

I've been trying to send extra parameters when submiting the stripe button, which is integrated in my Django application, but I cannot make it work.

So far, I have this:

views.py

stripe.api_key = "XXXX"

class StripeApi(View):
@staticmethod
def post(request):
a = request.body
event_json = json.dumps(a)
print a
return HttpResponse(
event_json, content_type="application/x-javascript-config")


urls.py

urlpatterns = [
url(r'^stripe/', ApiViews.StripeApi.as_view()),
]


index.html

<form action="" method="POST">
<input type="text" name="extraParam2" value="55555fghjkldfgdgfasdfghhjjj"> <!-- here, I tried to add extraParam2 -->
<script
src="https://checkout.stripe.com/checkout.js" class="stripe-button"
data-key="XXXX"
data-amount="2000"
data-name="Demo Site"
data-description="2 widgets ($20.00)"
data-image="/128x128.png"
data-locale="auto">
</script>
</form>


Any hints on this, please ?




//EDIT:

I tried to integrate what Ywain gave me into my app and I get
"POST /stripe/ HTTP/1.1" 405 0
in console after completing and sending the form. What do I do wrong ?

views.py

class StripeApi(View):
@staticmethod
def index(request):
return HttpResponse(request, 'index.html', {
'stripe_pub_key': settings.STRIPE_PUBLISHABLE_KEY},
content_type="application/x-javascript-config")

@staticmethod
def charge(request):
charge = stripe.Charge.create(
amount=2000,
currency='usd',
source=request.POST['stripeToken'],
description='Charge for {}'.format(request.POST['stripeEmail'])
)
return HttpResponse(request, 'stripe.html', {'charge_id': charge.id,
'extra_param': request.POST['extraParam2']},
content_type="application/x-javascript-config")


settings.py:

'''stripe'''

STRIPE_SECRET_KEY = 'sk_test_secret',
STRIPE_PUBLISHABLE_KEY = 'pk_test_secret'

stripe.api_key = STRIPE_SECRET_KEY


urls.py

...
url(r'^stripe/', ApiViews.StripeApi.as_view()),


index.html

<form action="/stripe/" method="POST">
<input type="text" name="extraParam2" value="Test extraParam">
<script
src="https://checkout.stripe.com/checkout.js" class="stripe-button"
data-key="pk_test_secret"
data-image="https://stripe.com/img/documentation/checkout/marketplace.png"
data-name="Stripe.com"
data-description="2 widgets"
data-amount="2000"
data-locale="auto">
</script>
</form>


stripe.html

{% extends "base_site.html" %}

{% block content %}
<pre>
Charge ID: {{ charge_id }}
Extra param: {{ extra_param }}
</pre>
{% endblock %}

Answer

Here is a minimal Django app that illustrates how to use Stripe Checkout and use the resulting token to create a charge, as well as pass an extra parameter along:

django-stripe.py

import sys

from django.conf import settings
from django.conf.urls import url
from django.core.management import execute_from_command_line
from django.shortcuts import render
from django.views.generic import View

import stripe


settings.configure(
    DEBUG=True,
    ROOT_URLCONF=sys.modules[__name__],
    TEMPLATE_DIRS=['.'],
    STRIPE_SECRET_KEY='sk_test_...',
    STRIPE_PUBLISHABLE_KEY='pk_test_...'
)

stripe.api_key = settings.STRIPE_SECRET_KEY


class StripeView(View):

    @staticmethod
    def get(request):
        return render(request, 'index.html',
                      {
                          'stripe_pub_key': settings.STRIPE_PUBLISHABLE_KEY
                      })

    @staticmethod
    def post(request):
        charge = stripe.Charge.create(
            amount=2000,
            currency="usd",
            source=request.POST['stripeToken'],
            description="Charge for {}".format(request.POST['stripeEmail'])
        )
        return render(request, 'charge.html',
                      {
                          'charge_id': charge.id,
                          'extra_param': request.POST['extraParam2']
                      })


urlpatterns = [
    url(r'^stripe/', StripeView.as_view()),
]

if __name__ == "__main__":
    execute_from_command_line(sys.argv)

index.html

<form action="" method="POST">
  {% csrf_token %}
  <input type="text" name="extraParam2" value="55555fghjkldfgdgfasdfghhjjj">
  <script
    src="https://checkout.stripe.com/checkout.js" class="stripe-button"
    data-key="{{ stripe_pub_key }}"
    data-image="https://stripe.com/img/documentation/checkout/marketplace.png"
    data-name="Stripe.com"
    data-description="2 widgets"
    data-amount="2000"
    data-locale="auto">
  </script>
</form>

charge.html

<pre>
Charge ID: {{ charge_id }}
Extra param: {{ extra_param }}
</pre>

You can test it by pasting your Stripe API keys (in the STRIPE_SECRET_KEY and STRIPE_PUBLISHABLE_KEY arguments of the settings.configure() function call), starting the app with python django-stripe.py runserver, and pointing your web browser to http://localhost:8000/stripe.

Basically, index.html contains the Checkout form as well as your extra parameter. The form is submitted to the same page (the action attribute of the <form> tag is empty), and is handled by the post() method of the StripeView class. The method creates an actual charge with Stripe's API, and passes the resulting charge ID along with your extra parameter to the charge.html template.