#vporto-webhook-python

1 messages · Page 1 of 1 (latest)

floral haloBOT
crimson trout
#

Hi 👋

Can you share the ID of the registered webhook endpoint?

craggy imp
#

Hi man

#

Sure!

#

we_1O1i12LtJnmsejmmy6tP5EFj

#

here itI is

crimson trout
#

Okay and your Django app has a view function mapped to the url https://om-quant-betting-6ead114c71cf.herokuapp.com ?

#

Or is the view function at https://om-quant-betting-6ead114c71cf.herokuapp.com/payments/webhooks ?

craggy imp
#

@login_required
def checkout_page(request, pk):
selected_membership = request.POST.get('selected_membership')
object = Membership.objects.get(slug=selected_membership)

context = {
    'object': object,
    'STRIPE_PUBLISHABLE_KEY': settings.STRIPE_PUBLISHABLE_KEY,
}
return render(request, 'checkout.html', context=context)
#

def create_checkout_session(request):
if settings.DEBUG:
DOMAIN = "http://127.0.0.1:8000"
else:
DOMAIN = "https://om-quant-betting-6ead114c71cf.herokuapp.com"

try:
    checkout_session = stripe.checkout.Session.create(
        line_items=[
            {
                # Provide the exact Price ID (for example, pr_1234) of the product you want to sell
                'price': 'price_1NzU9xLtJnmsejmm8IoTsVPq',
                'quantity': 1,
            },
        ],
        mode='subscription',
        success_url=DOMAIN + '/',
        cancel_url=DOMAIN + '/payments/memberships',
        metadata={
            'user': request.user,
        }

    )
except Exception as e:
    return str(e)

return redirect(checkout_session.url, code=303)
#

@csrf_exempt
def stripe_webhook(request):
payload = request.body

sig_header = request.META['HTTP_STRIPE_SIGNATURE']
event = None

try:
event = stripe.Webhook.construct_event(
payload, sig_header, settings.WEBHOOK_SECRET
)
except ValueError as e:
# Invalid payload
return HttpResponse(status=400)
except stripe.error.SignatureVerificationError as e:
# Invalid signature
return HttpResponse(status=400)

Handle the checkout.session.completed event

if event['type'] == 'checkout.session.completed':
# Retrieve the session. If you require line items in the response, you may include them by expanding line_items.
session = stripe.checkout.Session.retrieve(
event['data']['object']['id'],
expand=['line_items'],
)

user = session.metadata.user

line_items = session.line_items
# Fulfill the purchase...
fulfill_order(line_items, user=user)

Passed signature verification

return HttpResponse(status=200)

#

def fulfill_order(line_items, user):
user = User.objects.get(username=user)
user_membership = UserMembership.objects.get(user=user)
new_membership = Membership.objects.get(membership_type='Paid')

  user_membership.membership = new_membership
  user_membership.save()

  #Checking to see if user has an existing subscription
  subscription = Subscription.objects.filter(user_membership=user_membership).first()
  # if the user has a subscription, update the subscription expiration date
  if subscription is not None:
      subscription.expiration_date = datetime.date.today() + datetime.timedelta(days=30)
      subscription.save()
  # if the user doesn't have a subscription, create one
  else:
      new_subscription = Subscription.objects.create(
          user_membership=user_membership,
          stripe_subscription_id='sub_12345',
          active=True,
          expiration_date=datetime.date.today() + datetime.timedelta(days=30)
      )
      new_subscription.save()
#

those are the functions that deal with stripe checkout

crimson trout
#

I don't have time to read all of this

#

You should be able to answer my question pretty easily

craggy imp
#

Ok

crimson trout
#

Is your webhook receiving function reachable at the URL you registered?

craggy imp
crimson trout
#

Well that is the problem

#

You need to give the exact URL that maps to the webhook receiver function in your Django app

craggy imp
#

Can you point me where it is on the documentation please?

crimson trout
craggy imp
#

Hi man

#

I still didnt find where I can map the function to read the specific url

#

would you help me

crimson trout
#

You would register a new webhook endpoint with the complete URL that points to the function you wrote in your Django app

craggy imp
#

I already did that

#

here's the complete webhook

crimson trout
#

Okay and you have a Django view wired up to that URL?

craggy imp
#

yes

#

you mean that?

crimson trout
#

No

floral haloBOT
crimson trout
#

If you are building a Django app, you should have the /payments/webhooks route registered in your urls.py file. That shoud point to a view function or class that handles receiving webhooks

craggy imp
#

I have it. look

#

'webhooks'

#

leads to the stripe_webhook view

crimson trout
#

You need to add some logging to make it clear if that view function is actually getting hit

marble fox
#

vporto-webhook-python

craggy imp
#

that is the function the url leads to

#

I got it from docs

craggy imp
#

it doesnt get hit in deploy and in my localhost if I dont type the command