Does anyone have a stripe connect demo or example for web2py?

42 views
Skip to first unread message

Andrew E.

unread,
Apr 2, 2022, 2:29:19 AM4/2/22
to web2py-users
Hello, I am looking to see if anyone has an example of using the stripe connect api with a Web2py project and can share it. I might be asking for to much but I thought I would try my luck.

Thanks all in advance, Web2py is truly a great platform.

*cheers Andrew

Maurice Waka

unread,
Apr 3, 2022, 9:29:43 PM4/3/22
to web...@googlegroups.com
There is an example with e-store somewhere in Github.com... 

--
Resources:
- http://web2py.com
- http://web2py.com/book (Documentation)
- http://github.com/web2py/web2py (Source code)
- https://code.google.com/p/web2py/issues/list (Report Issues)
---
You received this message because you are subscribed to the Google Groups "web2py-users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to web2py+un...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/web2py/daa7c045-97cb-4a09-9466-a996b02701a8n%40googlegroups.com.

Jose C

unread,
Apr 5, 2022, 3:09:42 PM4/5/22
to web2py-users
Here's some code that I use... hopefully should get you started.

In your python environment:  pip install stripe

Then in a controller (donations):
```
def __create_stripe_session(item_name='', amount_cents=0, success_url='', cancel_url='', item_description='', customer_email=None):
    """
        Creates a Stripe session (with a payment intent id), valid for 24 hrs, which we can then submit later.
    """
    import stripe

    stripe.api_key = 'stripe_key_secret'
    stripe_session = stripe.checkout.Session.create(
                                          payment_method_types=['card'],
                                          customer_email = customer_email,   # prepopulates, but readonly - user can't change it.
                                          line_items=[{
                                            'name': item_name,
                                            'description': item_description,
                                            'amount': amount_cents,
                                            'currency': 'cad',
                                            'quantity': 1,
                                          }],
                                          success_url = success_url,
                                          cancel_url = cancel_url,
    )

    return stripe_session


def make_donation():
    """
        display page with form to enter amount.
    """
    # display form.
    form = SQLFORM.factory(Field('amount', type='string', label='Donation Amount'))

    if form.process().accepted:
        #  create a Stripe session
        stripe_session = __create_stripe_session(
                                    item_name = 'Donation',
                                    amount_cents = int(round(float(form.vars.amount),2)*100),
                                    success_url = 'http://localhost:8055/donations/done?action=payment_complete',   # stripe redirects here on success.
                                    cancel_url = 'http://localhost:8055/donations/done?action=cancelled'            # stripe redirects here if cancelled.
                                    )

        # Save record so can compare with stripe returned event...
        # Store the PI in the description temporarily and overwrite when transaction is sucessful.
        db.donations.insert(user_id = session.user_id, description=stripe_session.payment_intent, amount=round(float(form.vars.amount),2))

        # Now submit to Stripe for execution.
        context = dict(public_key = '<your stripe public key here>',  stripe_session_id = stripe_session.id)
        return response.render('donations/do_stripe_payment.html', context)
    elif form.errors:
        response.error = form.errors.amount

    return dict(form = form)


@request.restful()
def my_stripe_webhook():
    """
        On event, Stripe POSTs this json `webhook` via http.
        We need to respond with simple 200-ok or it will attempt to resend a few more times.
    """
    import stripe

    def POST(*args, **vars):
        # Alternatively can take the `id` from the POST info and turn it into a stripe object that can be used and queried.
        # e.g.  See https://stripe.com/docs/api/python#retrieve_event for details of the object.

        if request.vars.id == 'evt_00000000000000':     # Test event from Stripe - can't query it with api...silly as that seems.
            log.warning("dummy Stripe event evt_00000000000000 received. Not processing further.")
            return "Ok, thanks. (dummy/test event received)."

        else:
            # Set the secret key.
            stripe.api_key =  'stripe_key_secret'
            # see:    https://stripe.com/docs/api/events/object
            event = stripe.Event.retrieve(request.vars.id)
            log.info(f"Stripe event received.  id: {event.id} type: {event.type}")

            if event.type == 'charge.succeeded':
                # Check if donation.
                rec = db(db.donations.description == event.data.object.payment_intent).select().first()

                if rec:
                    log.info(f"Donation made by user: {rec.user_id}")
                    # Overwrite the PI code in the description with actual action/message visible to user.
                    # This is final step and confirms money has been received.
                    rec.update_record(description = "Funds received, thank you!")
                else:
                    log.error(f"Unknown payment received, see: {event.data.object.payment_intent}")

            elif event.type == 'charge.refunded':
                # Refund processing here...

            elif event.type == 'checkout.session.completed':
                return "Ok, thanks"

            else:
                # process other possible other event types.
                return "Thanks again"

    return locals()
```

the view (donations/do_stripe_payment.html):
```
<div>Communicating with our payment processor, Stripe...</div>
<script src="https://js.stripe.com/v3/"></script>
<script>
    var stripe = Stripe('{{=public_key}}');

    stripe.redirectToCheckout({
            sessionId: '{{=stripe_session_id}}'
        }).then(function (result) {
          // If `redirectToCheckout` fails due to a browser or network
          // error, display the localized error message to your customer
          // using `result.error.message`.
        });
</script>
```

Hope that helps,
J

Reply all
Reply to author
Forward
0 new messages