#emnaruto07-webhooks

1 messages ยท Page 1 of 1 (latest)

abstract flame
#

Hello! How can I help?

daring field
#
2022-03-28 23:58:07   --> invoice.finalized [evt_1KiNIRDaN18cbJKsAxEMgncA]
2022-03-28 23:58:07  <--  [500] POST http://localhost:8000/webhook [evt_1KiNIQDaN18cbJKs8I0Qe5ga]
2022-03-28 23:58:07  <--  [500] POST http://localhost:8000/webhook [evt_1KiNIRDaN18cbJKsAxEMgncA]
2022-03-28 23:58:07   --> customer.subscription.created [evt_1KiNIRDaN18cbJKsKy6HDe6f]
2022-03-28 23:58:07  <--  [500] POST http://localhost:8000/webhook [evt_1KiNIRDaN18cbJKsKy6HDe6f]
2022-03-28 23:58:07   --> invoice.updated [evt_1KiNIRDaN18cbJKsQ0oYiaH3]
2022-03-28 23:58:07   --> customer.subscription.updated [evt_1KiNIRDaN18cbJKsCz0JzxrU]
2022-03-28 23:58:08  <--  [500] POST http://localhost:8000/webhook [evt_1KiNIRDaN18cbJKsQ0oYiaH3]
2022-03-28 23:58:08  <--  [500] POST http://localhost:8000/webhook [evt_1KiNIRDaN18cbJKsCz0JzxrU]
2022-03-28 23:58:08   --> invoice.paid [evt_1KiNIRDaN18cbJKsZRF0BNN2]
2022-03-28 23:58:08  <--  [500] POST http://localhost:8000/webhook [evt_1KiNIRDaN18cbJKsZRF0BNN2]
2022-03-28 23:58:08   --> invoice.payment_succeeded [evt_1KiNIRDaN18cbJKsRNXzr8dg]
2022-03-28 23:58:08   --> payment_intent.succeeded [evt_3KiNINDaN18cbJKs03Wo0p14]
2022-03-28 23:58:08  <--  [500] POST http://localhost:8000/webhook [evt_1KiNIRDaN18cbJKsRNXzr8dg]
2022-03-28 23:58:08  <--  [500] POST http://localhost:8000/webhook [evt_3KiNINDaN18cbJKs03Wo0p14]
2022-03-28 23:58:08   --> payment_intent.created [evt_3KiNINDaN18cbJKs0TGb8EKl]```
#

i create one endpoint called webhook in django

#
def webhook_received(request, *args, **kwargs):
    # Replace this endpoint secret with your endpoint's unique secret
    # If you are testing with the CLI, find the secret by running 'stripe listen'
    # If you are using an endpoint defined with the API or dashboard, look in your webhook settings
    # at https://dashboard.stripe.com/webhooks
    webhook_secret = settings.WEBHOOK_KEY
    payload = request.body

    # Retrieve the event by verifying the signature using the raw body and secret if webhook signing is configured.
    signature = request.headers.get('stripe-signature')
    try:
        event = stripe.Webhook.construct_event(
            payload=request.data, sig_header=signature, secret=webhook_secret)
        data = event['data']
    except Exception as e:
        return e
    # Get the type of webhook event sent - used to check the status of PaymentIntents.
    event_type = event['type']

    print('event ' + event_type)

    if event_type == 'checkout.session.completed':
        print(event_type)
        print('๐Ÿ”” Payment succeeded!')
    elif event_type == 'customer.subscription.created':
        print('Subscription created %s', event.id)
    elif event_type == 'customer.subscription.updated':
        print('Subscription created %s', event.id)
    elif event_type == 'customer.subscription.deleted':
        # handle subscription canceled automatically based
        # upon your subscription settings. Or if the user cancels it.
        print('Subscription canceled: %s', event.id)

    return JsonResponse({'status': 'success'})```
#

./stripe listen --forward-to localhost:8000/webhook

abstract flame
#

