def test_whoami_is_subscriber( user_client, wiki_user, ): """Test responses for logged-in users and whether they have an active subscription.""" url = reverse("api.v1.whoami") response = user_client.get(url) assert response.status_code == 200 assert response.json()["is_subscriber"] is False UserSubscription.set_active(wiki_user, "abc123") response = user_client.get(url) assert response.status_code == 200 assert response.json()["is_subscriber"] is True UserSubscription.set_canceled(wiki_user, "abc123") response = user_client.get(url) assert response.status_code == 200 assert response.json()["is_subscriber"] is False
def recurring_payment_management(request): context = { "support_mail_link": "mailto:" + settings.CONTRIBUTION_SUPPORT_EMAIL + "?Subject=Recurring%20payment%20support", "support_mail": settings.CONTRIBUTION_SUPPORT_EMAIL, "cancel_request": False, "cancel_success": False, } if request.user.stripe_customer_id and "stripe_cancel_subscription" in request.POST: context["cancel_request"] = True cancel_success = False try: for subscription_id in cancel_stripe_customer_subscription( request.user.stripe_customer_id): UserSubscription.set_canceled(request.user, subscription_id) except StripeError: log.exception( "Stripe subscription cancellation: Stripe error for %s [%s]", request.user.username, request.user.email, ) else: cancel_success = True context["cancel_success"] = cancel_success if request.user.stripe_customer_id: data = {"active_subscriptions": False} try: data = get_stripe_customer_data(request.user.stripe_customer_id) except StripeError: log.exception( "Stripe subscription data: Stripe error for %s [%s]", request.user.username, request.user.email, ) context.update(data) return render(request, "payments/management.html", context)
def stripe_hooks(request): try: payload = json.loads(request.body) except ValueError: return HttpResponseBadRequest("Invalid JSON payload") try: event = stripe.Event.construct_from(payload, stripe.api_key) except stripe.error.StripeError: raven_client.captureException() return HttpResponseBadRequest() # Generally, for this list of if-statements, see the create_missing_stripe_webhook # function. # The list of events there ought to at least minimally match what we're prepared # to deal with here. if event.type == "invoice.payment_succeeded": invoice = event.data.object _send_payment_received_email(invoice, request.LANGUAGE_CODE) track_event( CATEGORY_MONTHLY_PAYMENTS, ACTION_SUBSCRIPTION_CREATED, f"{settings.CONTRIBUTION_AMOUNT_USD:.2f}", ) elif event.type == "customer.subscription.deleted": obj = event.data.object for user in User.objects.filter(stripe_customer_id=obj.customer): UserSubscription.set_canceled(user, obj.id) track_event(CATEGORY_MONTHLY_PAYMENTS, ACTION_SUBSCRIPTION_CANCELED, "webhook") else: return HttpResponseBadRequest( f"We did not expect a Stripe webhook of type {event.type!r}") return HttpResponse()