Commet
  • Pricing
Log InTry out
Introducción

Inicio rápido

Integrar con GoIntegrar con Encore

Aprender

Recursos

Referencia del SDKVersionado de APIManejo de erroresTestingCLI

Plugins

Better Auth
DocumentaciónRecursosConstruir con AIAPI ReferenceWebhooks

Integrar con Encore

Agrega cobros y pagos a tu aplicación de Encore.

Instalar

encore app create --example=hello-world myapp
cd myapp
go get github.com/commet-labs/commet-go

Configurar

Guarda los secretos usando el gestor de secretos de Encore en lugar de variables de entorno:

encore secret set --type dev,local,pr,prod CommetAPIKey
encore secret set --type dev,local,pr,prod CommetWebhookSecret
billing/billing.go
package billing

import (
	commet "github.com/commet-labs/commet-go"
)

var secrets struct {
	CommetAPIKey       string
	CommetWebhookSecret string
}

var client *commet.Client

func initClient() error {
	var err error
	client, err = commet.New(
		secrets.CommetAPIKey,
		commet.WithEnvironment(commet.Sandbox),
	)
	return err
}

Suscribir

billing/billing.go
import "context"

type SubscribeParams struct {
	Email      string `json:"email"`
	CustomerID string `json:"customer_id"`
}

type SubscribeResponse struct {
	CheckoutURL string `json:"checkout_url"`
}

//encore:api public method=POST path=/billing/subscribe
func Subscribe(ctx context.Context, req *SubscribeParams) (*SubscribeResponse, error) {
	if err := initClient(); err != nil {
		return nil, err
	}

	_, err := client.Customers.Create(ctx, &commet.CreateCustomerParams{
		Email:      req.Email,
		ID: req.CustomerID,
	})
	if err != nil {
		return nil, err
	}

	subscription, err := client.Subscriptions.Create(ctx, &commet.CreateSubscriptionParams{
		CustomerID: req.CustomerID,
		PlanCode:   "pro",
	})
	if err != nil {
		return nil, err
	}

	return &SubscribeResponse{
		CheckoutURL: subscription.Data["checkout_url"].(string),
	}, nil
}

Verificar acceso

billing/billing.go
type SubscriptionResponse struct {
	Status string `json:"status"`
}

//encore:api public method=GET path=/billing/subscription/:customerID
func GetSubscription(ctx context.Context, customerID string) (*SubscriptionResponse, error) {
	if err := initClient(); err != nil {
		return nil, err
	}

	sub, err := client.Subscriptions.Get(ctx, customerID)
	if err != nil {
		return nil, err
	}

	return &SubscriptionResponse{
		Status: sub.Data["status"].(string),
	}, nil
}

type FeatureResponse struct {
	Allowed bool `json:"allowed"`
}

//encore:api public method=GET path=/billing/features/:feature/:customerID
func CheckFeature(ctx context.Context, feature string, customerID string) (*FeatureResponse, error) {
	if err := initClient(); err != nil {
		return nil, err
	}

	result, err := client.Features.Check(ctx, feature, customerID)
	if err != nil {
		return nil, err
	}

	return &FeatureResponse{
		Allowed: result.Data["allowed"].(bool),
	}, nil
}

Trackear uso

billing/billing.go
func intPtr(i int) *int { return &i }

type UsageParams struct {
	CustomerID string `json:"customer_id"`
}

type UsageResponse struct {
	Tracked bool `json:"tracked"`
}

//encore:api public method=POST path=/billing/usage
func TrackUsage(ctx context.Context, req *UsageParams) (*UsageResponse, error) {
	if err := initClient(); err != nil {
		return nil, err
	}

	_, err := client.Usage.Track(ctx, &commet.TrackUsageParams{
		CustomerID: req.CustomerID,
		Feature:    "api_calls",
		Value:      intPtr(1),
	})
	if err != nil {
		return nil, err
	}

	return &UsageResponse{Tracked: true}, nil
}

El uso se agrega y se cobra al final del período.

Webhooks

billing/webhooks.go
package billing

import (
	"net/http"

	commet "github.com/commet-labs/commet-go"
)

//encore:api public raw method=POST path=/webhooks/commet
func HandleWebhook(w http.ResponseWriter, r *http.Request) {
	rawBody, err := io.ReadAll(r.Body)
	if err != nil {
		http.Error(w, "Failed to read body", http.StatusBadRequest)
		return
	}

	webhooks := &commet.Webhooks{}
	payload, err := webhooks.VerifyAndParse(
		string(rawBody),
		r.Header.Get("x-commet-signature"),
		secrets.CommetWebhookSecret,
	)
	if err != nil {
		http.Error(w, "Invalid signature", http.StatusUnauthorized)
		return
	}

	switch payload["event"] {
	case "subscription.activated":
		// manejar activación
	}

	w.Header().Set("Content-Type", "application/json")
	w.Write([]byte(`{"ok":true}`))
}

Ejecutar

encore run

Relacionado

  • Suscripciones
  • Trackear Uso
  • Portal del Cliente
  • Referencia del SDK

¿Cómo está esta guía?

Integrar con Go

Agrega cobros y pagos a tu aplicación de Go usando net/http.

Integrar con PHP

Instala y configura el SDK de Commet para PHP.

En esta página

Instalar
Configurar
Suscribir
Verificar acceso
Trackear uso
Webhooks
Ejecutar
Relacionado