def test_find_by_price_id_positive(self): product = PRODUCTS['club1_recurrent_yearly'] price_id = product['stripe_id'] result = products.find_by_price_id(price_id=price_id) self.assertIsNotNone(result) self.assertEqual(result, product)
def stripe_webhook(request): payload = request.body sig_header = request.META.get("HTTP_STRIPE_SIGNATURE") if not payload or not sig_header: return HttpResponse("[invalid payload]", status=400) try: event = stripe.Webhook.construct_event(payload, sig_header, settings.STRIPE_WEBHOOK_SECRET) except ValueError: return HttpResponse("[invalid payload]", status=400) except stripe.error.SignatureVerificationError: return HttpResponse("[invalid signature]", status=400) log.info("Stripe webhook event: " + event["type"]) if event["type"] == "checkout.session.completed": session = event["data"]["object"] payment = Payment.finish( reference=session["id"], status=Payment.STATUS_SUCCESS, data=session, ) # todo: do we need throw error in case payment not found? product = PRODUCTS[payment.product_code] product["activator"](product, payment, payment.user) return HttpResponse("[ok]", status=200) if event["type"] == "invoice.paid": invoice = event["data"]["object"] if invoice["billing_reason"] == "subscription_create": # already processed in "checkout.session.completed" event return HttpResponse("[ok]", status=200) user = User.objects.filter(stripe_id=invoice["customer"]).first() # todo: do we need throw error in case user not found? payment = Payment.create( reference=invoice["id"], user=user, product=find_by_price_id( invoice["lines"]["data"][0]["plan"]["id"]), data=invoice, status=Payment.STATUS_SUCCESS, ) product = PRODUCTS[payment.product_code] product["activator"](product, payment, user) return HttpResponse("[ok]", status=200) if event["type"] in {"customer.created", "customer.updated"}: customer = event["data"]["object"] User.objects.filter(email=customer["email"]).update( stripe_id=customer["id"]) return HttpResponse("[ok]", status=200) return HttpResponse("[unknown event]", status=400)
def test_find_by_price_id_not_existed(self): result = products.find_by_price_id(price_id="not-existed-price-id") self.assertIsNone(result)
def test_find_by_price_id_positive(self): result = products.find_by_price_id( price_id="price_1H73q7KgJMaF2rHtswNA3rha") self.assertIsNotNone(result) self.assertEqual(result, PRODUCTS["club50_recurrent_monthly"])