### Install Fewsats Python Library Source: https://github.com/fewsats/fewsats-python/blob/main/nbs/index.ipynb Provides instructions for installing the Fewsats Python library using pip, the standard Python package installer. This command fetches the latest version of the library from PyPI. ```sh $ pip install fewsats ``` -------------------------------- ### Python: Example X402 Link Purchase Source: https://github.com/fewsats/fewsats-python/blob/main/nbs/00_core.ipynb This example demonstrates how to use the `pay_x402_link` function to purchase content from a URL requiring X402 payment. It shows a simple call to the function with the target URL and specified blockchain chain. ```python x402_link = "https://proxy402.com/KQzW9kfi3Z" r = fs.pay_x402_link(x402_link, chain="base-sepolia") r.status_code, r.json() ``` -------------------------------- ### Python: Example X402 Offer Payment Source: https://github.com/fewsats/fewsats-python/blob/main/nbs/00_core.ipynb This example demonstrates how to define an X402 offer payload and use the `pay_x402_offer` function to initiate a payment. It shows the structure of a typical X402 offer and how to call the payment function with the offer and chain. ```python x402_offer = { "accepts": [ { "scheme": "exact", "network": "base", "maxAmountRequired": "1", "resource": "https://proxy402.com/L27XYy_NCU", "description": "Payment for GET https://proxy402.com/L27XYy_NCU", "mimeType": "", "payTo": "0xddb24Bd8A6Cb0f2d3eaBF7a828C0b4364668B963", "maxTimeoutSeconds": 300, "asset": "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913", "extra": { "name": "USD Coin", "version": "2" } } ], "error": "X-PAYMENT header is required", "x402Version": 1 } r = fs.pay_x402_offer(x402_offer, chain="base") r.status_code, r.json() ``` -------------------------------- ### Initialize Fewsats Client Source: https://github.com/fewsats/fewsats-python/blob/main/nbs/00_core.ipynb Demonstrates how to initialize the `Fewsats` client using an API key from environment variables. It shows examples for both production and local API endpoints. ```python k = os.getenv("FEWSATS_API_KEY") fs = Fewsats(api_key=k) k = os.getenv("FEWSATS_LOCAL_API_KEY") fs = Fewsats(api_key=k, base_url="http://localhost:8000") ``` -------------------------------- ### Install fewsats Python Library Source: https://github.com/fewsats/fewsats-python/blob/main/README.md This command installs the fewsats library from PyPI using pip, making it available for use in Python projects. ```Shell $ pip install fewsats ``` -------------------------------- ### Example: Instantiate L402Offers from Dictionary Source: https://github.com/fewsats/fewsats-python/blob/main/nbs/00_core.ipynb Shows how to create an instance of the `L402Offers` class using its `from_dict` class method, assuming `l402_offers` is a pre-existing dictionary containing the offer data. ```python l402 = L402Offers.from_dict(l402_offers) l402 ``` -------------------------------- ### Python: Example Usage of Fewsats get_payment_details Source: https://github.com/fewsats/fewsats-python/blob/main/nbs/00_core.ipynb This example demonstrates how to invoke the `get_payment_details` method using pre-existing offer data. It illustrates extracting the Lightning invoice from the JSON response and verifying the HTTP status code, showcasing a typical buyer workflow. ```python r = fs.get_payment_details(l402_offers["payment_request_url"], l402_offers["offers"][0]["id"], "lightning", l402_offers["payment_context_token"]) payment_details = r.json() ln_invoice = payment_details["payment_request"]['lightning_invoice'] r.status_code, payment_details ``` -------------------------------- ### Python: Example Usage of Fewsats add_webhook Source: https://github.com/fewsats/fewsats-python/blob/main/nbs/00_core.ipynb This example demonstrates how to use the `add_webhook` method to register a new notification URL. It shows a simple call with a placeholder URL and how to inspect the response object and its JSON content for confirmation. ```python r = fs.add_webhook("https://example.com") r, r.json() ``` -------------------------------- ### Create Offers to Receive Payments Source: https://github.com/fewsats/fewsats-python/blob/main/nbs/index.ipynb Illustrates how to define and create offers for receiving payments using the `create_offers` method. The example specifies an offer with a unique ID, amount, currency, description, title, and a list of supported payment methods. ```python offers_data = [{ "id": "offer_example", "amount": 1, "currency": "USD", "description": "Receive payment for your service", "title": "1 Credit Package", "payment_methods": ["lightning", "stripe"] }] r = fs.create_offers(offers_data) offers = r.json() offers ``` -------------------------------- ### Python: Example Usage of Fewsats verify_webhook Source: https://github.com/fewsats/fewsats-python/blob/main/nbs/00_core.ipynb This example demonstrates how to use the `verify_webhook` method to validate a sample webhook payload and signature. It shows the process of preparing the raw data and signature, then parsing the verified event into a structured `FewsatsWebhookEvent` object. ```python data = bytes(json.dumps({ "offer_id": "offer-501040", "payment_context_token": "a0b1caf3-3e3b-488f-ae9c-18d64f690894", "amount": 812319, "currency": "USD", "status": "failed", "timestamp": "2025-04-16T08:51:12Z" }, sort_keys=True, separators=(',', ':')), "utf-8") signature = "t=1744793472,v1=89a491b8f3f8e72b75896faa24cb1cfade27bea12bbdfe333759809b8a573ad3" event = Fewsats.verify_webhook(data, signature, "whsec_bIi4m3by9sJ_KNfY5PFWb2YmAqm2WVAvwq5wGuphayE") event ``` -------------------------------- ### Define an Example L402 Offer Structure (Python) Source: https://github.com/fewsats/fewsats-python/blob/main/README.md Illustrates the structure of an L402 offer, typically received from a '402 Payment Required' HTTP response. This dictionary defines the available offers, payment context, and the URL for payment requests. ```Python l402_offer = { "offers":[ { "amount":1, "currency":"USD", "description":"Purchase 1 credit for API access", "id":"offer_c668e0c0", "payment_methods":[ "lightning" ], "title":"1 Credit Package" } ], "payment_context_token":"edb53dec-28f5-4cbb-924a-20e9003c20e1", "payment_request_url":"https://stock.l402.org/l402/payment-request", "version":"0.2.2" } ``` -------------------------------- ### Python: Example Usage of Fewsats get_payment_status Source: https://github.com/fewsats/fewsats-python/blob/main/nbs/00_core.ipynb This example illustrates how to call the `get_payment_status` method using a payment context token. It shows how to retrieve and inspect the HTTP status code and the JSON response, providing immediate feedback on the payment's state. ```python r = fs.get_payment_status(l402_offers["payment_context_token"]) r.status_code, r.json() ``` -------------------------------- ### Install Fewsats MCP server for Claude Desktop App Source: https://github.com/fewsats/fewsats-python/blob/main/mcp/README.md Instructions to install the Fewsats MCP server for integration with the Claude desktop application. This command adds the server to the Claude configuration file, allowing Claude to access Fewsats tools directly. ```bash mcp install main.py --name 'Fewsats MCP' --env-file .env ``` -------------------------------- ### Example L402 Payment Offer Structure Source: https://github.com/fewsats/fewsats-python/blob/main/nbs/index.ipynb Illustrates the typical JSON structure of an L402 payment offer, including details such as amount, currency, description, offer ID, supported payment methods, and the payment context token. This object serves as input for the `pay_offer` method. ```python l402_offer = { "offers":[ { "amount":1, "currency":"USD", "description":"Purchase 1 credit for API access", "id":"offer_c668e0c0", "payment_methods":[ "lightning" ], "title":"1 Credit Package" } ], "payment_context_token":"edb53dec-28f5-4cbb-924a-20e9003c20e1", "payment_request_url":"https://stock.l402.org/l402/payment-request", "version":"0.2.2" } ``` -------------------------------- ### Example: Pay Lightning Invoice with Variable Source: https://github.com/fewsats/fewsats-python/blob/main/nbs/00_core.ipynb Demonstrates how to call the `pay_lightning` method using a pre-defined lightning invoice variable. It shows how to capture the response and access the status code and JSON payload. ```python r = fs.pay_lightning(invoice=ln_invoice, description="fewsats webhook trial", amount=1) lightning_payment = r.json() r.status_code, lightning_payment ``` -------------------------------- ### Example: Pay Lightning Invoice with Hardcoded Value Source: https://github.com/fewsats/fewsats-python/blob/main/nbs/00_core.ipynb Illustrates calling `pay_lightning` with a hardcoded, long lightning invoice string. This example focuses on checking the HTTP status code and the raw text response after a payment attempt. ```python r = fs.pay_lightning(invoice='lnbc100n1p5qlv5dpp5r4jjrenyvlndnr59nx2fgk8azyeaaxzpeuy7putgm07wfnvt398qdqqcqzzsxqrrsssp54897npsmum0av3qqj6jyvl3sks4hlc67ugdyr8x85hla79u262uq9qxpqysgq3m9p2a8j7fy2pxeg5xuhyw4zwwp6md5egkez28afffmsch2l7clhw5922mxlr52gp48w0pdvnngytgj08kn4z8uv25pq7fc0mxhrs6qphe3c0k', description="fewsats webhook trial", amount=1) r.status_code, r.text ``` -------------------------------- ### Example: Validate Invalid L402 Offer Creation Source: https://github.com/fewsats/fewsats-python/blob/main/nbs/00_core.ipynb Demonstrates a test case to ensure that invalid L402 offer dictionaries, missing required fields, correctly raise errors during object instantiation. It uses a `test_fail` utility to assert that an `Offer` creation fails when essential arguments like 'currency', 'description', and 'title' are absent. ```python invalid_json = { 'offers': [{'id': 'test_offer_2', 'amount': 1}], # Missing fields 'payment_context_token': '60a8e027-8b8b-4ccf-b2b9-380ed0930283' # Missing payment_request_url } test_fail(lambda: Offer(id="test", amount=1), contains="missing 3 required positional arguments: 'currency', 'description', and 'title'") ``` -------------------------------- ### Debug Fewsats MCP tools Source: https://github.com/fewsats/fewsats-python/blob/main/mcp/README.md Commands to install necessary dependencies and run the Fewsats MCP server in development mode. This allows users to try out and debug the Fewsats tools locally by opening the inspector. ```bash pip install -r requirements.txt mcp dev main.py ``` -------------------------------- ### Python: Access Resource with X-PAYMENT Header Source: https://github.com/fewsats/fewsats-python/blob/main/nbs/00_core.ipynb After successfully paying an X402 offer, this snippet demonstrates how to use the obtained `payment_header` to access the protected resource. It uses the `httpx` library to make a GET request with the required `X-PAYMENT` header. ```python httpx.get(x402_offer["accepts"][0]["resource"], headers={"X-PAYMENT": r.json()["payment_header"]}) ``` -------------------------------- ### Initial Fewsats Core Import (Hidden) Source: https://github.com/fewsats/fewsats-python/blob/main/nbs/index.ipynb This line imports all necessary components from the `fewsats.core` module. It's typically used for internal library setup or foundational imports, often hidden in user-facing documentation. ```python #| hide from fewsats.core import * ``` -------------------------------- ### Retrieve User Billing Information Source: https://github.com/fewsats/fewsats-python/blob/main/nbs/00_core.ipynb Fetches the authenticated user's billing details from the Fewsats API. This method performs a GET request to the `v0/users/me/billing-info` endpoint. ```python billing_info = fs.billing_info() billing_info.status_code, billing_info.json() ``` -------------------------------- ### Retrieve User Information Source: https://github.com/fewsats/fewsats-python/blob/main/nbs/00_core.ipynb Retrieves the authenticated user's profile information from the Fewsats API. This method makes a GET request to the `v0/users/me` endpoint and returns the API response. ```python r = fs.me() r.status_code, r.json() ``` -------------------------------- ### Retrieve User Payment Methods Source: https://github.com/fewsats/fewsats-python/blob/main/nbs/00_core.ipynb Retrieves a list of payment methods associated with the authenticated user. This is useful for identifying which card will be used for purchases. The method makes a GET request to the `v0/stripe/payment-methods` endpoint. ```python r = fs.payment_methods() payment_methods = r.json() r.status_code, payment_methods ``` -------------------------------- ### Retrieve Wallet Balance Source: https://github.com/fewsats/fewsats-python/blob/main/nbs/00_core.ipynb Retrieves the current balance of the authenticated user's wallet. All amounts are returned in USD cents. This method makes a GET request to the `v0/wallets` endpoint. ```python r = fs.balance() r.status_code, r.json() ``` -------------------------------- ### Retrieve Payment Information in Fewsats Python Source: https://github.com/fewsats/fewsats-python/blob/main/nbs/00_core.ipynb Retrieves the detailed status and information for a specific outgoing payment using its purchase ID (`pid`). This method sends a GET request to the Fewsats API to fetch the payment details. ```python #| export @patch def payment_info(self:Fewsats, pid:str): # purchase id "Retrieve the details of a payment." return self._request("GET", f"v0/l402/outgoing-payments/{pid}") ``` ```python r = fs.payment_info(payment_response['id']) r.status_code, r.json() ``` -------------------------------- ### Initialize Fewsats Client and Fetch Account Details Source: https://github.com/fewsats/fewsats-python/blob/main/nbs/index.ipynb Demonstrates how to initialize the Fewsats client, optionally configuring it with an API key and a base URL for local development. It then retrieves and prints the user's payment methods, current balance, and personal account information. ```python fs = Fewsats() import os fs = Fewsats(api_key=os.getenv("FEWSATS_LOCAL_API_KEY"), base_url='http://localhost:8000') fs.payment_methods().json(), fs.balance().json(), fs.me().json() ``` -------------------------------- ### Initialize Fewsats Client and Fetch Account Details (Python) Source: https://github.com/fewsats/fewsats-python/blob/main/README.md Initializes the Fewsats client, optionally configuring it with an API key and base URL. It then retrieves and displays the user's registered payment methods, current balance, and personal profile information. ```Python from fewsats.core import * fs = Fewsats() import os fs = Fewsats(api_key=os.getenv("FEWSATS_LOCAL_API_KEY"), base_url='http://localhost:8000') fs.payment_methods().json(), fs.balance().json(), fs.me().json() ``` -------------------------------- ### AI Chat Assistant Using Fewsats Tools for User Info and Balance Source: https://github.com/fewsats/fewsats-python/blob/main/README.md This snippet initializes a 'Chat' object with an AI model, a system prompt, and Fewsats methods as tools. It then processes a user prompt using 'toolloop', demonstrating how the AI assistant can utilize the 'me' and 'balance' tools to fulfill the request and trace the interaction steps. ```python chat = Chat(model, sp='You are a helpful assistant that can pay offers.', tools=fs.as_tools()) pr = f"Can you check my details and balance?" r = chat.toolloop(pr, trace_func=print) r ``` -------------------------------- ### Python: Create Test Payable Offers Source: https://github.com/fewsats/fewsats-python/blob/main/nbs/00_core.ipynb This snippet shows how to programmatically create test offers using the Fewsats API. It defines a list of offer details, including amount, currency, description, and supported payment methods, then uses `fs.create_offers` to register them. ```python test_offers = [{ "id": "test_offer_2", "amount": 1, "currency": "usd" , "description": "Test offer", "title": "Test Package", "payment_methods": ["lightning", "credit_card"] }] l402_offers = fs.create_offers(test_offers).json() ``` -------------------------------- ### Python: AI Agent Pays Cheapest Offer Source: https://github.com/fewsats/fewsats-python/blob/main/nbs/00_core.ipynb This snippet demonstrates an AI agent (Claudette) interacting with Fewsats tools to pay an offer. It initializes a `Chat` agent with a model and Fewsats tools, then prompts the agent to pay the cheapest offer from a list, tracing the tool usage. ```python chat = Chat(model, sp='You are a helpful assistant that can pay offers.', tools=fs.as_tools()) pr = f"Could you pay the cheapest offer in {l402_offers}?" r = chat.toolloop(pr, trace_func=print) r ``` -------------------------------- ### Create Payment Offers with Fewsats Python SDK Source: https://github.com/fewsats/fewsats-python/blob/main/README.md This snippet demonstrates how to define and create payment offers using the Fewsats Python SDK. It shows the structure of the `offers_data` payload and the call to `fs.create_offers` to initiate payment offers. ```python offers_data = [{ "id": "offer_example", "amount": 1, "currency": "USD", "description": "Receive payment for your service", "title": "1 Credit Package", "payment_methods": ["lightning", "stripe"] }] r = fs.create_offers(offers_data) offers = r.json() offers ``` -------------------------------- ### Fewsats Client Class API Documentation Source: https://github.com/fewsats/fewsats-python/blob/main/nbs/00_core.ipynb Defines the `Fewsats` client class, which manages API authentication and provides a base method for making authenticated HTTP requests. It initializes with an API key and a base URL, setting up an `httpx` client for secure communication. This section also documents all core methods patched onto the `Fewsats` class. ```APIDOC Fewsats Class: Description: Client for interacting with the Fewsats API. Handles authentication and provides the foundation for API interactions. Imports: from fastcore.utils import * import os import hashlib import hmac import httpx import time import json from dataclasses import dataclass from fastcore.basics import BasicRepr from fastcore.utils import store_attr from typing import List, Dict, Any from functools import wraps Constants: WEBHOOK_VERSION: "v1" WEBHOOK_SIGNATURE_HEADER: "Fewsats-Signature" Methods: __init__(api_key: str = None, base_url: str = "https://api.fewsats.com"): Description: Initializes the Fewsats client. Parameters: api_key: The API key for the Fewsats account. Can be passed directly or set via FEWSATS_API_KEY environment variable. base_url: The Fewsats API base URL (defaults to "https://api.fewsats.com"). Raises: ValueError: If api_key is not provided. _request(method: str, path: str, timeout: int = 10, **kwargs) -> Dict[str, Any]: Description: Makes an authenticated request to the Fewsats API. Parameters: method: The HTTP method to use (e.g., "GET", "POST"). path: The API endpoint path (e.g., "v0/users/me"). timeout: Timeout for the request in seconds (default: 10). **kwargs: Additional keyword arguments passed to httpx.Client.request. Returns: Dict[str, Any]: The JSON response from the API. me() -> Response: Description: Retrieve the user's info. Endpoint: GET v0/users/me Returns: Response: The HTTP response object containing user information. billing_info() -> Response: Description: Retrieve the user's billing info. Endpoint: GET v0/users/me/billing-info Returns: Response: The HTTP response object containing billing information. balance() -> Response: Description: Retrieve the balance of the user's wallet. Amounts are always in USD cents. Endpoint: GET v0/wallets Returns: Response: The HTTP response object containing wallet balance. payment_methods() -> List[Dict[str, Any]]: Description: Retrieve the user's payment methods. Endpoint: GET v0/stripe/payment-methods Returns: List[Dict[str, Any]]: A list of dictionaries, each representing a payment method. _preview_payment(amount: str) -> Response: Description: Simulates a purchase to determine its outcome. Endpoint: POST v0/l402/preview/purchase/amount Parameters: amount: The amount in USD cents (e.g., "300" for $3.00). Returns: Response: The HTTP response object containing the purchase preview. create_offers(offers: List[Dict[str, Any]]) -> dict: Description: Create offers for L402 payment server. Endpoint: POST v0/l402/offers Parameters: offers: List of offer objects following OfferCreateV0 schema. Returns: dict: The JSON response containing the created offers. ``` -------------------------------- ### Python: Call Fewsats as Tools Source: https://github.com/fewsats/fewsats-python/blob/main/nbs/00_core.ipynb This snippet demonstrates calling the `as_tools` method on the Fewsats client instance to retrieve the list of available methods wrapped as AI agent tools. ```python fs.as_tools() ``` -------------------------------- ### AI Chat Interaction: Pay Cheapest Lightning Offer Source: https://github.com/fewsats/fewsats-python/blob/main/nbs/index.ipynb This code sets up an AI chat assistant capable of interacting with Fewsats tools. It then provides a prompt to the `toolloop` method, instructing the AI to find and pay the cheapest lightning offer, demonstrating automated payment processing via AI. ```python chat = Chat(model, sp='You are a helpful assistant that can pay offers.', tools=fs.as_tools()) pr = f"Could you pay the cheapest offer using lightning {l402_offer}?" r = chat.toolloop(pr, trace_func=print) r ``` -------------------------------- ### Create L402 Offers Source: https://github.com/fewsats/fewsats-python/blob/main/nbs/00_core.ipynb Creates new L402 offers for the payment server. This method accepts a list of offer objects, each conforming to the `OfferCreateV0` schema, and sends them as a POST request to the `v0/l402/offers` endpoint. ```python test_offers = [{ "id": "test_offer_2", "amount": 1, "currency": "usd" , "description": "Test offer", "title": "Test Package", "payment_methods": ["lightning", "credit_card"] }] r = fs.create_offers(test_offers) l402_offers = r.json() r.status_code, l402_offers ``` -------------------------------- ### Python: Import Claudette for Agent Demo Source: https://github.com/fewsats/fewsats-python/blob/main/nbs/00_core.ipynb This snippet imports necessary classes from the `claudette` library, specifically `Chat` and `models`, to set up an AI agent for demonstration purposes. ```python from claudette import Chat, models ``` -------------------------------- ### AI Chat Interaction: Check User Details and Balance Source: https://github.com/fewsats/fewsats-python/blob/main/nbs/index.ipynb This snippet initializes an AI chat assistant with a specific model and Fewsats tools. It then uses the `toolloop` method to process a user prompt asking to check details and balance, allowing the AI to use Fewsats tools to fulfill the request. ```python chat = Chat(model, sp='You are a helpful assistant that can pay offers.', tools=fs.as_tools()) pr = f"Can you check my details and balance?" r = chat.toolloop(pr, trace_func=print) r ``` -------------------------------- ### Preview a Purchase Source: https://github.com/fewsats/fewsats-python/blob/main/nbs/00_core.ipynb Simulates a purchase to determine its outcome, such as whether a credit card charge is required or if the purchase will be covered by the user's balance. The `amount` parameter should be provided in USD cents. ```python r = fs._preview_payment(amount="300") # 3.00 USD preview = r.json() r.status_code = preview ``` -------------------------------- ### AI Chat Assistant Using Fewsats Tools for Lightning Payment Source: https://github.com/fewsats/fewsats-python/blob/main/README.md This snippet re-initializes the 'Chat' object and demonstrates another AI interaction where the assistant is prompted to pay the cheapest offer using lightning. It showcases the AI's ability to interpret and act on payment-related requests using the integrated Fewsats tools. ```python chat = Chat(model, sp='You are a helpful assistant that can pay offers.', tools=fs.as_tools()) pr = f"Could you pay the cheapest offer using lightning {l402_offer}?" r = chat.toolloop(pr, trace_func=print) r ``` -------------------------------- ### List Available Fewsats API Tools Source: https://github.com/fewsats/fewsats-python/blob/main/README.md This snippet demonstrates using the 'as_tools()' method of the Fewsats object to obtain a list of methods that can be exposed as tools, typically for integration with AI models. The output shows a list of bound methods available for use. ```python fs.as_tools() ``` -------------------------------- ### Pay a Specific L402 Offer Source: https://github.com/fewsats/fewsats-python/blob/main/nbs/index.ipynb Shows how to use the `pay_offer` method to submit a payment for a specific L402 offer. It requires the offer's ID and the complete L402 offer object, with the backend handling the underlying payment flow. ```python fs.pay_offer(l402_offer['offers'][0]['id'], l402_offer).json() ``` -------------------------------- ### Python: Create Purchase from X402 Link Source: https://github.com/fewsats/fewsats-python/blob/main/nbs/00_core.ipynb This function facilitates creating a purchase from an external URL that requires X402 payment. It allows specifying the URL, HTTP method, optional body, headers, and blockchain chain. The function sends a POST request to the Fewsats API to handle the payment and resource access. ```python @patch def pay_x402_link(self:Fewsats, url:str, # URL to purchase from method:str = "GET", # HTTP method to use body:Dict[str, Any] = None, # Optional request body headers:Dict[str, str] = None, # Optional request headers chain:str = "base", # Blockchain chain to use ) -> dict: """Creates a purchase from an external URL that requires x402 payment. Args: url: The URL to purchase from method: HTTP method to use (default: "GET") body: Optional request body headers: Optional request headers chain: Blockchain chain to use (default: "base") Returns: The response from the target URL after successful payment """ data = { "url": url, "method": method, "chain": chain } if body is not None: data["body"] = body if headers is not None: data["headers"] = headers return self._request("POST", "v0/x402/purchases/from-link", json=data) ``` -------------------------------- ### Python: Expose Fewsats Methods as AI Agent Tools Source: https://github.com/fewsats/fewsats-python/blob/main/nbs/00_core.ipynb This set of functions prepares Fewsats client methods to be used as tools for AI agents. `get_response` extracts status code and text, `wrap_with_response` adapts methods to return this format, and `as_tools` compiles a list of wrapped Fewsats methods suitable for agent integration. ```python def get_response(r): return r.status_code, r.text def wrap_with_response(method): """Wraps a method to return (status_code, text) instead of a Response object""" @wraps(method) # This preserves name, docstring, signature def wrapped(*args, **kwargs): response = method(*args, **kwargs) return get_response(response) return wrapped @patch def as_tools(self:Fewsats): "Return list of available tools for AI agents" methods = [self.me, self.balance, self.payment_methods, self.pay_offer_str, self.payment_info] return [wrap_with_response(m) for m in methods] ``` -------------------------------- ### Import Fewsats Core Module Source: https://github.com/fewsats/fewsats-python/blob/main/nbs/index.ipynb Imports all classes and functions from the `fewsats.core` module. This is a prerequisite for initializing and interacting with the Fewsats library's functionalities. ```python from fewsats.core import * ``` -------------------------------- ### Define L402 Offer and L402Offers Data Models Source: https://github.com/fewsats/fewsats-python/blob/main/nbs/00_core.ipynb Defines the `Offer` and `L402Offers` Python classes, which represent the structured data for L402 offers. `Offer` models a single offer with ID, amount, currency, description, and title. `L402Offers` aggregates multiple `Offer` objects along with payment context and request URL. Both classes include `from_dict` methods for deserialization and `as_dict` for serialization (for `L402Offers`). ```python #| export class Offer(BasicRepr): "Represents a single L402 offer" def __init__(self, id: str, amount: int, currency: str, description: str, title: str, payment_methods: List[str] = None, type: str = "one-off"): store_attr() def __repr__(self): return f"Offer: {self.title}\nID: {self.id}\nAmount: {self.amount/100} {self.currency}\nDescription: {self.description}" @classmethod def from_dict(cls, d: Dict[str, Any]) -> 'Offer': "Create an Offer from a dictionary" return cls(**d) class L402Offers(BasicRepr): "Represents the complete L402 offers schema" def __init__(self, offers: List[Offer], payment_context_token: str, payment_request_url: str, version: str): store_attr() def __repr__(self): offers_str = "\n".join([f"- {o.title} ({o.amount/100} {o.currency})" for o in self.offers]) return f"L402 Offers:\n{offers_str}\nPayment URL: {self.payment_request_url}\nContext Token: {self.payment_context_token}" def as_dict(self) -> Dict[str, Any]: "Convert to dictionary format for API usage" return { 'offers': [vars(o) for o in self.offers], 'payment_context_token': self.payment_context_token, 'payment_request_url': self.payment_request_url, 'version': self.version } @classmethod def from_dict(cls, d: Dict[str, Any]) -> 'L402Offers': "Create an L402Offers object from a dictionary" offers = [Offer.from_dict(o) for o in d['offers']] return cls( offers=offers, payment_context_token=d['payment_context_token'], payment_request_url=d['payment_request_url'], version=d['version'] ) ``` -------------------------------- ### Expose Fewsats Functionality as AI Tools Source: https://github.com/fewsats/fewsats-python/blob/main/nbs/index.ipynb This snippet utilizes the `as_tools()` method from the Fewsats SDK. This method likely converts available Fewsats functionalities into a format consumable by AI models, enabling them to interact with the Fewsats service programmatically. ```python fs.as_tools() ``` -------------------------------- ### Python: Create Payment from X402 Offer Source: https://github.com/fewsats/fewsats-python/blob/main/nbs/00_core.ipynb This function creates a payment based on an X402 offer payload and returns a payment header. It requires the X402 offer details and the blockchain chain. The function makes a POST request to the Fewsats API to process the payment. ```python @patch def pay_x402_offer(self:Fewsats, payload:Dict[str, Any], # The x402 offer payload chain:str = "base", # Blockchain chain to use ) -> dict: """Creates a payment from an x402 offer and returns a payment header to access the resource. Args: payload: The x402 offer payload containing accepts, error, and x402Version chain: Blockchain chain to use (default: "base") Returns: Dictionary containing payment_header to use for subsequent requests """ data = { "chain": chain, "payload": payload } return self._request("POST", "v0/x402/purchases/from-offer", json=data) ``` -------------------------------- ### Pay a Lightning Invoice Directly Source: https://github.com/fewsats/fewsats-python/blob/main/nbs/index.ipynb Demonstrates how to directly pay a lightning invoice using the `pay_lightning` method. This method requires the invoice string, the expected amount, currency, and a description for accounting purposes, although the actual amount paid is determined by the invoice's sats. ```python fs.pay_lightning(invoice='lnbc100n1pn6fsyspp5g2f6hdqxc76wxccq2cd4wekck0nxfucfyvzkvy9fmxezlf3hcl6qdqqcqzpgxqyz5vqrzjqwghf7zxvfkxq5a6sr65g0gdkv768p83mhsnt0msszapamzx2qvuxqqqqz99gpz55yqqqqqqqqqqqqqq9qrzjq25carzepgd4vqsyn44jrk85ezrpju92xyrk9apw4cdjh6yrwt5jgqqqqz99gpz55yqqqqqqqqqqqqqq9qsp5yzvs9czquyf8mjgwf465k0a7g4vh7jqv2cpza3lkygnllxnzk2wq9qxpqysgqnkmhmw05q6qc8urah004jtnkuztpazgg49m3g2wfamexr0m0ayrhla2ephnsm0xan3pweqc3hexeqx2mkfr8d3afwx6rds2r2znf4vgq7new3k', amount=1, currency='USD', description='Purchase 1 cent for API access') ``` -------------------------------- ### Import Claudette for AI Agent Integration Source: https://github.com/fewsats/fewsats-python/blob/main/nbs/index.ipynb Imports the `Chat` and `models` components from the `claudette` library, which serves as a convenient wrapper for Claude. This import is a necessary step for integrating Fewsats payment capabilities with AI assistants built using Claudette. ```python from claudette import Chat, models ``` -------------------------------- ### Check Payment Status of an Offer Source: https://github.com/fewsats/fewsats-python/blob/main/nbs/index.ipynb Shows how to retrieve the payment status of a previously created offer using its `payment_context_token`. This allows you to programmatically verify if an offer has been successfully paid. ```python fs.get_payment_status(payment_context_token=offers["payment_context_token"]).json() ``` -------------------------------- ### Import Claudette for AI Agent Payment Integration Source: https://github.com/fewsats/fewsats-python/blob/main/README.md This snippet shows the necessary Python imports from the `claudette` library, specifically `Chat` and `models`, which are used to enable AI assistants like Claude to handle payment interactions. ```python from claudette import Chat, models ``` -------------------------------- ### Configure Anthropic Logging and Select Model Source: https://github.com/fewsats/fewsats-python/blob/main/nbs/index.ipynb This snippet shows how to enable debug logging for Anthropic API calls by setting an environment variable. It also demonstrates selecting a specific model from a list, likely for use with a chat or AI interaction. ```python # os.environ['ANTHROPIC_LOG'] = 'debug' model = models[1]; model ``` -------------------------------- ### Submit Payment for an L402 Offer (Python) Source: https://github.com/fewsats/fewsats-python/blob/main/README.md Uses the Fewsats client's `pay_offer` method to submit a payment for a specific L402 offer. The backend handles the entire L402 flow, including selecting the most convenient payment method and processing the transaction. ```Python fs.pay_offer(l402_offer['offers'][0]['id'], l402_offer).json() ``` -------------------------------- ### Configure Debug Logging for Anthropic API and Select Model Source: https://github.com/fewsats/fewsats-python/blob/main/README.md This snippet demonstrates how to enable full HTTP request and response logging for Anthropic API interactions by setting the 'ANTHROPIC_LOG' environment variable to 'debug'. It also shows how to select and display a specific model from a predefined list. ```python # os.environ['ANTHROPIC_LOG'] = 'debug' model = models[1]; model ``` -------------------------------- ### Pay a Lightning Invoice Directly (Python) Source: https://github.com/fewsats/fewsats-python/blob/main/README.md Demonstrates how to directly pay a Lightning Network invoice using Fewsats. Although the invoice contains the payment amount, the method requires specifying the expected amount in cents for internal accounting and convenience. ```Python fs.pay_lightning(invoice='lnbc100n1pn6fsyspp5g2f6hdqxc76wxccq2cd4wekck0nxfucfyvzkvy9fmxezlf3hcl6qdqqcqzpgxqyz5vqrzjqwghf7zxvfkxq5a6sr65g0gdkv768p83mhsnt0msszapamzx2qvuxqqqqz99gpz55yqqqqqqqqqqqqqq9qrzjq25carzepgd4vqsyn44jrk85ezrpju92xyrk9apw4cdjh6yrwt5jgqqqqz99gpz55yqqqqqqqqqqqqqq9qsp5yzvs9czquyf8mjgwf465k0a7g4vh7jqv2cpza3lkygnllxnzk2wq9qxpqysgqnkmhmw05q6qc8urah004jtnkuztpazgg49m3g2wfamexr0m0ayrhla2ephnsm0xan3pweqc3hexeqx2mkfr8d3afwx6rds2r2znf4vgq7new3k', amount=1, currency='USD', description='Purchase 1 cent for API access') ``` -------------------------------- ### Pay L402 Offer using Fewsats Python Source: https://github.com/fewsats/fewsats-python/blob/main/nbs/00_core.ipynb Pays an offer identified by `offer_id` using a structured `L402Offers` object. This method handles the conversion of the `L402Offers` object to a dictionary and sends a POST request to the Fewsats API to complete the purchase. It returns the payment status response. ```python #| export @patch def pay_offer(self:Fewsats, offer_id : str, # the offer id to pay for l402_offer: L402Offers, # a dictionary containing L402 offers ) -> dict: # payment status response """Pays an offer_id from the l402_offers. The l402_offer parameter must be a dictionary with this structure: { 'offers': [ { 'id': 'test_offer_2', # String identifier for the offer 'amount': 1, # USD cents 'currency': 'usd', # Currency code 'description': 'Test offer', # Text description 'title': 'Test Package' # Title of the package } ], 'payment_context_token': 'token', # Payment context token 'payment_request_url': 'https://api.fewsats.com/v0/l402/payment-request', # Payment URL 'version': '0.2.2' # API version } Returns payment status response""" if isinstance(l402_offer, dict): l402_offer = L402Offers.from_dict(l402_offer) offer_dict = l402_offer.as_dict() data = {"offer_id": offer_id, **offer_dict} return self._request("POST", "v0/l402/purchases/from-offer", json=data) ``` ```python offer_id = l402.offers[0].id r = fs.pay_offer(offer_id, l402) payment_response = r.json() r.status_code, payment_response ``` -------------------------------- ### Retrieve Fewsats Account Balance with Detailed Output Source: https://github.com/fewsats/fewsats-python/blob/main/README.md This snippet re-demonstrates calling the 'balance()' method on the 'fs' object, showing a more detailed JSON response that includes the account ID, current balance, and currency. This illustrates the typical structured output for balance inquiries. ```python fs.balance() ``` -------------------------------- ### Add a Webhook for Payment Notifications Source: https://github.com/fewsats/fewsats-python/blob/main/nbs/index.ipynb Demonstrates how to register a webhook URL with Fewsats. The specified URL will be called automatically whenever a payment is made for an offer, enabling real-time notifications for your application. ```python r = fs.add_webhook(webhook_url="https://example.com/webhook") r.json() ``` -------------------------------- ### Python: Define Fewsats get_payment_details Method Source: https://github.com/fewsats/fewsats-python/blob/main/nbs/00_core.ipynb This Fewsats method allows buyers to retrieve comprehensive payment information, including Stripe checkout URLs and Lightning invoices. It requires a payment request URL, offer ID, desired payment method, and a payment context token as inputs, returning a dictionary of payment details. ```python #| export @patch def get_payment_details(self:Fewsats, payment_request_url:str, # The payment request URL offer_id:str, # The offer ID payment_method:str, # The payment method (lightning, credit_card, ...) payment_context_token:str, # The payment context token ) -> dict: """Gets payment details for a specific offer. Use this as buyer when you want to make the payment manually.""" data = {"offer_id": offer_id, "payment_method": payment_method, "payment_context_token": payment_context_token} return httpx.post(payment_request_url, json=data) ``` -------------------------------- ### Pay External Link using Fewsats Python Source: https://github.com/fewsats/fewsats-python/blob/main/nbs/00_core.ipynb Creates a purchase record for an external URL. This method allows specifying the URL, a description, the price in USD cents, the payment method (defaulting to 'credit_card'), and a title for the purchase. It constructs the payload and sends a POST request to the Fewsats API. ```python #| export @patch def pay_link(self:Fewsats, url: str, # URL to purchase from description: str, # Description of the purchase price: int, # Price in USD cents payment_method: str = "credit_card", # Payment method (credit_card, lightning, etc.) title: str = "Purchase from URL" # Title of the purchase ) -> dict: # payment status response """Creates a purchase record for an external URL. Args: url: The URL to purchase from description: Description of the purchase price: Price in USD cents payment_method: Payment method to use (default: credit_card) title: Title of the purchase (default: "Purchase from URL") Returns: Payment status response containing information about the purchase """ data = { "url": url, "description": description, "price": price, "payment_method": payment_method, "title": title } return self._request("POST", "v0/l402/purchases/from-link", json=data) ``` ```python url = "https://www.amazon.com/Matter-Culture-Iain-M-Banks/dp/0316005371" r = fs.pay_link(url, "Matter (Culture)", 629) r.status_code, r.text ``` -------------------------------- ### Fetch Fewsats User Details as JSON Source: https://github.com/fewsats/fewsats-python/blob/main/nbs/index.ipynb This code retrieves the current user's details from the Fewsats service using the `me()` method. The `.json()` call then parses the response into a JSON object, making the user information easily accessible. ```python fs.me().json() ``` -------------------------------- ### Python: Define Fewsats add_webhook Method Source: https://github.com/fewsats/fewsats-python/blob/main/nbs/00_core.ipynb This Fewsats method allows vendors to register a URL for receiving real-time notifications upon successful payments. It supports only one webhook URL per user, which will be triggered for every completed payment associated with their offers. ```python #| export @patch def add_webhook(self:Fewsats, webhook_url:str, ) -> dict: """Add a URL to the list of webhooks that will receive notifications when you receive a payment. The webhook will be triggered for every successful payment.""" return self._request("POST", f"v0/users/webhook/add", json={"webhook_url": webhook_url}) ``` -------------------------------- ### Import OS Module for Environment Variables Source: https://github.com/fewsats/fewsats-python/blob/main/README.md This snippet shows the import of the `os` module in Python. This module is commonly used to access environment variables, such as `ANTHROPIC_API_KEY`, which is required for authenticating with AI services like Anthropic's Claude. ```python import os ``` -------------------------------- ### Check Payment Status of Fewsats Offer Source: https://github.com/fewsats/fewsats-python/blob/main/README.md This snippet illustrates how to retrieve the current payment status of a previously created offer. It uses the `payment_context_token` obtained from the offer creation response to query `fs.get_payment_status`. ```python fs.get_payment_status(payment_context_token=offers["payment_context_token"]).json() ``` -------------------------------- ### Import OS Module Source: https://github.com/fewsats/fewsats-python/blob/main/nbs/index.ipynb Imports the standard `os` module, which provides a way of using operating system dependent functionality. It is commonly used for tasks such as accessing environment variables, which might be necessary for configuring API keys or other sensitive information. ```python import os ``` -------------------------------- ### Define Fewsats pay_lightning Method Source: https://github.com/fewsats/fewsats-python/blob/main/nbs/00_core.ipynb Defines the `pay_lightning` method within the Fewsats class, allowing direct payment of a lightning invoice. It takes the invoice string, amount in cents, currency, and an optional description. This method makes a POST request to the `v0/l402/purchases/lightning` endpoint. ```python #| export @patch def pay_lightning(self: Fewsats, invoice: str, # lightning invoice amount: int, # amount in cents currency: str = "usd", # currency description: str = "" ): # description of the payment "Pay for a lightning invoice directly." data = { "invoice": invoice, "amount": amount, "currency": currency, "description": description } return self._request("POST", "v0/l402/purchases/lightning", json=data) ```