0

I can make the simple button or default button work but as there is no option to custom css I need to use "Custom" stripe button. Following is the simple and custom form I am using where simple one works fine but don't know how to make custom work. Currently it is doing nothing when I click and enter information. But Default button works just fine.

View:

@app.route('/monthly', methods=['GET', 'POST'])
def monthly_charged():

    if not user_authorized():
        return redirect('/')
    amount = 1495
    # customer
    key = stripe_keys['publishable_key']
    print key
    charge_all = stripe.Charge.list(limit=10000)
    charge_dic = {}
    charge_list = []
    for charge_data in charge_all:
        charge_dic['Amount'] = "$" + str(float(charge_data.amount) / 100) + " " + charge_data.currency.upper()
        charge_dic['Description'] = charge_data.description
        charge_dic['Name'] = charge_data.receipt_email
        charge_dic['Date'] = str(datetime.datetime.fromtimestamp(charge_data.created))
        charge_list.append(charge_dic)
        charge_dic = {}

    data = get_profile_data(session['auth_token'])       
    profile_data = data['StudentProfile']
    student_id = profile_data.id
    student = get_profile_data(session['auth_token'])['StudentProfile']    
    pkg = Package.query.filter_by(student_id=profile_data.id).first()
    if pkg:
        flash('You already have an active subscription.')
    else:
        stripe_token = request.form['stripeToken']
        email = request.form['stripeEmail']
        try: 
            customer = stripe.Customer.create(
                email=email,
                source=request.form['stripeToken']
            )

            subscription = stripe.Subscription.create(
                customer=customer.id,
                plan="monthly",
            )
            student_id = profile_data.id
            student.stripe_customer_id = customer.id
            student.stripe_subscription_id = subscription.id

            package = Package(
                student_id=student_id,
                stripe_id = customer.id,
                student_email=request.form['stripeEmail'],
                is_active=True,
                package_type='monthly',
                subscription_id=subscription.id
            )
            dbase.session.add(package)
            flash("You've successfylly subscribed for monthly package.")
            dbase.session.commit()

        except stripe.error.CardError as e:
        # The card has been declined
            body = e.json_body
            err = body['error']
    return redirect(url_for('packages', key=key, amount=amount))

Simple or Default Stripe Button:

            <form action="/monthly" method="post" >
            <div class="form-group">

            <script src="https://checkout.stripe.com/checkout.js" class="stripe-button"
            data-key="pk_test_YgHVTCLIMQLW4NV6ntnJPAXs"
            data-description="Monthly Package"
            data-name="Monthly"
            data-amount="10000"
            data-image="https://stripe.com/img/documentation/checkout/marketplace.png"
            data-locale="auto">
            </script>
            </div>
        </form>

Custom Stripe Button:

<form action="/monthlycharged" method="post">
<script src="https://checkout.stripe.com/checkout.js"></script>
<button id="customButton">Enroll</button>
<style>
#customButton{
width:100px;
height:30px;
background-color:red;
color:white;
border:2px solid red;
}
</style>
 <script>
var handler = StripeCheckout.configure({
  key: 'pk_test_YgHVTCLIMQLW4NV6ntnJPAXs',
  image: 'https://stripe.com/img/documentation/checkout/marketplace.png',
  locale: 'auto',
  token: function(token) {
    // You can access the token ID with `token.id`.
    // Get the token ID to your server-side code for use.
  }
});

document.getElementById('customButton').addEventListener('click', function(e) {
  // Open Checkout with further options:
  handler.open({
    name: 'Monthly',
    description: 'monthly',
    amount: 10000
  });
  e.preventDefault();
});

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

</form>

1 Answer 1

2

You need to submit your form in the token: function() {} of StripeCheckout.configure.

Here's an example of how to do that: https://jsfiddle.net/osrLsc8m/

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

2 Comments

It seems to be working to get token and communicating with local server so partially your answer is correct. But now I am getting an error "InvalidRequestError: Request req_ALkmzqetwvJmMH: Invalid source object: must be a dictionary or a non-empty string. See API docs at stripe.com/docs'". In debug it says the error is to when I called "source=request.form['stripeToken']" while creating customer in my view. Any solution for this?
That's a different problem. What is the value in request.form['stripeToken']? You need to add logging output to make sure everything is what you expect it to be as you work through debugging this.

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.