Integrate with Django
Add billing and payments to your Django application.
Install
pip install commet-sdk djangouv add commet-sdk djangopoetry add commet-sdk djangoConfigure
COMMET_API_KEY=ck_sandbox_xxximport os
from commet import Commet
commet = Commet(
api_key=os.environ["COMMET_API_KEY"],
environment="sandbox",
)Subscribe
import json
from django.http import JsonResponse
from django.views.decorators.http import require_POST
from .commet_client import commet
@require_POST
def subscribe(request):
data = json.loads(request.body)
commet.customers.create(
email=data["email"],
external_id=data["external_id"],
)
subscription = commet.subscriptions.create(
external_id=data["external_id"],
plan_code="pro",
)
return JsonResponse({"checkout_url": subscription.data["checkout_url"]})Check Access
def get_subscription(request, external_id):
sub = commet.subscriptions.get(external_id)
return JsonResponse({"status": sub.data["status"]})
def check_feature(request, feature, external_id):
result = commet.features.check(code=feature, external_id=external_id)
return JsonResponse({"allowed": result.data["allowed"]})Track Usage
@require_POST
def track_usage(request):
data = json.loads(request.body)
commet.usage.track(
external_id=data["external_id"],
feature="api_calls",
value=1,
)
return JsonResponse({"tracked": True})Usage is aggregated and billed at end of period.
Customer Portal
from django.shortcuts import redirect
def portal(request):
result = commet.portal.get_url(external_id="user_123")
return redirect(result.data["portal_url"])Webhooks
import os
from django.views.decorators.csrf import csrf_exempt
from commet import Webhooks
webhooks = Webhooks()
@csrf_exempt
@require_POST
def handle_webhook(request):
payload = webhooks.verify_and_parse(
raw_body=request.body.decode(),
signature=request.headers.get("x-commet-signature"),
secret=os.environ["COMMET_WEBHOOK_SECRET"],
)
if payload is None:
return JsonResponse({"error": "Invalid signature"}, status=401)
if payload["event"] == "subscription.activated":
# handle activation
pass
return JsonResponse({"ok": True})URLs
from django.urls import path
from . import views
urlpatterns = [
path("subscribe", views.subscribe),
path("subscription/<str:external_id>", views.get_subscription),
path("features/<str:feature>/<str:external_id>", views.check_feature),
path("usage", views.track_usage),
path("portal", views.portal),
path("webhooks/commet", views.handle_webhook),
]from django.urls import path, include
urlpatterns = [
path("billing/", include("billing.urls")),
]Related
How is this guide?