Are you sure the path is correct? and your server is running correctly?

daring field
#

path('webhook/', webhook_received, name='webhook'),

#
Quit the server with CONTROL-C.
/home/shell/Desktop/qhp/qhp/urls.py changed, reloading.
Watching for file changes with StatReloader
Performing system checks...

System check identified no issues (0 silenced).
March 28, 2022 - 18:38:12
Django version 3.2.12, using settings 'qhp.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.```
#
[28/Mar/2022 18:39:05] "POST /webhook HTTP/1.1" 500 72423
[28/Mar/2022 18:39:05] "POST /webhook HTTP/1.1" 500 72423```
abstract flame
#

So looks like you found the issue already - looks like you have to set APPEND_SLASH=False

daring field
#

'AttributeError' object has no attribute 'get'

abstract flame
#

When are you getting that error?

daring field
#

When I run payment intent

#

./stripe trigger payment.something

karmic linden
#

What line of code is it on? Is it in the code that you have already sent us?

daring field
#

No it's a normal command

karmic linden
#

Whenever you run any stripe command you get 'AttributeError' object has no attribute 'get'?

#

And that is the full output?

#

Just trying to get a better idea of how to look in to this.

daring field
#
[28/Mar/2022 19:21:55] "POST /webhooks/stripe/ HTTP/1.1" 500 66738
[28/Mar/2022 19:21:55] "POST /webhooks/stripe/ HTTP/1.1" 500 66738
[28/Mar/2022 19:21:55] "GET /success/?session_id=cs_test_a1mOsFjRaByPfjDJ0ebJWjWBgSdQNc5g54ov7CxAQzFs4SZpeZ2iLKdlf3 HTTP/1.1" 200 3415
Internal Server Error: /webhooks/stripe/
Traceback (most recent call last):
  File "/home/shell/Desktop/qhp/env/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner
    response = get_response(request)
  File "/home/shell/Desktop/qhp/env/lib/python3.8/site-packages/django/utils/deprecation.py", line 119, in __call__
    response = self.process_response(request, response)
  File "/home/shell/Desktop/qhp/env/lib/python3.8/site-packages/django/middleware/clickjacking.py", line 26, in process_response
    if response.get('X-Frame-Options') is not None:
AttributeError: 'AttributeError' object has no attribute 'get'
[28/Mar/2022 19:21:55] "POST /webhooks/stripe/ HTTP/1.1" 500 66738
Internal Server Error: /webhooks/stripe/
Traceback (most recent call last):
  File "/home/shell/Desktop/qhp/env/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner
    response = get_response(request)
  File "/home/shell/Desktop/qhp/env/lib/python3.8/site-packages/django/utils/deprecation.py", line 119, in __call__
    response = self.process_response(request, response)
  File "/home/shell/Desktop/qhp/env/lib/python3.8/site-packages/django/middleware/clickjacking.py", line 26, in process_response
    if response.get('X-Frame-Options') is not None:
AttributeError: 'AttributeError' object has no attribute 'get'
[28/Mar/2022 19:21:55] "POST /webhooks/stripe/ HTTP/1.1" 500 66738```
#

this is the output

karmic linden
#

That call stack is for your webhook endpoint code. Can you see how far your webhook endpoint code is getting before throwing this error?

daring field
#

ok

daring field
#

i fixed alot

#
  File "/home/shell/Desktop/qhp/recipes/views.py", line 157, in webhook_received
    receipt_email=session["billing_details"]["email"]
  File "/home/shell/Desktop/qhp/env/lib/python3.8/site-packages/stripe/stripe_object.py", line 132, in __getitem__
    raise err
  File "/home/shell/Desktop/qhp/env/lib/python3.8/site-packages/stripe/stripe_object.py", line 120, in __getitem__
    return super(StripeObject, self).__getitem__(k)
