### Rye SDK Setup Source: https://rye.com/docs/api-v2/lovable-rye-tutorial Instructions for setting up the Rye checkout-intents SDK in a Deno (Supabase Edge Functions) or Node.js environment. Includes installation, environment variable configuration, and client initialization. ```APIDOC ## Rye SDK Setup In Supabase Edge Functions (Deno), import the SDK via npm: ``` import CheckoutIntents from 'npm:checkout-intents'; ``` For Node.js projects: ``` npm install checkout-intents import CheckoutIntents from 'checkout-intents'; ``` Environment variable: `CHECKOUT_INTENTS_API_KEY` (the SDK reads this by default) For staging, also set: `CHECKOUT_INTENTS_BASE_URL=https://staging.api.rye.com` Initialize: ```javascript const client = new CheckoutIntents(); // reads CHECKOUT_INTENTS_API_KEY from env ``` ``` -------------------------------- ### Install Rendering Dependencies Source: https://rye.com/docs/api-v2/example-flows/chat-storefront Install libraries for rendering markdown and parsing HTML. ```bash npm install cheerio react-markdown ``` -------------------------------- ### Install and Initialize Checkout Intents SDK Source: https://rye.com/docs/api-v2/example-flows/simple-checkout Install the SDK using npm and initialize the client. The client automatically reads the API key from the CHECKOUT_INTENTS_API_KEY environment variable. ```bash npm install checkout-intents ``` ```typescript import CheckoutIntents from 'checkout-intents'; const client = new CheckoutIntents(); ``` -------------------------------- ### Install LLM and Commerce Dependencies Source: https://rye.com/docs/api-v2/example-flows/chat-storefront Install necessary libraries for AI chat functionality and Stripe payment processing. ```bash npm install ai @ai-sdk/openai @ai-sdk/react zod ``` ```bash npm install @stripe/stripe-js @stripe/react-stripe-js ``` -------------------------------- ### Example Completed Response Source: https://rye.com/docs/api-v2/example-flows/single-step-checkout An example JSON response indicating a successful order placement. ```json { "state": "completed" } ``` -------------------------------- ### Install and Import Rye SDK in Node.js Source: https://rye.com/docs/api-v2/lovable-rye-tutorial Install the SDK using npm and import it for use in Node.js projects. ```bash npm install checkout-intents ``` ```javascript import CheckoutIntents from 'checkout-intents'; ``` -------------------------------- ### List Events with Java Source: https://rye.com/docs/api-v2/api-reference/events/list-events Retrieve a paginated list of events. This example initializes the client from environment variables and fetches the first page of events. ```Java package com.rye.example; import com.rye.client.CheckoutIntentsClient; import com.rye.client.okhttp.CheckoutIntentsOkHttpClient; import com.rye.models.events.EventListPage; import com.rye.models.events.EventListParams; public final class Main { private Main() {} public static void main(String[] args) { CheckoutIntentsClient client = CheckoutIntentsOkHttpClient.fromEnv(); EventListPage page = client.events().list(); } } ``` -------------------------------- ### Run the App Locally Source: https://rye.com/docs/api-v2/payment-providers/basis-theory This command starts the development server for your application. The app will be accessible at http://localhost:3000, where you can test Basis Theory integration. ```bash npm run dev ``` -------------------------------- ### Example Thin Event Payload Source: https://rye.com/docs/api-v2/webhooks This is an example of a thin event payload. Fetch the full resource using the source ID for complete state. ```json { "id": "evt_ci_abc123def456_completed", "object": "event", "type": "checkout_intent.completed", "createdAt": "2026-03-18T02:30:00.000Z", "source": { "type": "checkout_intent", "id": "ci_abc123def456" } } ``` -------------------------------- ### Create On-Demand Top-Up Invoice Source: https://rye.com/docs/api-v2/api-reference/billing/create-on-demand-top-up-invoice This example demonstrates how to create an on-demand top-up invoice by sending a POST request to the appropriate endpoint with the required parameters. ```APIDOC ## POST /invoices/top-up ### Description Creates an on-demand invoice for a top-up. ### Method POST ### Endpoint /invoices/top-up ### Request Body - **amountSubunits** (integer) - Required - Amount in smallest currency unit (e.g. cents). - **chargeAutomatically** (boolean) - Optional - Override whether to automatically charge the invoice. Defaults to the developer's drawdown config value if not specified. ### Request Example ```json { "amountSubunits": 500000, "chargeAutomatically": false } ``` ### Response #### Success Response (200) - **id** (string) - The unique identifier for the invoice. - **url** (string) - The URL to the invoice. - **amount** (object) - The amount of the invoice. - **currencyCode** (string) - The currency code (e.g. USD). - **amountSubunits** (integer) - The amount in subunits. - **status** (string) - The status of the invoice (e.g., draft, open, paid). - **bankTransferDetails** (object) - Details for bank transfer payments. - **routingNumber** (string) - **accountNumber** (string) - **bankName** (string) - **accountHolderName** (string) #### Response Example ```json { "id": "in_abc123", "url": "https://invoice.stripe.com/i/acct_xxx/test_xxx", "amount": { "currencyCode": "USD", "amountSubunits": 500000 }, "status": "open", "bankTransferDetails": { "routingNumber": "123456789", "accountNumber": "987654321", "bankName": "Example Bank", "accountHolderName": "Example Corp" } } ``` ``` -------------------------------- ### Fetch Full Checkout Intent Source: https://rye.com/docs/api-v2/webhooks After receiving a thin event, call the API to get the complete resource state. ```bash curl -X GET https://api.rye.com/api/v1/checkout-intents/ci_abc123def456 \ -H "Authorization: Bearer YOUR_API_KEY" ``` -------------------------------- ### Transition to Production with AI Source: https://rye.com/docs/api-v2/llm-quickstart Use this prompt to get AI assistance in moving your Rye integration from staging to live production orders, including necessary changes. ```plaintext Read https://docs.rye.com/llm-context.md for context on Rye's Universal Checkout API. Then: I've integrated Rye in staging — help me go to production. What do I need to change? ``` -------------------------------- ### Create Checkout Intent with Java Source: https://rye.com/docs/api-v2/api-reference/checkout-intents/create-checkout-intent Example of creating a checkout intent using the Java client. Ensure the API key is accessible via environment variables. ```Java package com.rye.example; import com.rye.client.CheckoutIntentsClient; import com.rye.client.okhttp.CheckoutIntentsOkHttpClient; import com.rye.models.checkoutintents.Buyer; import com.rye.models.checkoutintents.CheckoutIntent; import com.rye.models.checkoutintents.CheckoutIntentCreateParams; public final class Main { private Main() {} public static void main(String[] args) { CheckoutIntentsClient client = CheckoutIntentsOkHttpClient.fromEnv(); CheckoutIntentCreateParams params = CheckoutIntentCreateParams.builder() .buyer(Buyer.builder() .address1("123 Main St") .city("New York") .country("US") .email("john.doe@example.com") .firstName("John") .lastName("Doe") .phone("1234567890") .postalCode("10001") .province("NY") .build()) ``` -------------------------------- ### Start Rye Integration with AI Source: https://rye.com/docs/api-v2/llm-quickstart This prompt instructs an AI to analyze your codebase, identify your tech stack, and add Rye checkout functionality. ```plaintext Read https://docs.rye.com/llm-context.md for context on Rye's Universal Checkout API. Then: Integrate Rye's Universal Checkout API into my app. ``` -------------------------------- ### Handle Webhooks with Sinatra Source: https://rye.com/docs/api-v2/webhooks Implement a Sinatra application for webhook processing. This example includes manual signature verification using OpenSSL and Rack::Utils.secure_compare. Ensure `RYE_HMAC_SECRET_KEY` is set. ```ruby # gem install sinatra require "sinatra" require "openssl" require "json" WEBHOOK_SECRET = ENV["RYE_HMAC_SECRET_KEY"] def verify_signature(body, signature_header) return false unless signature_header&.start_with?("v0=") expected_signature = signature_header[3..] computed_signature = OpenSSL::HMAC.hexdigest("sha256", WEBHOOK_SECRET, body) Rack::Utils.secure_compare(computed_signature, expected_signature) end post "/webhook" do request.body.rewind body = request.body.read signature_header = request.env["HTTP_X_RYE_SIGNATURE"] unless signature_header && verify_signature(body, signature_header) halt 401, "Unauthorized" end data = JSON.parse(body) # Handle the challenge during setup if data["type"] == "WEBHOOK_URL_VERIFICATION" && data.dig("data", "challenge") content_type :json return { challenge: data["data"]["challenge"] }.to_json end # Process the webhook event topic = request.env["HTTP_X_RYE_TOPIC"] ``` -------------------------------- ### Confirm Checkout Intent with Java Source: https://rye.com/docs/api-v2/api-reference/checkout-intents/confirm-checkout-intent This Java example demonstrates how to confirm a checkout intent using the Rye client library. It requires setting up the client with environment variables for authentication. ```java package com.rye.example; import com.rye.client.CheckoutIntentsClient; import com.rye.client.okhttp.CheckoutIntentsOkHttpClient; import com.rye.models.checkoutintents.CheckoutIntent; import com.rye.models.checkoutintents.CheckoutIntentConfirmParams; import com.rye.models.checkoutintents.PaymentMethod; public final class Main { private Main() {} public static void main(String[] args) { CheckoutIntentsClient client = CheckoutIntentsOkHttpClient.fromEnv(); CheckoutIntentConfirmParams params = CheckoutIntentConfirmParams.builder() .id("id") .paymentMethod(PaymentMethod.StripeTokenPaymentMethod.builder() .stripeToken("tok_1RkrWWHGDlstla3f1Fc7ZrhH") .type(PaymentMethod.StripeTokenPaymentMethod.Type.STRIPE_TOKEN) .build()) .build(); CheckoutIntent checkoutIntent = client.checkoutIntents().confirm(params); } } ``` -------------------------------- ### Example Thin Event Payload Source: https://rye.com/docs/api-v2/webhooks Most webhook payloads are thin events, containing only the resource ID and event type. Fetch the full resource using the provided ID to get the complete state. ```APIDOC ## Example Thin Event Payload ### Description This is an example of a thin event payload, which includes minimal information about the event. To get the full resource details, you should make a subsequent API call using the `source.id`. ### Payload Format ```json { "id": "evt_ci_abc123def456_completed", "object": "event", "type": "checkout_intent.completed", "createdAt": "2026-03-18T02:30:00.000Z", "source": { "type": "checkout_intent", "id": "ci_abc123def456" } } ``` ### Fetching Full Resource Example ```bash curl -X GET https://api.rye.com/api/v1/checkout-intents/ci_abc123def456 \ -H "Authorization: Bearer YOUR_API_KEY" ``` ``` -------------------------------- ### Create Checkout Intent with Ruby SDK Source: https://rye.com/docs/api-v2/example-flows/simple-checkout This Ruby example shows how to create a checkout intent using the SDK. Initialize the client with your API key and pass the buyer and product details. ```ruby require "checkout_intents" client = CheckoutIntents::Client.new( api_key: ENV["RYE_API_KEY"] ) checkout_intent = client.checkout_intents.create( buyer: { address1: "123 Main St", city: "New York", country: "US", email: "john.doe@example.com", firstName: "John", lastName: "Doe", phone: "212-333-2121", postalCode: "10001", province: "NY" }, product_url: "https://flybyjing.com/collections/shop/products/the-big-boi", quantity: 1 ) ``` -------------------------------- ### Example Failed Response Source: https://rye.com/docs/api-v2/example-flows/single-step-checkout An example JSON response indicating a failed checkout, including the reason for failure. ```json { "state": "failed", "failureReason": { "code": "product_out_of_stock", "message": "The item is no longer available." } } ``` -------------------------------- ### Create Top-Up Invoice with Java Source: https://rye.com/docs/api-v2/api-reference/billing/create-on-demand-top-up-invoice This Java example shows how to create an on-demand top-up invoice. Ensure the CheckoutIntents client is initialized with your API key from environment variables. Only one top-up invoice can be active simultaneously. ```Java package com.rye.example; import com.rye.client.CheckoutIntentsClient; import com.rye.client.okhttp.CheckoutIntentsOkHttpClient; import com.rye.models.billing.BillingCreateTopupInvoiceParams; import com.rye.models.billing.BillingCreateTopupInvoiceResponse; public final class Main { private Main() {} public static void main(String[] args) { CheckoutIntentsClient client = CheckoutIntentsOkHttpClient.fromEnv(); BillingCreateTopupInvoiceParams params = BillingCreateTopupInvoiceParams.builder() .amountSubunits(500000) .build(); BillingCreateTopupInvoiceResponse response = client.billing().createTopupInvoice(params); } } ``` -------------------------------- ### Configure GitHub Copilot for Rye Integration Source: https://rye.com/docs/api-v2/llm-quickstart Create a `.github/copilot-instructions.md` file to guide Copilot. This file defines its role, context, workflow steps, and constraints for integrating Rye's Universal Checkout API. ```markdown # Rye Integration Agent You are a Rye integration specialist. Your job is to help the developer add product purchasing to their application using Rye's Universal Checkout API. ## Context Fetch https://docs.rye.com/llm-context.md before starting. This contains the full Rye API reference, SDK docs, code examples, and limitations. ## Workflow Follow these steps in order. Do not skip ahead. ### Step 1: Analyze the codebase Examine the project and identify: - Language and framework (e.g., Next.js, Python/Flask, Ruby on Rails) - Existing payment or checkout code - API patterns (REST clients, fetch wrappers, SDK usage) - Environment variable conventions - Test infrastructure ### Step 2: Propose an integration plan Based on your analysis, present a plan covering: - Which Rye SDK to use (TypeScript, Python, Ruby, Java, or raw HTTP) - Multi-step vs single-step checkout (multi-step if the UI shows pricing; single-step for automated/background purchases) - Where checkout logic will live (API route, server action, service layer) - How to handle the async lifecycle (polling vs createAndPoll helper) - Environment setup (staging API key, env vars) Format the plan as a numbered list. Ask the developer to approve before proceeding. ### Step 3: Implement After approval, implement step by step: 1. Install the SDK (`npm install checkout-intents`, `pip install checkout-intents`, etc.) 2. Add environment variables for `RYE_API_KEY` (staging key from https://staging.console.rye.com/account) 3. Create the checkout integration using the SDK's helper methods (`createAndPoll`, `confirmAndPoll`) 4. Use `tok_visa` as the Stripe test token in staging 5. Add error handling for failed intents (check `failureReason`) 6. Follow existing project patterns for file structure, naming, and error handling ### Step 4: Verify After implementation: 1. Walk through the code and confirm it handles the full intent lifecycle: create -> poll -> awaiting_confirmation -> confirm -> poll -> completed/failed 2. Suggest a test scenario using a staging product URL: - Shopify: https://flybyjing.com/collections/shop/products/the-big-boi - Amazon: https://www.amazon.com/Apple-MX532LL-A-AirTag/dp/B0CWXNS552/ 3. Point out any missing error handling or edge cases ## Key constraints - US shipping addresses only - Physical products only - One product per checkout intent (multiple quantity is fine) - Checkout intents expire after 45 minutes - Poll every 10 seconds; allow up to 45 minutes for offer retrieval - Rate limits: 5 req/s, 50 req/day (contact Rye to increase) ## Documentation - Quickstart: https://docs.rye.com/api-v2/example-flows/simple-checkout - Single-step: https://docs.rye.com/api-v2/example-flows/single-step-checkout - API Reference: https://docs.rye.com/api-v2-experimental/api-reference - Lifecycle: https://docs.rye.com/api-v2/checkout-intent-lifecycle - Errors: https://docs.rye.com/api-v2/errors - Go Live: https://docs.rye.com/api-v2/go-live ``` -------------------------------- ### Install Basis Theory React Elements and Checkout Intents Source: https://rye.com/docs/api-v2/payment-providers/basis-theory Install the necessary dependencies for integrating Basis Theory React Elements and the checkout-intents SDK into your NextJS application. ```bash npm install @basis-theory/react-elements checkout-intents ``` -------------------------------- ### List Shipments with Java Source: https://rye.com/docs/api-v2/api-reference/shipments/list-shipments Instantiate the client using environment variables and retrieve the first page of shipments. ```Java package com.rye.example; import com.rye.client.CheckoutIntentsClient; import com.rye.client.okhttp.CheckoutIntentsOkHttpClient; import com.rye.models.shipments.ShipmentListPage; import com.rye.models.shipments.ShipmentListParams; public final class Main { private Main() {} public static void main(String[] args) { CheckoutIntentsClient client = CheckoutIntentsOkHttpClient.fromEnv(); ShipmentListPage page = client.shipments().list(); } } ``` -------------------------------- ### Install Stripe Dependencies in React App Source: https://rye.com/docs/api-v2/payment-providers/stripe Install the necessary Stripe.js and React Stripe.js libraries for your React application. These packages are required for handling Stripe elements and tokenization. ```bash npm install @stripe/stripe-js @stripe/react-stripe-js ``` -------------------------------- ### Initialize CheckoutIntents SDK in Python Source: https://rye.com/docs/api-v2/migrate-from-v1 Initialize the CheckoutIntents client with your API key. This is the recommended way to interact with the API. ```python from checkout_intents import CheckoutIntents rye = CheckoutIntents(api_key=os.environ["RYE_API_KEY"]) ``` -------------------------------- ### Set up Home Page Source: https://rye.com/docs/api-v2/example-flows/chat-storefront Configure the home page to render the Chat component. This serves as the entry point for the AI chat interface. ```tsx import Chat from "./components/Chat"; export default function Home() { return (
); } ``` -------------------------------- ### Get Drawdown Balance with cURL Source: https://rye.com/docs/api-v2/api-reference/billing/get-drawdown-balance Make a direct API call to get your drawdown balance using cURL. Ensure you include your API key in the Authorization header. ```cURL curl https://staging.api.rye.com/api/v1/billing/balance \ -H "Authorization: Bearer $CHECKOUT_INTENTS_API_KEY" ``` -------------------------------- ### Get Billing Info OpenAPI Specification Source: https://rye.com/docs/api-v2/api-reference/billing/get-billing-info This OpenAPI specification defines the GET /api/v1/billing endpoint, detailing request parameters, response schemas for success and errors, and authentication methods. ```yaml openapi: 3.0.0 info: title: Universal Checkout API version: 1.0.5 description: >- Turn any product URL into a completed checkout. Instantly retrieve price, tax, and shipping for any product, and let users buy without ever leaving your native AI experience. View the [Rye API docs](https://docs.rye.com). termsOfService: https://rye.com/terms-of-service license: name: UNLICENSED contact: name: Rye email: dev@rye.com url: https://docs.rye.com servers: - url: https://staging.api.rye.com security: [] paths: /api/v1/billing: get: tags: - Billing summary: Get billing info description: Get billing configuration and balance for the authenticated developer operationId: GetSettings parameters: [] responses: '200': description: Billing configuration including drawdown settings and balance content: application/json: schema: $ref: '#/components/schemas/BillingResponse' '401': description: Authentication Failed content: application/json: schema: $ref: '#/components/schemas/AuthenticationError' '422': description: Validation Error content: application/json: schema: $ref: '#/components/schemas/ValidateError' security: - bearerAuth: [] components: schemas: BillingResponse: properties: drawdown: properties: balance: allOf: - $ref: '#/components/schemas/Money' nullable: true config: properties: chargeAutomatically: type: boolean currency: type: string example: USD minBalanceSubunits: type: number format: double example: 200000 targetBalanceSubunits: type: number format: double example: 1000000 required: - chargeAutomatically - currency - minBalanceSubunits - targetBalanceSubunits type: object nullable: true enabled: type: boolean required: - balance - config - enabled type: object required: - drawdown type: object AuthenticationError: properties: name: type: string message: type: string stack: type: string required: - name - message type: object additionalProperties: false ValidateError: properties: name: type: string message: type: string stack: type: string status: type: number format: double fields: $ref: '#/components/schemas/FieldErrors' required: - name - message - status - fields type: object additionalProperties: false Money: properties: currencyCode: type: string example: USD amountSubunits: type: integer format: int32 example: 1500 required: - currencyCode - amountSubunits type: object FieldErrors: properties: {} type: object additionalProperties: properties: value: {} message: type: string required: - message type: object securitySchemes: bearerAuth: type: apiKey in: header name: Authorization description: Rye API key ``` -------------------------------- ### Create React App for Stripe Token Generation Source: https://rye.com/docs/api-v2/payment-providers/stripe Initialize a new React project using Vite and navigate into the project directory. This sets up the basic structure for a Stripe integration demo. ```bash npm create vite@latest stripe-demo -- --template react cd stripe-demo ``` -------------------------------- ### GET /api/v1/checkout-intents/{id} Source: https://rye.com/docs/api-v2/example-flows/chat-storefront Retrieves a Checkout Intent by its ID. ```APIDOC ## GET /api/v1/checkout-intents/{id} ### Description Retrieves a checkout intent by its ID. ### Method GET ### Endpoint /api/v1/checkout-intents/{id} ### Parameters #### Path Parameters - **id** (string) - Required - The ID of the checkout intent to retrieve. ### Response #### Success Response (200) - **id** (string) - The unique identifier for the checkout intent. - **buyer** (Buyer) - Information about the buyer. - **quantity** (number) - The quantity of the product. - **productUrl** (string) - The URL of the product. - **status** (string) - The current status of the checkout intent. - **createdAt** (string) - The timestamp when the checkout intent was created. - **updatedAt** (string) - The timestamp when the checkout intent was last updated. #### Response Example ```json { "id": "ch_12345", "buyer": { "firstName": "John", "lastName": "Doe", "email": "john.doe@example.com", "phone": "123-456-7890", "address1": "123 Main St", "city": "Anytown", "province": "CA", "country": "USA", "postalCode": "12345" }, "quantity": 1, "productUrl": "https://example.com/product/123", "status": "retrieving_offer", "createdAt": "2023-10-27T10:00:00Z", "updatedAt": "2023-10-27T10:00:00Z" } ``` ``` -------------------------------- ### Configure Environment Variables Source: https://rye.com/docs/api-v2/example-flows/chat-storefront Set up your API keys and base URLs in a .env file. Ensure you have your OpenAI API key, Rye API key and base URL, and Stripe publishable key. ```dotenv // .env OPENAI_API_KEY=sk-... RYE_API_KEY=U... # https://staging.console.rye.com/account or https://console.rye.com/account RYE_API_BASE=https://staging.api.rye.com NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY=pk_test_51LgDhrHGDlstla3fdqlULAne0rAf4Ho6aBV2cobkYQ4m863Sy0W8DNu2HOnUeYTQzQnE4DZGyzvCB8Yzl1r38isl00H9sVKEMu ``` -------------------------------- ### Get Billing Info Source: https://rye.com/docs/api-v2/api-reference/billing/get-billing-info Retrieves the billing configuration and balance for the authenticated developer. ```APIDOC ## GET /api/v1/billing ### Description Get billing configuration and balance for the authenticated developer ### Method GET ### Endpoint /api/v1/billing ### Parameters #### Query Parameters None #### Request Body None ### Response #### Success Response (200) - **drawdown** (object) - Billing drawdown information. - **balance** (Money) - Current balance. - **config** (object) - Billing configuration settings. - **chargeAutomatically** (boolean) - **currency** (string) - Example: USD - **minBalanceSubunits** (number) - Example: 200000 - **targetBalanceSubunits** (number) - Example: 1000000 - **enabled** (boolean) #### Response Example ```json { "drawdown": { "balance": { "currencyCode": "USD", "amountSubunits": 1500 }, "config": { "chargeAutomatically": true, "currency": "USD", "minBalanceSubunits": 200000, "targetBalanceSubunits": 1000000 }, "enabled": true } } ``` #### Error Response (401) - **Authentication Failed** #### Error Response (422) - **Validation Error** ``` -------------------------------- ### Poll for Final State Source: https://rye.com/docs/api-v2/example-flows/single-step-checkout Poll the GET endpoint until the checkout intent reaches a terminal state: 'completed' or 'failed'. ```APIDOC ## GET /api/v1/checkout-intents/{id} ### Description Poll this endpoint to retrieve the current state of a checkout intent. Continue polling until the state is terminal ('completed' or 'failed'). ### Method GET ### Endpoint /api/v1/checkout-intents/{id} ### Parameters #### Path Parameters - **id** (string) - Required - The unique identifier of the checkout intent. ### Response #### Success Response (200) - **state** (string) - The current state of the checkout intent. Possible values are 'completed' or 'failed'. - **failureReason** (object) - Optional. Present only if the state is 'failed'. Contains details about the failure. - **code** (string) - A machine-readable error code. - **message** (string) - A human-readable error message. ### Request Example ```json { "state": "completed" } ``` ### Response Example ```json { "state": "failed", "failureReason": { "code": "product_out_of_stock", "message": "The item is no longer available." } } ``` ``` -------------------------------- ### Create Checkout Session in Java Source: https://rye.com/docs/api-v2/api-reference/betas/create-checkout-session Example of creating a checkout session using the Rye Java client. It requires setting up the client with environment variables and building the session creation parameters. ```java package com.rye.example; import com.rye.client.CheckoutIntentsClient; import com.rye.client.okhttp.CheckoutIntentsOkHttpClient; import com.rye.models.betas.CheckoutSession; import com.rye.models.betas.checkoutsessions.CheckoutSessionCreateParams; public final class Main { private Main() {} public static void main(String[] args) { CheckoutIntentsClient client = CheckoutIntentsOkHttpClient.fromEnv(); CheckoutSessionCreateParams params = CheckoutSessionCreateParams.builder() .productUrl("https://www.amazon.com/dp/B0DFC9MT8Q") .quantity(1) .build(); CheckoutSession checkoutSession = client.betas().checkoutSessions().create(params); } } ``` -------------------------------- ### Create Checkout Intent with Python SDK Source: https://rye.com/docs/api-v2/introduction Initialize the CheckoutIntents client using your Rye API key from environment variables. Then, call the create method with buyer and product details. ```python import os from checkout_intents import CheckoutIntents api_key = os.environ["RYE_API_KEY"] client = CheckoutIntents(api_key) checkout_intent = client.checkout_intents.create( buyer={ "address1": "123 Main St", "city": "New York", "country": "US", "email": "john.doe@example.com", "first_name": "John", "last_name": "Doe", "phone": "212-333-2121", "postal_code": "10001", "province": "NY", }, product_url="https://flybyjing.com/collections/shop/products/the-big-boi", quantity=1, ) ``` -------------------------------- ### Identify RyeBot User-Agent String Source: https://rye.com/docs/api-v2/ryebot This is an example of how RyeBot identifies itself in the user-agent string. Ensure your security measures recognize this format. ```text Mozilla/5.0 (X11; Linux x86_64; rv:38.0) Gecko/20100101 Firefox/38.0 (compatible; RyeBot/1.0) ``` -------------------------------- ### List Shipments with cURL Source: https://rye.com/docs/api-v2/api-reference/shipments/list-shipments Make a GET request to the shipments endpoint. Ensure your API key is set as an environment variable. ```cURL curl https://staging.api.rye.com/api/v1/shipments \ -H "Authorization: Bearer $CHECKOUT_INTENTS_API_KEY" ``` -------------------------------- ### List Checkout Intents - cURL Source: https://rye.com/docs/api-v2/api-reference/checkout-intents/list-checkout-intents Make a GET request to the `/api/v1/checkout-intents` endpoint, including your API key in the `Authorization` header. ```cURL curl https://staging.api.rye.com/api/v1/checkout-intents \ -H "Authorization: Bearer $CHECKOUT_INTENTS_API_KEY" ``` -------------------------------- ### Create Payment Gateway Session with Java Source: https://rye.com/docs/api-v2/api-reference/payment-gateways/create-payment-gateway-session Implement session creation for payment gateways using the CheckoutIntents Java client. The client can be initialized from environment variables. ```java package com.rye.example; import com.rye.client.CheckoutIntentsClient; import com.rye.client.okhttp.CheckoutIntentsOkHttpClient; import com.rye.models.paymentgateways.PaymentGateway; import com.rye.models.paymentgateways.PaymentGatewayCreateSessionParams; import com.rye.models.paymentgateways.PaymentGatewaySession; public final class Main { private Main() {} public static void main(String[] args) { CheckoutIntentsClient client = CheckoutIntentsOkHttpClient.fromEnv(); PaymentGatewaySession paymentGatewaySession = client.paymentGateways().createSession(PaymentGateway.BASIS_THEORY); } } ``` -------------------------------- ### Purchase Product using Java SDK Source: https://rye.com/docs/api-v2/api-reference/checkout-intents/purchase-product Use the CheckoutIntentsClient to purchase a product. This involves building CheckoutIntentPurchaseParams with buyer details, payment method, product URL, and quantity. ```java public static void main(String[] args) { CheckoutIntentsClient client = CheckoutIntentsOkHttpClient.fromEnv(); CheckoutIntentPurchaseParams params = CheckoutIntentPurchaseParams.builder() .buyer(Buyer.builder() .address1("123 Main St") .city("New York") .country("US") .email("john.doe@example.com") .firstName("John") .lastName("Doe") .phone("1234567890") .postalCode("10001") .province("NY") .build()) .paymentMethod(PaymentMethod.StripeTokenPaymentMethod.builder() .stripeToken("tok_1RkrWWHGDlstla3f1Fc7ZrhH") .type(PaymentMethod.StripeTokenPaymentMethod.Type.STRIPE_TOKEN) .build()) .productUrl("https://www.amazon.com/dp/B0DFC9MT8Q") .quantity(1) .build(); CheckoutIntent checkoutIntent = client.checkoutIntents().purchase(params); } ``` -------------------------------- ### Confirm Checkout Intent using Stripe Token Source: https://rye.com/docs/api-v2/api-reference/checkout-intents/confirm-checkout-intent This example shows how to confirm a checkout intent using a Stripe token for payment. ```APIDOC ## POST /api/v1/checkout-intents/$ID/confirm ### Description Confirms a checkout intent, processing the payment and finalizing the order. ### Method POST ### Endpoint /api/v1/checkout-intents/$ID/confirm ### Parameters #### Request Body - **paymentMethod** (object) - Required - Details of the payment method. - **stripeToken** (string) - Required - The token generated by Stripe for the payment. - **type** (string) - Required - The type of payment method, e.g., "stripe_token". ### Request Example { "paymentMethod": { "stripeToken": "tok_1RkrWWHGDlstla3f1Fc7ZrhH", "type": "stripe_token" } } ### Response #### Success Response (200) - **CheckoutIntent** (object) - The updated checkout intent object. #### Response Example { "id": "ci_1RkrWWHGDlstla3f1Fc7ZrhH", "state": "placing_order", "amount": { "currency": "USD", "value": "100.00" }, "paymentMethod": { "type": "stripe_token", "stripeToken": "tok_1RkrWWHGDlstla3f1Fc7ZrhH" }, "offer": { "id": "off_1RkrWWHGDlstla3f1Fc7ZrhH", "name": "Sample Product", "price": { "currency": "USD", "value": "100.00" } }, "orderId": "ord_1RkrWWHGDlstla3f1Fc7ZrhH" } ``` -------------------------------- ### Webhook Implementation Source: https://rye.com/docs/api-v2/webhooks Examples of how to implement a webhook endpoint in different programming languages to handle incoming events from Rye. This includes setting up an HTTP server, verifying webhook signatures, and processing event data. ```APIDOC ## POST /webhook ### Description This endpoint receives webhook events from Rye. It verifies the signature of incoming requests and processes event data. ### Method POST ### Endpoint /webhook ### Headers - **x-rye-signature** (string) - Required - The signature of the webhook payload. - **x-rye-topic** (string) - Required - The topic of the webhook event. ### Request Body The request body contains the event data in JSON format. ### Request Example (TypeScript) ```typescript import { CheckoutIntents } from "checkout-intents"; import express from "express"; const app = express(); const client = new CheckoutIntents(); const WEBHOOK_SECRET = process.env.RYE_HMAC_SECRET_KEY!; app.use(express.raw({ type: "application/json" })); app.post("/webhook", (req, res) => { const signatureHeader = req.headers["x-rye-signature"] as string; if (!signatureHeader) { return res.status(401).send("Unauthorized"); } const event = client.events.unwrap( req.body.toString(), signatureHeader, WEBHOOK_SECRET, ); // Handle the challenge during setup if (event.type === "webhook_endpoint.verification_challenge") { return res.json({ challenge: event.source.id }); } // Process the webhook event const topic = req.headers["x-rye-topic"]; console.log(`Received event: ${topic}`); res.status(200).send("OK"); }); app.listen(3000, () => { console.log("Webhook server listening on port 3000"); }); ``` ### Request Example (Python) ```python from flask import Flask, request, jsonify import os import hmac import hashlib from checkout_intents import CheckoutIntentsClient app = Flask(__name__) WEBHOOK_SECRET = os.environ["RYE_HMAC_SECRET_KEY"] client = CheckoutIntentsClient() @app.route("/webhook", methods=["POST"]) def webhook(): signature_header = request.headers.get("x-rye-signature") if not signature_header: return "Unauthorized", 401 event = client.events.unwrap( request.get_data(), signature_header, WEBHOOK_SECRET, ) # Handle the challenge during setup if event.type == "webhook_endpoint.verification_challenge": return jsonify({"challenge": event.source.id}) # Process the webhook event topic = request.headers.get("x-rye-topic") print(f"Received event: {topic}") return "OK", 200 if __name__ == "__main__": app.run(port=3000) ``` ### Request Example (Java) ```java import com.rye.client.CheckoutIntentsClient; import com.rye.client.okhttp.CheckoutIntentsOkHttpClient; import com.rye.models.events.Event; import com.rye.models.events.WebhookSignatureVerificationException; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import java.util.Map; @RestController public class WebhookController { private static final String WEBHOOK_SECRET = System.getenv("RYE_HMAC_SECRET_KEY"); private static final ObjectMapper mapper = new ObjectMapper(); private final CheckoutIntentsClient client = CheckoutIntentsOkHttpClient.builder() .apiKey(System.getenv("RYE_API_KEY")), .build(); @PostMapping("/webhook") public ResponseEntity handleWebhook( @RequestBody String body, @RequestHeader(value = "x-rye-signature", required = false) String signatureHeader, @RequestHeader(value = "x-rye-topic", required = false) String topic) { Event event; try { event = client.events().unwrap(body, signatureHeader, WEBHOOK_SECRET); } catch (WebhookSignatureVerificationException e) { return ResponseEntity.status(401).body("Unauthorized"); } // Handle the challenge during setup if (event.type().equals(Event.Type.WEBHOOK_ENDPOINT_VERIFICATION_CHALLENGE)) { return ResponseEntity.ok(Map.of("challenge", event.source().id())); } // Process the webhook event System.out.println("Received event: " + topic + " for " + event.source().id()); return ResponseEntity.ok("OK"); } } ``` ### Request Example (Ruby) ```ruby # gem install sinatra require "sinatra" require "openssl" require "json" WEBHOOK_SECRET = ENV["RYE_HMAC_SECRET_KEY"] def verify_signature(body, signature_header) return false unless signature_header&.start_with?("v0=") expected_signature = signature_header[3..] computed_signature = OpenSSL::HMAC.hexdigest("sha256", WEBHOOK_SECRET, body) Rack::Utils.secure_compare(computed_signature, expected_signature) end post "/webhook" do request.body.rewind body = request.body.read signature_header = request.env["HTTP_X_RYE_SIGNATURE"] unless signature_header && verify_signature(body, signature_header) halt 401, "Unauthorized" end data = JSON.parse(body) # Handle the challenge during setup if data["type"] == "WEBHOOK_URL_VERIFICATION" && data.dig("data", "challenge") content_type :json return { challenge: data["data"]["challenge"] }.to_json end # Process the webhook event topic = request.env["HTTP_X_RYE_TOPIC"] # ... process event ... "OK" end ``` ### Response #### Success Response (200) Returns "OK" if the webhook event is processed successfully. #### Error Response (401) Returns "Unauthorized" if the signature verification fails. ``` -------------------------------- ### Retrieve Brand by Domain (Java) Source: https://rye.com/docs/api-v2/api-reference/brands/retrieve-brand Example in Java for retrieving brand information. It utilizes the CheckoutIntentsClient and requires the API key to be configured. ```java package com.rye.example; import com.rye.client.CheckoutIntentsClient; import com.rye.client.okhttp.CheckoutIntentsOkHttpClient; import com.rye.models.brands.BrandRetrieveParams; import com.rye.models.brands.BrandRetrieveResponse; public final class Main { private Main() {} public static void main(String[] args) { CheckoutIntentsClient client = CheckoutIntentsOkHttpClient.fromEnv(); BrandRetrieveResponse brand = client.brands().retrieve("shop.aloyoga.com"); } } ``` -------------------------------- ### Create a New NextJS App for Basis Theory Demo Source: https://rye.com/docs/api-v2/payment-providers/basis-theory Use this command to create a new NextJS application with TypeScript, Tailwind CSS, and ESLint configured for your Basis Theory demo. ```bash npx create-next-app@latest bt-demo-next --typescript --tailwind --eslint --app --src-dir --no-import-alias --use-npm cd bt-demo-next ``` -------------------------------- ### Product Updated Event Payload Source: https://rye.com/docs/api-v2/webhooks/types Example payload for a `product.updated` event. This event includes a `data` field containing the full Product object. ```json { "id": "evt_rye-dev-store.myshopify.com:10501236982062_updated_developer_2070443601311540", "object": "event", "type": "product.updated", "createdAt": "2026-04-23T02:42:24.042Z", "source": { "type": "product", "id": "rye-dev-store.myshopify.com:10501236982062" }, "data": { "id": "rye-dev-store.myshopify.com:10501236982062", "url": "https://rye-dev-store.myshopify.com/products/widget-pro", "name": "Widget Pro", "brand": "Acme", "sku": "SKU-12345" } } ``` -------------------------------- ### Set up Root Layout Source: https://rye.com/docs/api-v2/example-flows/chat-storefront Define the main layout for your Next.js application, including header and main content areas. This sets up the basic structure for your app. ```tsx import "./globals.css"; import Link from 'next/link' export default function RootLayout({ children, }: Readonly<{ children: React.ReactNode; }>) { return (
Rye Demo
{children}
); } ``` -------------------------------- ### Lookup Product Source: https://rye.com/docs/api-v2/api-reference/products/lookup-product This endpoint retrieves product details using a product URL. It supports GET requests and requires a 'url' query parameter. ```APIDOC ## GET /api/v1/products/lookup ### Description Lookup a product's information by URL. ### Method GET ### Endpoint /api/v1/products/lookup ### Parameters #### Query Parameters - **url** (string) - Required - The URL of the product to look up. ### Response #### Success Response (200) - **Product** (object) - Contains detailed product information. #### Error Responses - **401** - Authentication Failed - **404** - Not Found - **422** - Validation Error - **500** - Internal Server Error ### Request Example ```curl curl https://staging.api.rye.com/api/v1/products/lookup?url=https://example.com/products/widget-pro \ -H "Authorization: Bearer $CHECKOUT_INTENTS_API_KEY" ``` ### Response Example ```json { "variants": [ { "sku": "WIDGET-PRO-RED", "price": { "amount": 1999, "currency": "USD" }, "images": [ { "url": "https://example.com/images/widget-pro-red.jpg" } ], "id": "variant-123", "name": "Widget Pro - Red" } ], "variantDimensions": [ { "name": "Color", "options": [ "Red", "Blue" ] } ], "isPurchasable": true, "availability": "in_stock", "price": { "amount": 1999, "currency": "USD" }, "images": [ { "url": "https://example.com/images/widget-pro.jpg" } ], "description": "A high-quality widget designed for professionals.", "brand": "Acme", "name": "Widget Pro", "sku": "SKU-12345", "url": "https://example.com/products/widget-pro", "id": "prod-abcde" } ``` ```