extension-stripe

Payment support based on Stripe, supporting credit cards and debit cards

npx skills add https://github.com/caffeinelabs/skills --skill extension-stripe

Stripe Payment Integration

Stripe payment extension for Caffeine AI.

Overview

This skill adds Stripe payment support using HTTP outcalls. The MixinStripe mixin provides configuration, checkout session creation, payment status checks, and the HTTP outcall transform callback. The frontend handles checkout flow and payment result pages.

Inbound Stripe webhooks (an external POST to the canister) are not covered here — use extension-http-endpoints for the http_request / http_request_update handlers, then verify Stripe signatures in the update path.

Prerequisite: You must follow extension-authorization first, as this integration depends on it.

Backend

Module API

The prefabricated module mo:caffeineai-stripe/stripe.mo provides low-level Stripe HTTP helpers. Do not modify it.

import OutCall "mo:caffeineai-http-outcalls/outcall";

module {
  public type StripeConfiguration = {
    secretKey : Text;
    allowedCountries : [Text];
  };

  public type StripeState = {
    var configuration : ?StripeConfiguration;
  };

  public func initState() : StripeState;

  public type ShoppingItem = {
    currency : Text;
    productName : Text;
    productDescription : Text;
    priceInCents : Nat;
    quantity : Nat;
  };

  public func createCheckoutSession(configuration : StripeConfiguration, caller : Principal, items : [ShoppingItem], successUrl : Text, cancelUrl : Text, transform : OutCall.Transform) : async Text;

  public type StripeSessionStatus = {
    #failed : { error : Text };
    #completed : { response : Text; userPrincipal : ?Text };
  };

  public func getSessionStatus(configuration : StripeConfiguration, sessionId : Text, transform : OutCall.Transform) : async StripeSessionStatus;
};

Setup in main.mo

include MixinStripe(accessControlState, stripeState) MUST be placed in main.mo, not in a custom mixin file. The mixin provides these public endpoints automatically:

  • isStripeConfigured()
  • setStripeConfiguration(config)
  • createCheckoutSession(items, successUrl, cancelUrl)
  • getStripeSessionStatus(sessionId)
  • transform(input) — required for HTTP outcall response transformation

Do NOT redeclare any of these functions. They are provided exclusively by MixinStripe.

import Stripe "mo:caffeineai-stripe/stripe";
import AccessControl "mo:caffeineai-authorization/access-control";
import MixinAuthorization "mo:caffeineai-authorization/MixinAuthorization";
import MixinStripe "mo:caffeineai-stripe/MixinStripe";
import Map "mo:core/Map";
import Iter "mo:core/Iter";
import Text "mo:core/Text";
import Runtime "mo:core/Runtime";