KeyError: 'billing_details'
[28/Mar/2022 20:23:09] "POST /webhooks/stripe/ HTTP/1.1" 500 106171
[28/Mar/2022 20:23:09] "GET /success/?session_id=cs_test_a1FR96Q1mgWXEWL8ggQMkCGpuoDAheWG7btwZDL6vJvy2cqZTKObLDBYMU HTTP/1.1" 200 3405```
karmic linden
#

Awesome! So do you know which line of your webhook code it is?

daring field
#

yes

#

i'm not able to get the email

#

customer = ["billing_detail"]["email']

karmic linden
#

What is the customer ID? Does that customer have a billing email set?

#

You may want to add a check to see if ["billing_detail"]["email'] exists before doing the get

daring field
#
        "data": [
          {
            "amount": 9900,
            "amount_captured": 9900,
            "amount_refunded": 0,
            "application": null,
            "application_fee": null,
            "application_fee_amount": null,
            "balance_transaction": "txn_3KiP5hDaN18cbJKs060EW6I9",
            "billing_details": {
              "address": {
                "city": null,
                "country": "IN",
                "line1": null,
                "line2": null,
                "postal_code": null,
                "state": null
              },
              "email": "shazeb@qhp.com",
              "name": "SYED HUSSAINI",
              "phone": null
            },
            "calculated_statement_descriptor": "P2PSECPTEL",
            "captured": true,
            "created": 1648498986,
            "currency": "usd",
            "customer": "cus_LPDWzprVueSTjn",
            "description": "Subscription creation",
            "destination": null,
            "dispute": null,```
#
Traceback (most recent call last):
  File "/home/shell/Desktop/qhp/env/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner
    response = get_response(request)
  File "/home/shell/Desktop/qhp/env/lib/python3.8/site-packages/django/core/handlers/base.py", line 181, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/home/shell/Desktop/qhp/env/lib/python3.8/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view
    return view_func(*args, **kwargs)
  File "/home/shell/Desktop/qhp/recipes/views.py", line 162, in webhook_received
    stripe_payment_id=session["payment_intent"],
  File "/home/shell/Desktop/qhp/env/lib/python3.8/site-packages/stripe/stripe_object.py", line 132, in __getitem__
    raise err
  File "/home/shell/Desktop/qhp/env/lib/python3.8/site-packages/stripe/stripe_object.py", line 120, in __getitem__
    return super(StripeObject, self).__getitem__(k)
KeyError: 'payment_intent'```
wispy garden
#

Hello! I'm taking over and catching up...

#

Okay, so what line of your code is throwing the error above?

daring field
#

i'm not able to get email

#

its inside charges

wispy garden
#

Right, but what is the line of code throwing that error?

daring field
#
def webhook_received(request):
    webhook_secret = settings.WEBHOOK_KEY
    payload = request.body
    sig_header = request.META['HTTP_STRIPE_SIGNATURE']
    event = None

    try:
        event = stripe.Webhook.construct_event(
        payload, sig_header, webhook_secret
        )
    except ValueError as e:
        # Invalid payload
        return e
    except stripe.error.SignatureVerificationError as e:
        # Invalid signature
        return e

    if event['type'] == 'payment_intent.succeeded':
        session = event['data']['object']
        # print(session)
        receipt_email=session["charges"]["data"]["billing_details"]["email"]
        print(receipt_email)


        #Creating a successfull copy
        Subscription.objects.create(
            stripe_payment_id=session["payment_intent"],
            customer=session["customer"],
            payment_type=session["payment_method_types"],
            status=session["payment_status"],
            email=session["charges"]["data"]["billing_details"]["email"]

        )```
#

line 19th

#

and line 23

wispy garden
#

Line 19 is if event['type'] == 'payment_intent.succeeded': and line 23 is print(receipt_email) which both do not seem like the lines throwing the error above.

#

You sure it's not line 28?

daring field
#

line 22

#

receipt_email=session["charges"]["data"]["billing_details"]["email"]

wispy garden
#

