agenticlypay
v0.8.0
Published
Node.js/TypeScript library for processing agentic payments (ACP, AP2, x402) via Stripe with automated Square-managed payouts
Maintainers
Readme
AgenticlyPay
A Node.js/TypeScript library for processing agentic payments (ACP, AP2, x402) via Stripe. Built for agentic developers who need automated payment processing, monthly Square-managed payouts, and tax compliance.
What's New in 0.8.0
- Security: Removed insecure email query parameter authentication (use API tokens or headers)
- Security: Enhanced input validation for amounts, account IDs, and currencies
- Security: Improved error handling - no internal error details exposed to clients
- Reliability: Custom exception system with structured error responses
- Performance: Request ID middleware for better tracing and debugging
- Code Quality: Comprehensive input validators and improved error messages
- Features: Automatic retrieval of all connected accounts for bulk payout processing
⚠️ Breaking Changes in 0.8.0
Email Query Parameters Removed: For security reasons, email authentication via query parameters (?email=...) has been removed.
Migration:
- Use API tokens (recommended):
new AgenticlyPay({ apiKey: 'agt_...' }) - Or use
X-Developer-Emailheader (deprecated but still supported) - Email in request body still works for backward compatibility
Input Validation: The API now validates:
- Amounts must be positive and ≤ $1,000,000
- Account IDs must match Stripe format (
acct_*) - Currency codes must be valid ISO 4217 codes
What's New in 0.7.0
- Security: Improved CORS configuration with explicit allowed origins
- Security: Added server-side rate limiting to prevent API abuse
- Performance: O(1) API token verification (previously O(n) - much faster at scale)
- Reliability: Enhanced health checks with dependency verification
- Code Quality: Improved error handling and structured logging on the backend
Features
- Multi-Protocol Support: Process payments using ACP (Agentic Commerce Protocol), AP2 (Agent Payments Protocol), or x402 protocols
- Square Payout Integration: Seamless onboarding for developer payout profiles backed by Square
- Automated Square Payouts: Monthly automated payouts via Square to your connected bank details
- Tax Compliance: Automatic 1099 form generation and filing
- Transparent Pricing: 6.5% + $0.30 per transaction (Stripe fees included - no additional charges)
- Flexible Authentication: Use your email address or API tokens for authentication
- TypeScript Support: Full TypeScript definitions included
- Dual Module Support: Works with both CommonJS and ES modules
Requirements to Use AgenticlyPay
- Use or register a Square business account: https://app.squareup.com/signup/
- Use the AgenticlyPay package with the same email address used in Square.
- Check usage on https://agenticlypay.com/console
Installation
npm install agenticlypayOr with yarn:
yarn add agenticlypayQuick Start
Authentication
AgenticlyPay supports two authentication methods:
- Email-based (simplest): Pass your email address with each request
- API Token (recommended for production): Create tokens in the Developer Console and use them instead
API tokens provide better security and isolation between projects. When using an API token, you don't need to pass the email parameter to methods.
Basic Usage with Email
import { AgenticlyPay } from 'agenticlypay';
// Initialize the client with email-based auth
const client = new AgenticlyPay({
baseUrl: 'https://api.agenticlypay.com' // Optional, defaults to production
});
// Create a developer account
const account = await client.createAccount({
email: '[email protected]',
country: 'US'
});
// Process a payment (AUTO protocol)
// IMPORTANT: Include your email for usage tracking
const payment = await client.processPayment({
protocol: 'AUTO',
amount: 10000, // $100.00 in cents
developer_account_id: account.account.account_id,
email: '[email protected]',
currency: 'usd',
description: 'Payment for service'
// Include `mandate` for AP2 or `resource_url` for x402
});Basic Usage with API Token
import { AgenticlyPay } from 'agenticlypay';
// Initialize the client with API token (recommended for production)
// Get your token from https://agenticlypay.com/console
const client = new AgenticlyPay({
baseUrl: 'https://api.agenticlypay.com',
apiKey: 'agt_your_token_here'
});
// Create a developer account (email still needed for account creation)
const account = await client.createAccount({
email: '[email protected]',
country: 'US'
});
// Process a payment (no email parameter needed with API token)
const payment = await client.processPayment({
protocol: 'AUTO',
amount: 10000, // $100.00 in cents
developer_account_id: account.account.account_id,
currency: 'usd',
description: 'Payment for service'
});Note: When using an API token, the email parameter is optional for most methods. The API token automatically associates requests with your account.
TypeScript Usage
The package includes full TypeScript definitions:
import { AgenticlyPay, ProcessPaymentRequest, ProcessPaymentResponse } from 'agenticlypay';
const client = new AgenticlyPay();
const request: ProcessPaymentRequest = {
protocol: 'AUTO',
amount: 10000,
developer_account_id: 'acct_xxxxx',
currency: 'usd'
};
const response: ProcessPaymentResponse = await client.processPayment(request);CommonJS Usage
const { AgenticlyPay } = require('agenticlypay');
const client = new AgenticlyPay();
// Use async/await or promises
client.processPayment({
protocol: 'AUTO',
amount: 10000,
developer_account_id: 'acct_xxxxx',
email: '[email protected]',
currency: 'usd'
}).then(response => {
console.log('Payment processed:', response);
});API Examples
Create Developer Account
const account = await client.createAccount({
email: '[email protected]',
country: 'US',
metadata: { // Optional
company: 'My Company'
}
});
console.log('Account ID:', account.account.account_id);Complete Onboarding
const onboarding = await client.createOnboardingLink({
account_id: 'acct_xxxxx',
refresh_url: 'https://yourapp.com/reauth',
return_url: 'https://yourapp.com/success'
});
// Redirect user to onboarding.url
console.log('Onboarding URL:', onboarding.onboarding_link.url);Process Payment (Unified AUTO)
// AUTO protocol - automatically selects ACP, AP2, or x402 based on parameters
const payment = await client.processPayment({
protocol: 'AUTO',
amount: 10000, // $100.00 in cents
developer_account_id: 'acct_xxxxx',
email: '[email protected]',
currency: 'usd',
description: 'Payment for service'
// For AP2, include mandate:
// mandate: {
// agent_id: 'agent_123',
// user_id: 'user_456',
// permissions: ['create_payment'],
// expires_at: 1735689600,
// mandate_id: 'mand_789'
// }
// For x402, include resource_url:
// resource_url: '/api/data/endpoint'
});Confirm Payment
const confirmation = await client.confirmPayment({
protocol: 'AUTO',
payment_id: 'pi_xxxxx',
payment_method: 'pm_xxxxx' // Optional
});
console.log('Payment status:', confirmation.status);Check Payment Status
const status = await client.getPaymentStatus('AUTO', 'pi_xxxxx');
console.log('Status:', status.status);
console.log('Amount:', status.amount / 100, status.currency);API Token Management
Create and manage API tokens in the Developer Console:
- Sign in to the console
- Navigate to the "API Tokens" tab
- Click "Create Token" and give it a descriptive name
- Copy the token immediately - it's only shown once
- Use the token in your code:
new AgenticlyPay({ apiKey: 'agt_...' })
Tokens can be revoked at any time from the console. When using an API token, you don't need to pass the email parameter to most methods.
MCP Server Configuration
For MCP (Model Context Protocol) server integrations, use these environment variables:
# Required
AGENTICLYPAY_DEVELOPER_ACCOUNT_ID=acct_xxxxx
[email protected]
AGENTICLYPAY_BASE_URL=https://api.agenticlypay.com
# Optional - use API token instead of email
AGENTICLYPAY_API_KEY=agt_your_token_here
# AP2 service configuration (if using AP2 protocol)
AP2_SERVICE_URL=https://ap2-service.your-domain.com
AP2_SERVICE_API_KEY=super-secret
# Stripe configuration (for AP2 service)
STRIPE_SECRET_KEY=sk_live_...Note: If AGENTICLYPAY_API_KEY is set, it takes precedence over AGENTICLYPAY_EMAIL for authentication.
Monthly Square Payouts
Monthly payouts are automatically sent via Square to the bank account associated with your developer account. Square handles transfer scheduling automatically once your balance is ready.
Get Monthly Earnings
const earnings = await client.getMonthlyEarnings('acct_xxxxx', 2024, 11);
console.log('Gross:', earnings.earnings.gross_amount / 100);
console.log('Fees:', earnings.earnings.fee_amount / 100);
console.log('Net:', earnings.earnings.net_amount / 100);Get Annual Earnings (for Tax Reporting)
const annualEarnings = await client.getAnnualEarnings('acct_xxxxx', 2024);
console.log('Annual gross:', annualEarnings.earnings.gross_amount / 100);
console.log('Annual fees:', annualEarnings.earnings.fee_amount / 100);
console.log('Annual net:', annualEarnings.earnings.net_amount / 100);Calculate Fee
const feeInfo = await client.getFee(10000); // $100.00
console.log('Amount:', feeInfo.amount / 100);
console.log('Fee:', feeInfo.fee / 100);
console.log('Net:', feeInfo.net_amount / 100);Error Handling
The library throws AgenticlyPayError for API errors with structured error information:
import { AgenticlyPay, AgenticlyPayError } from 'agenticlypay';
try {
const payment = await client.processPayment({...});
} catch (error) {
if (error instanceof AgenticlyPayError) {
console.error('API Error:', error.message);
console.error('Status Code:', error.statusCode);
console.error('Response:', error.response);
// Error responses include structured error codes
// error.response.error.code - Error code (e.g., "VALIDATION_ERROR")
// error.response.error.message - Human-readable message
// error.response.error.details - Additional error details
} else {
console.error('Unexpected error:', error);
}
}Error Types
- VALIDATION_ERROR: Invalid input (amount, account_id, currency, etc.)
- AUTHENTICATION_ERROR: Missing or invalid authentication
- PAYMENT_ERROR: Payment processing failures
- NOT_FOUND: Resource not found
All errors include structured error codes and messages for easier handling.
API Reference
AgenticlyPay Class
Constructor
new AgenticlyPay(config?: {
baseUrl?: string;
apiKey?: string; // Optional API token for authentication
})Methods
createAccount(request: CreateAccountRequest): Promise<CreateAccountResponse>getAccount(accountId: string): Promise<GetAccountResponse>createOnboardingLink(request: CreateOnboardingLinkRequest): Promise<CreateOnboardingLinkResponse>processPayment(request: ProcessPaymentRequest): Promise<ProcessPaymentResponse>confirmPayment(request: ConfirmPaymentRequest): Promise<ConfirmPaymentResponse>getPaymentStatus(protocol: Protocol, paymentId: string): Promise<GetPaymentStatusResponse>getFee(amount: number): Promise<GetFeeResponse>getMonthlyEarnings(accountId: string, year: number, month: number): Promise<GetMonthlyEarningsResponse>getAnnualEarnings(accountId: string, year: number): Promise<GetAnnualEarningsResponse>
Protocol Selection (AUTO)
The AUTO protocol automatically selects the appropriate payment protocol:
- ACP: Default when no special parameters are provided
- AP2: Selected when a
mandateobject is included - x402: Selected when a
resource_urlis included
// ACP (default)
await client.processPayment({
protocol: 'AUTO',
amount: 10000,
developer_account_id: 'acct_xxxxx',
email: '[email protected]'
});
// AP2 (with mandate)
await client.processPayment({
protocol: 'AUTO',
amount: 10000,
developer_account_id: 'acct_xxxxx',
email: '[email protected]',
mandate: { agent_id: 'agent_123', ... }
});
// x402 (with resource_url)
await client.processPayment({
protocol: 'AUTO',
amount: 10000,
developer_account_id: 'acct_xxxxx',
email: '[email protected]',
resource_url: '/api/data/endpoint'
});Requirements
- Node.js >= 16.0.0
- TypeScript >= 4.0 (optional, for TypeScript projects)
License
All rights reserved. AgenticlyPay for Node.js is proprietary—contact [email protected] for licensing terms.
Support
For issues and questions contact [email protected].
Related
- Python Package - Python library for AgenticlyPay