actor {
  // Include authorization
  let accessControlState : AccessControl.AccessControlState;
  include MixinAuthorization(accessControlState, null);
  let stripeState : Stripe.StripeState;
  include MixinStripe(accessControlState, stripeState);

  public type Product = {
    id : Text;
    // add custom fields
  };

  let products : Map.Map<Text, Product>;

  public query func getProducts() : async [Product] {
    products.values().toArray();
  };

  public shared ({ caller }) func addProduct(product : Product) : async () {
    if (not (AccessControl.hasPermission(accessControlState, caller, #admin))) {
      Runtime.trap("Unauthorized: Only admins can add products");
    };
    products.add(product.id, product);
  };

  public shared ({ caller }) func updateProduct(product : Product) : async () {
    if (not (AccessControl.hasPermission(accessControlState, caller, #admin))) {
      Runtime.trap("Unauthorized: Only admins can update products");
    };
    products.add(product.id, product);
  };

  public shared ({ caller }) func deleteProduct(productId : Text) : async () {
    if (not (AccessControl.hasPermission(accessControlState, caller, #admin))) {
      Runtime.trap("Unauthorized: Only admins can delete products");
    };
    products.remove(productId);
  };

  // Add more data and functions as needed
};

The migration chain head:

import Map "mo:core/Map";
import AccessControl "mo:caffeineai-authorization/access-control";

module {
  type Product = {
    id : Text;
  };

  type StripeConfiguration = {
    secretKey : Text;
    allowedCountries : [Text];
  };

  type StripeState = {
    var configuration : ?StripeConfiguration;
  };

  type NewActor = {
    accessControlState : AccessControl.AccessControlState;
    products : Map.Map<Text, Product>;
    stripeState : StripeState;
  };

  public func migration(_old : {}) : NewActor {
    {
      accessControlState = AccessControl.initState();
      products = Map.empty<Text, Product>();
      stripeState = { var configuration = null };
    };
  };
};

Frontend

For Stripe payment integration:

Usage:

  1. Implement a PaymentSetup component with:

    • Use isStripeConfigured() and setStripeConfiguration()
    • Checks whether Stripe payment is configured.
    • If not, opens an admin panel and asks the user to initialze Stripe with StripeConfiguration.
      • Stripe secret key
      • List of allowed countries, notation ["US", "CA", "GB"] etc., see the Stripe documentation.
    • Do not show the payment setup when it has already been configured!
  2. Implement a checkout hook:

    • Note that JSON parsing of backend createCheckoutSession result is needed.
    • Validate that the parsed session includes a non-empty url. If missing, throw an error and do not redirect.
    import { useMutation } from '@tanstack/react-query';
    import { useActor } from '@caffeineai/core-infrastructure';
    import { ShoppingItem } from '../backend';
    
    export type CheckoutSession = {
        id: string;
        url: string;
    };
    
    export function useCreateCheckoutSession() {
        const { actor } = useActor();
    
        return useMutation({
            mutationFn: async (items: ShoppingItem[]): Promise<CheckoutSession> => {
                if (!actor) throw new Error('Actor not available');
                const baseUrl = `${window.location.protocol}//${window.location.host}`;
                const successUrl = `${baseUrl}/payment-success`;
                const cancelUrl = `${baseUrl}/payment-failure`;
                const result = await actor.createCheckoutSession(items, successUrl, cancelUrl);
                // JSON parsing is important!
                const session = JSON.parse(result) as CheckoutSession;
                if (!session?.url) {
                    throw new Error('Stripe session missing url');
                }
                return session;
            }
        });
    }
    
  3. Implement a Payment component with:

    • useCreateCheckoutSession()
    • Pass ShoppingItem[] as input.
    • Anaylze the CheckoutSession result.
    • Redirect webpage to url in CheckoutSession: This allows the user to complete the payment.
    • Do NOT use router navigation for the Stripe URL. Use window.location.href.
    • Never navigate to /undefined; if session.url is missing, show an error and stop.
    const session = await createCheckoutSession.mutateAsync(shoppingItems);
    if (!session?.url) throw new Error('Stripe session missing url');
    window.location.href = session.url;
    
  4. Implement a PaymentSuccess and PaymentFailure component to handle payment success or failure, respectively.

  5. Route two specific paths to the payment status components:

    • Path "/payment-success" to PaymentSuccess.
    • Path "/payment-failure" to PaymentFailure. You need to use @tanstack router.
  6. The admin view offers a menu to configure Stripe. If not yet configured, it asks the admin to configure Stripe on login.

Side note: Make sure that product images are properly rendered and resized inside the product canvas.

More skills from caffeinelabs

extension-object-storage
caffeinelabs
General file/object storage, such as for images, videos, files, documents and other bulk data. Perfect fit for image galleries, video galleries, and other file or object management. Supports large files beyond IC limit, with browser-cached HTTP URL access.
developmentmedia
extension-openai
caffeinelabs
MANDATORY recipe for every Caffeine build that calls OpenAI (ChatGPT, GPT-4o, an LLM, a chatbot, embeddings). The ONLY supported path is the `openai-client` mops package with a canister-side API-key bearer. Hand-rolling `ic.http_request` to `api.openai.com/v1/...` is a FORBIDDEN anti-pattern — it leaks the bearer across replicated outcalls (security + 13× billing impact), bypasses the typed request/response bindings, and forces hand-rolled JSON on a language with poor JSON support. Load this...
developmentapisecurity
extension-http-outcalls
caffeinelabs
HTTP outcalls performed by the backend canister (not in the frontend).
developmentapi
connector-googlemail
caffeinelabs
Use the `googlemail-client` mops package whenever the user asks the canister to send email, compose a draft, list or read Gmail messages, or fetch the authenticated user's Gmail profile. The package wraps the Gmail REST API v1 at `https://gmail.googleapis.com` via outbound HTTPS calls.
communicationapiproductivity
extension-querying-oql
caffeinelabs
Quick reference for the Caffeine Data Intelligence agent to query an OQL-exposing canister (schema() + execute()) through the `icp` CLI against the project's `backend` canister: read the schema, form JSON queries (filter / order / paginate / aggregate / dotted-path edges), and parse the Candid result rows.
developmentdatabaseapi
extension-core-infrastructure
caffeinelabs
Core infrastructure providing backend connection configuration, storage client, and React app entry point.
developmentapidevops
extension-posting-to-x
caffeinelabs
MANDATORY recipe for every Caffeine build that posts to X (Twitter). The ONLY supported path is the `x-client` mops package with OAuth 2.0 PKCE. Hand-rolling `ic.http_request` or `icBooking.http_request` calls to `api.x.com/2/tweets`, `api.x.com/2/oauth2/token`, or any other X endpoint is a FORBIDDEN anti-pattern — it bypasses bearer auth, replication-cost safeguards, and `x-client`'s null-field handling. Load this skill whenever the user, spec, or any prior task mentions tweeting,...
developmentapi
extension-qr-code
caffeinelabs
QR code scanner using the camera.
productivitymediaimage