That doesn't seem possible. The error you mentioned above was KeyError: 'payment_intent' and line 22 does not try to reference payment_intent at all.

daring field
#

I'm getting error from both

wispy garden
#

Okay, let's focus on a single error at a time. What is the specific error and associated line of code you want to work on first?

daring field
#

email

wispy garden
#

Okay, so what's the error you're getting related to that?

daring field
#
  File "/home/shell/Desktop/qhp/recipes/views.py", line 157, in webhook_received
    receipt_email=session["billing_details"]["email"]
  File "/home/shell/Desktop/qhp/env/lib/python3.8/site-packages/stripe/stripe_object.py", line 132, in __getitem__
    raise err
  File "/home/shell/Desktop/qhp/env/lib/python3.8/site-packages/stripe/stripe_object.py", line 120, in __getitem__
    return super(StripeObject, self).__getitem__(k)
KeyError: 'billing_details'
[28/Mar/2022 20:23:09] "POST /webhooks/stripe/ HTTP/1.1" 500 106171
[28/Mar/2022 20:23:09] "GET /success/?session_id=cs_test_a1FR96Q1mgWXEWL8ggQMkCGpuoDAheWG7btwZDL6vJvy2cqZTKObLDBYMU HTTP/1.1" 200 3405```
#
        "data": [
          {
            "amount": 9900,
            "amount_captured": 9900,
            "amount_refunded": 0,
            "application": null,
            "application_fee": null,
            "application_fee_amount": null,
            "balance_transaction": "txn_3KiP5hDaN18cbJKs060EW6I9",
            "billing_details": {
              "address": {
                "city": null,
                "country": "IN",
                "line1": null,
                "line2": null,
                "postal_code": null,
                "state": null
              },
              "email": "shazeb@qhp.com",
              "name": "SYED HUSSAINI",
              "phone": null
            },
            "calculated_statement_descriptor": "P2PSECPTEL",
            "captured": true,
            "created": 1648498986,
            "currency": "usd",
            "customer": "cus_LPDWzprVueSTjn",
            "description": "Subscription creation",
            "destination": null,
            "dispute": null,```
wispy garden
#

Okay, so KeyError: 'billing_details'. And which line of code is throwing that error?

daring field
#

line 22

wispy garden
#

Okay, so I think the issue is that data is an array, so you need to specify which object in that array you want.

#

Right now you have this:

receipt_email=session["charges"]["data"]["billing_details"]["email"]

Which does not specify which item in the data array you want.

#

My Python is rusty, but can you do this to get the first item in the array?

receipt_email=session["charges"]["data"][0]["billing_details"]["email"]
daring field
#

let me try

#

yep working

#

now payment_intent

#

i think i can fix that issue

#

let me check

wispy garden
#

Glad to hear the other one is working! If you need help with the KeyError: 'payment_intent' error let me know!

daring field
#

ok 2min

#

hey @wispy garden which one is better for subscription checkout.session webhook or payment.intent

#

?

wispy garden
#

They're two different events for two different things. One is not "better" than the other. Can you provide more details about what you're trying to do?

daring field
#

i want to create a subscription base model website

wispy garden
#

What does "base model" mean?

daring field
#

means i'll charge my customers on monthly bases

wispy garden
#

Gotcha. Are the docs I linked to above helpful regarding Subscription events?

daring field
#

i think payment_intent.succeeded

#

makes more sense because i'll know that my customer got charged

wispy garden
#

That is certainly one event you should probably be listening to, but there are several others you also probably want to listen for as well.

daring field
#

for example? this is my first time implementing the stripe.

#

it will be helpful if you guide

wispy garden
#

Did you look at the docs I linked above?

#

The link I provided above is literally a guide to which events you should listen for when building a Subscriptions integration.

daring field
#

ok

#

i have last issue

#

i'm getting

#

