0

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 %}
5
  • Your <form> tag has an empty action attribute, so it's going to be submitted to the same page. Are you sure this is what you want? Aside from that, your extra parameter should be posted along with Checkout's stripeToken and stripeEmail, and be accessible via request.POST['extraParam2']. Commented Sep 21, 2015 at 6:03
  • @Ywain doing request.POST['extraParam2'] didn't work. I just don't receive in the response my extraParam2. Commented Sep 21, 2015 at 6:36
  • But do you receive the parameters from Checkout? E.g. request.POST['stripeToken']. Commented Sep 21, 2015 at 16:59
  • 1
    In your edited example, try changing index() to get() and charge() to post(). The example given by Ywain was using function based views, rather than class based views. Using CBV, you have to use the specific method names. Commented Sep 22, 2015 at 15:24
  • I have updated my sample app to use class-based views, and match more closely your first code style. Commented Sep 23, 2015 at 2:50

2 Answers 2

2
+100

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.

Sign up to request clarification or add additional context in comments.

3 Comments

I did how you said but I can't make it work. See the edit please.
I marked this as accepted but I have another small question: how should I get the value of a paymant of a specific plan ? I succeded to get the plan by doing plan=request.POST['plan'] and adding <input type="hidden" value="test6months" id="plan" name="plan"> to my form, where test6months is the id of the plan (I've seen it in the response body)
To get the value of a plan from its ID, the simplest way would be to issue a plan retrieval request and look at the amount attribute in the response.
0

The stripe page mentions a 'custom' option for using a stripe button, this is probably what you want, you can add extra values to your button:

https://stripe.com/docs/checkout#integration-custom

<script src="https://checkout.stripe.com/checkout.js"></script>

<button id="customButton">Purchase</button>

<script>
  var handler = StripeCheckout.configure({
    key: 'pk_test_6pRNASCoBOKtIshFeQd4XMUh',
    image: '/img/documentation/checkout/marketplace.png',
    locale: 'auto',
    token: function(token) {
      // Use the token to create the charge with a server-side script.
      // You can access the token ID with `token.id`
    }
  });

  $('#customButton').on('click', function(e) {
    // Open Checkout with further options
    handler.open({
      name: 'Stripe.com',
      description: '2 widgets',
      amount: 2000
    });
    e.preventDefault();
  });

  // Close Checkout on page navigation
  $(window).on('popstate', function() {
    handler.close();
  });
</script>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.