Skip to main content
Version: Next

Build a Stripe Payment Agent with ASI:One and uAgents

This guide demonstrates how to create an intelligent Stripe payment agent using ASI:One for natural language processing and the official Stripe API, deployed via uAgents.

Overview

The Stripe ASI:One Agent provides:

  • AI-powered payment link creation with natural-language requests
  • Direct Stripe API integration (products, prices, payment links)
  • ASI:One reasoning for natural language understanding
  • uAgents deployment for 24/7 availability

Prerequisites

Before you begin, ensure you have:

Installation

1. Create Project Directory

mkdir stripe_asi_agent
cd stripe_asi_agent

2. Set Up Virtual Environment

python -m venv venv
source venv/bin/activate # On Windows: venv\Scripts\activate

3. Install Dependencies

Create a requirements.txt file:

# Core uAgents
uagents==0.22.5

# Stripe
stripe==12.2.0

# Environment and utilities
python-dotenv>=1.0.0
requests>=2.31.0

Install the packages:

pip install -r requirements.txt

Environment Setup

1. Create Environment File

Create a .env file in your project directory:

# Stripe Configuration
STRIPE_SECRET_KEY=sk_test_your_stripe_secret_key_here

# ASI:One Configuration
ASI_API_KEY=your_asi_api_key_here

2. Get Your API Keys

Stripe Keys:

  1. Go to Stripe Dashboard
  2. Copy your Secret key (starts with sk_test_)

ASI:One Key:

  1. Go to ASI:One Platform
  2. Create a new API key

Create the Agent

Create stripe_llm_agent.py:

#!/usr/bin/env python3
"""Stripe Payment-Link Agent using ASI:One function-calling and uAgents.

Send any message like:
"Create a payment link for a $1200 laptop"
The LLM extracts {product, amount} via structured output, we call
Stripe to create Product, Price, and PaymentLink, then return the URL.
"""

import os, json, stripe
from uuid import uuid4
from datetime import datetime, timezone
from dotenv import load_dotenv
import requests

from uagents import Agent, Context, Protocol
from uagents_core.contrib.protocols.chat import (
ChatAcknowledgement,
ChatMessage,
TextContent,
chat_protocol_spec,
)

# ---------------------------------------------------------------------------
# Environment
# ---------------------------------------------------------------------------

load_dotenv()
stripe.api_key = os.getenv("STRIPE_SECRET_KEY")
ASI_API_KEY = os.getenv("ASI_API_KEY")
if not stripe.api_key or not ASI_API_KEY:
raise RuntimeError("STRIPE_SECRET_KEY and ASI_API_KEY must be set in environment")

# ASI:One API settings
BASE_URL = "https://api.asi1.ai/v1"
headers = {
"Authorization": f"Bearer {ASI_API_KEY}",
"Content-Type": "application/json"
}

# ---------------------------------------------------------------------------
# ASI:One tool / function definition
# ---------------------------------------------------------------------------

tool_def = {
"type": "function",
"function": {
"name": "create_payment_link",
"description": "Create a one-off Stripe payment link",
"parameters": {
"type": "object",
"properties": {
"product": {
"type": "string",
"description": "Product or service name"
},
"amount": {
"type": "number",
"description": "Price as a decimal number"
},
"currency": {
"type": "string",
"description": "ISO currency code (e.g. usd, inr, eur). Default usd",
"enum": ["usd", "inr", "eur", "gbp", "aud", "cad"]
}
},
"required": ["product", "amount"],
"additionalProperties": False
},
"strict": True
}
}

def is_payment_related(text: str) -> bool:
"""Check if the message is related to creating a payment link."""
prompt = f"""Analyze if the following message is about creating a payment link or processing a payment.
Return only 'true' if it's payment-related, 'false' otherwise.

Message: {text}

Examples of payment-related messages:
- "Create a payment link for a $100 product"
- "I want to sell my laptop for $500"
- "Generate a payment link for consulting services"

Examples of non-payment messages:
- "Hello, how are you?"
- "What's the weather like?"
- "Tell me a joke"
"""

payload = {
"model": "asi1-mini",
"messages": [{"role": "user", "content": prompt}],
"temperature": 0
}

response = requests.post(
f"{BASE_URL}/chat/completions",
headers=headers,
json=payload
)
response.raise_for_status()
return response.json()["choices"][0]["message"]["content"].strip().lower() == 'true'

def parse_with_llm(user_text: str):
"""Returns dict with product & amount extracted by LLM."""
payload = {
"model": "asi1-mini",
"messages": [{"role": "user", "content": user_text}],
"tools": [tool_def],
"tool_choice": {
"type": "function",
"function": {"name": "create_payment_link"}
},
"temperature": 0
}

response = requests.post(
f"{BASE_URL}/chat/completions",
headers=headers,
json=payload
)
response.raise_for_status()
response_json = response.json()

# Handle tool calls from ASI:One response
tool_calls = response_json["choices"][0]["message"].get("tool_calls", [])
if not tool_calls:
raise ValueError("No payment details found in the message")

tool_call = tool_calls[0]
return json.loads(tool_call["function"]["arguments"])

# ---------------------------------------------------------------------------
# Stripe helper
# ---------------------------------------------------------------------------

def create_payment_link(product: str, amount_usd: float, currency: str):
prod = stripe.Product.create(name=product)
price = stripe.Price.create(unit_amount=int(amount_usd * 100), currency=currency, product=prod.id)
link = stripe.PaymentLink.create(line_items=[{"price": price.id, "quantity": 1}])
return link