this error File "/usr/lib/python3.8/smtplib.py", line 339, in connect self.sock = self._get_socket(host, port, self.timeout) File "/usr/lib/python3.8/smtplib.py", line 310, in _get_socket return socket.create_connection((host, port), timeout, File "/usr/lib/python3.8/socket.py", line 808, in create_connection raise err File "/usr/lib/python3.8/socket.py", line 796, in create_connection sock.connect(sa) ConnectionRefusedError: [Errno 111] Connection refused [28/Mar/2022 21:32:47] "POST /webhooks/stripe/ HTTP/1.1" 500 130191

wispy garden
#

That's a connection refused error, which means whatever you were trying to connect to refused the connection. What line of code is throwing that error?

daring field
#

I dont know the line number

#

its not giving me any line number

wispy garden
#

Can you provide the full stack trace?

daring field
#

like the full output?

wispy garden
#

The full stack trace for that error, yeah.

daring field
#

yes

#

2min

wispy garden
#

It's hard to tell for sure, but it looks like you're trying to send an email and the mail server is refusing the connection.

#

What is /home/shell/Desktop/qhp/recipes/views.py? Is that your code or part of a library/framework?

daring field
#

ohh, i'm fkng stupid

#

now i understand.

#

thanks a lot.

#

let me go back and check the email thingy

#

yes, it was a email issue

#

thanks a lot for the help.

wispy garden
#

For what it's worth I don't think the issue is your intelligence, this stuff is hard, and it's easy to get mixed up! ๐Ÿ™‚

#

Happy to help!

daring field
#
2022-03-29 03:21:54  <--  [200] POST http://localhost:8000/webhooks/stripe/ [evt_1KiQTeDaN18cbJKsFUKVX754]
2022-03-29 03:21:55   --> customer.created [evt_1KiQTeDaN18cbJKsCxsDZnZa]
2022-03-29 03:21:55   --> customer.updated [evt_1KiQTeDaN18cbJKsfeANvKKa]
2022-03-29 03:21:55  <--  [200] POST http://localhost:8000/webhooks/stripe/ [evt_1KiQTeDaN18cbJKsCxsDZnZa]
2022-03-29 03:21:55  <--  [200] POST http://localhost:8000/webhooks/stripe/ [evt_1KiQTeDaN18cbJKsfeANvKKa]
2022-03-29 03:21:55   --> invoice.created [evt_1KiQTeDaN18cbJKslqcXEwAY]
2022-03-29 03:21:55   --> invoice.finalized [evt_1KiQTeDaN18cbJKsv3LeKvPs]
2022-03-29 03:21:55  <--  [200] POST http://localhost:8000/webhooks/stripe/ [evt_1KiQTeDaN18cbJKslqcXEwAY]
2022-03-29 03:21:55  <--  [200] POST http://localhost:8000/webhooks/stripe/ [evt_1KiQTeDaN18cbJKsv3LeKvPs]
2022-03-29 03:21:55   --> customer.subscription.created [evt_1KiQTeDaN18cbJKs7mVDjxHL]
2022-03-29 03:21:55  <--  [200] POST http://localhost:8000/webhooks/stripe/ [evt_1KiQTeDaN18cbJKs7mVDjxHL]
2022-03-29 03:21:55   --> invoice.updated [evt_1KiQTfDaN18cbJKstapYWHfH]
2022-03-29 03:21:55  <--  [200] POST http://localhost:8000/webhooks/stripe/ [evt_1KiQTfDaN18cbJKstapYWHfH]
wispy garden
#

All 200s! ๐ŸŽ‰

daring field
#

sorrry just last question. to deploy on the production. do i have to use ngrk?

#

for webhook?

wispy garden
#

In production you would typically have this code on a web server somewhere, and you would create a Webhook Endpoint in Stripe that points to the URL where this code lives.

#

Ngrok is typically used for testing.

daring field
wispy garden
#

Yep!

#

Exactly. ๐Ÿ™‚

daring field
#

ok, thanks a lot

wispy garden
#

No problem!

daring field
#

200 gives a different satisfaction.