# ---------------------------------------------------------------------------
# uAgents setup
# ---------------------------------------------------------------------------

agent = Agent(name="stripe_llm_agent", port=<"ANY OPEN PORT ON YOUR MACHINE">, mailbox=True, seed=<"RANDOM STRING SECRERT SEED PHASE">)
chat_proto = Protocol(spec=chat_protocol_spec)


@chat_proto.on_message(ChatMessage)
async def handler(ctx: Context, sender: str, msg: ChatMessage):
# ack
await ctx.send(sender, ChatAcknowledgement(timestamp=datetime.now(timezone.utc), acknowledged_msg_id=msg.msg_id))

text = " ".join(c.text for c in msg.content if hasattr(c, "text")).strip()
if not text:
return

try:
# First check if the message is payment-related
if not is_payment_related(text):
reply = (
"❌ I can only help with creating payment links. "
"Please ask me to create a payment link for a product or service.\n\n"
"Example: 'Create a payment link for a $100 laptop'"
)
else:
args = parse_with_llm(text)
currency = args.get("currency", "usd").lower()
link = create_payment_link(args["product"], args["amount"], currency)
reply = (
f"✅ Product Created: {args['product']} - {args['amount']} {currency.upper()}\n"
f"✅ Payment Link Generated: {link.url}\n\n"
"---\n*Powered by Stripe + ASI:One + uAgents*"
)
except Exception as e:
reply = f"❌ Error: {e}"

await ctx.send(sender, ChatMessage(timestamp=datetime.now(timezone.utc), msg_id=uuid4(), content=[TextContent(type="text", text=reply)]))


# Additional handler required by AgentChatProtocol spec

@chat_proto.on_message(ChatAcknowledgement)
async def handle_ack(ctx: Context, sender: str, ack: ChatAcknowledgement):
ctx.logger.debug(f"Ack from {sender} for {ack.acknowledged_msg_id}")

# include protocols after all handlers are registered
agent.include(chat_proto, publish_manifest=True)

if __name__ == "__main__":
agent.run()

Understanding the Code

Key Components

1. ASI:One Integration

tool_def = {
"type": "function",
"function": {
"name": "create_payment_link",
"description": "Create a one-off Stripe payment link",
"parameters": {
"type": "object",
"properties": {
"product": {"type": "string"},
"amount": {"type": "number"},
"currency": {"type": "string"}
},
"required": ["product", "amount"]
}
}
}
  • Uses ASI:One for natural language understanding
  • Defines structured function calling
  • Handles payment-related message detection

2. Stripe Integration

def create_payment_link(product: str, amount_usd: float, currency: str):
prod = stripe.Product.create(name=product)
price = stripe.Price.create(unit_amount=int(amount_usd * 100), currency=currency, product=prod.id)
link = stripe.PaymentLink.create(line_items=[{"price": price.id, "quantity": 1}])
return link
  • Direct Stripe API integration
  • Creates products, prices, and payment links
  • Handles currency conversion

3. uAgents Setup

agent = Agent(name="stripe_llm_agent", port=8032, mailbox=True)
chat_proto = Protocol(spec=chat_protocol_spec)
  • Sets up the agent with mailbox functionality
  • Handles message routing and acknowledgments
  • Provides 24/7 availability

Running the Agent

1. Start the Agent

With your virtual environment activated and .env file configured:

python stripe_llm_agent.py

2. Expected Output

🏃 Agent running — press Ctrl+C to stop

Usage Examples

Example 1: Basic Payment Request

Input:

"I want to buy a laptop for $1200"

Expected Response:

✅ Product Created: Laptop - 1200 USD
✅ Payment Link Generated: https://buy.stripe.com/test_XXXXXXXXX

---
*Powered by Stripe + ASI:One + uAgents*

Input:

"Generate a payment link for $49 annual membership"

Expected Response:

✅ Product Created: Annual Membership - 49 USD
✅ Payment Link Generated: https://buy.stripe.com/test_XXXXXXXXX

---
*Powered by Stripe + ASI:One + uAgents*

Agent Capabilities

Payment Operations

  • Create Products - Dynamic product creation
  • Generate Payment Links - Secure Stripe checkout URLs
  • Currency Support - Multiple currency options (USD, INR, EUR, GBP, AUD, CAD)

AI Features

  • 🤖 Natural Language Processing - Understands complex payment requests
  • 🧠 Intelligent Reasoning - Uses ASI:One for context understanding
  • 🎯 Message Classification - Detects payment-related queries
  • 🔄 Error Recovery - Handles API failures gracefully

Integration Features

  • 🌐 uAgents Deployment - 24/7 availability
  • 📬 Mailbox Communication - Agent-to-agent messaging
  • 🔗 API Integration - Real Stripe API calls with sandbox safety
  • 📊 Logging & Monitoring - Built-in error tracking

This guide demonstrates the power of combining ASI:One's natural language processing with Stripe's Payment Links for autonomous agent commerce.

A live instance of this payment-link agent is running on Agentverse: STRIPE TESTING AGENT

Chat screen

Stripe Agent chat

Payment Window

Stripe Agent payment

note

Note: If you want to test it type in the card number as 4242 4242 4242 4242.

You can even test this on ASI:One LLM.

Open the ASI:One and enable agents to ask a question.

can you check for an stripe agent which can generate a payment link for 1400 indian rupees for iphone 15 cover

Stripe Agent payment ASI ONE

note

Note: These are the test sandbox version, no money will be deducted and dont put in your original card details.