
Overview
AP2 (Agent Payments Protocol) is a protocol for agent payments that supports both human-present and human-absent commerce flows. This tutorial provides detailed instructions on how to use the AP2 Python sample project.
Project Structure
samples/python/
├── src/ap2/ # AP2 core code
├── scenarios/ # Usage scenario examples
│ └── a2a/human-present/ # Human-present payment scenarios
│ ├── cards/ # Card payment examples
│ └── x402/ # x402 payment examples
├── pyproject.toml # Project configuration
└── README.md # Project documentation
Environment Requirements
- Python 3.10+
uv
package manager- Google API Key (for AI functionality)
Installation Steps
1. Install uv Package Manager
If you haven't installed uv
yet, please visit the uv installation guide for installation instructions.
2. Clone Project and Install Dependencies
# Clone the project
git clone https://github.com/google-agentic-commerce/AP2.git
# Navigate to project directory
cd AP2/samples/python
# Install dependencies
uv sync
3. Configure Google API Key
Obtain an API key from Google AI Studio, then choose one of the following configuration methods:
Environment Variable
export GOOGLE_API_KEY=your_api_key_here
Core Concepts
1. Key Actors
- Shopping Agent: Main coordinator that handles user shopping requests and delegates to specialized agents
- Merchant Agent: Handles product queries from shopping agents
- Merchant Payment Processor Agent: Processes payments on behalf of merchants
- Credentials Provider Agent: Manages user payment credentials
2. Core Data Structures
- IntentMandate: Intent authorization containing purchase intent information
- CartMandate: Shopping cart authorization signed by merchant to ensure quote accuracy
- PaymentMandate: Payment authorization containing transaction information and user signature
Usage Scenarios
Scenario 1: Human-Present Card Payment
This is the most common payment scenario where the user is present to confirm purchase details and payment method.
Step-by-Step Launch
If you want to run each service in different terminals:
- Start Merchant Agent
# AP2/samples/python
uv run --package ap2-samples python -m roles.merchant_agent
- Start Credentials Provider
# AP2/samples/python
uv run --package ap2-samples python -m roles.credentials_provider_agent
- Start Merchant Payment Processor Agent
# AP2/samples/python
uv run --package ap2-samples python -m roles.merchant_payment_processor_agent
- Start Shopping Agent
# AP2/samples/python
uv run --package ap2-samples adk web src/roles
Interaction Flow
- Access Interface: Open browser and visit
http://0.0.0.0:8000/dev-ui
- Select Agent: Choose
shopping_agent
from the dropdown menu - Initiate Request: Input purchase intent, such as "I want to buy a coffee machine"
- Product Search: Shopping agent delegates to merchant agent to find matching products
- Create Cart: Merchant agent creates CartMandate and shares with shopping agent
- Select Product: Choose from displayed products
- Link Credentials Provider: Connect to your preferred credentials provider
- Select Payment Method: Choose from available payment methods
- Create Payment Authorization: Shopping agent creates PaymentMandate and requests signature
- OTP Verification: Enter simulated OTP
123
- Complete Purchase: Receive confirmation message and digital receipt
Scenario 2: x402 Payment
Supports x402-compatible payment methods (full AP2-compatible version coming soon).
Launch method is similar to card payment scenario, but uses x402-related scripts and configurations.
Advanced Features
1. Verbose Mode
To understand the internal workings of agents, you can enable verbose mode:
I want to buy a new pair of shoes. Please stay in verbose mode throughout the process, explaining what you're doing and showing all data payloads.
Verbose mode will display:
- Detailed explanations of current and next steps
- JSON representations of all data payloads
- Mandate objects being created, sent, or received
2. Agent Communication Logs
The system automatically creates detailed log files watch.log
in the .logs
directory.
Logs contain three categories of data:
Category | Content |
---|---|
Raw HTTP Data | HTTP methods, URLs, JSON request bodies and response bodies |
A2A Message Data | Request instructions extracted from A2A message TextPart and data in DataParts |
AP2 Protocol Data | Mandate objects identified in message DataParts |
Code Architecture
1. Message Builder
The A2aMessageBuilder
class is used to build A2A messages:
builder = A2aMessageBuilder()
message = builder.add_text("Hello").add_data("key", data).build()
2. Base Server Executor
BaseServerExecutor
provides basic functionality for agents:
- Handle requests and responses
- Manage extensions
- Tool parsing and execution
3. Payment Validation
The system includes payment mandate validation logic to ensure transaction security:
def validate_payment_mandate_signature(payment_mandate: PaymentMandate) -> None:
if payment_mandate.user_authorization is None:
raise ValueError("User authorization not found in PaymentMandate.")
4. Credentials Provider Agent Code Explanation
This agent acts as a "digital wallet," responsible for storing/retrieving user payment methods and shipping addresses, and generating and validating "payment credential tokens" during the payment process. Core code is located in samples/python/src/roles/credentials_provider_agent/
:
-
Entry point:
__main__.py
- Loads local
agent.json
description as agent_card. - Starts service on port
8002
with RPC path/a2a/credentials_provider
. - Creates
CredentialsProviderExecutor
and passes in supported extensions list.
- Loads local
-
Executor:
agent_executor.py
CredentialsProviderExecutor
inherits fromBaseServerExecutor
, constrained by system prompt to "only output tool calls, no casual chat with users."- Registered tools include:
handle_get_shipping_address
handle_search_payment_methods
handle_create_payment_credential_token
handle_signed_payment_mandate
handle_get_payment_method_raw_credentials
-
Tool set:
tools.py
- Common data keys:
- Shipping address key:
CONTACT_ADDRESS_DATA_KEY
- Payment mandate key:
PAYMENT_MANDATE_DATA_KEY
- Merchant-acceptable payment methods data key:
PAYMENT_METHOD_DATA_DATA_KEY
- Shipping address key:
- Key processing functions:
handle_get_shipping_address
- Input:
user_email
- Action: Query corresponding shipping address from account manager, output to
CONTACT_ADDRESS_DATA_KEY
.
- Input:
handle_search_payment_methods
- Input:
user_email
and a set ofPaymentMethodData
(merchant-acceptable conditions like card networks). - Action: Call internal matching logic (
_payment_method_is_eligible
) to filter user account payment methods that meet merchant conditions, return{"payment_method_aliases": [...]}
.
- Input:
handle_create_payment_credential_token
- Input:
user_email
,payment_method_alias
. - Action: Generate one-time "payment credential token" for selected payment method, return format like
{"token": "fake_payment_credential_token_x"}
.
- Input:
handle_signed_payment_mandate
- Input:
PaymentMandate
(containingpayment_mandate_id
andtoken
in payment details). - Action: Bind signed
payment_mandate_id
to previously generatedtoken
for subsequent verification.
- Input:
handle_get_payment_method_raw_credentials
- Input:
PaymentMandate
(containingpayment_mandate_id
andtoken
). - Action: Verify consistency of
token
andpayment_mandate_id
, return underlying raw payment credentials (e.g., card network, DPAN/encrypted data) for payment processor to complete charge.
- Input:
- Common data keys:
-
Account and token management:
account_manager.py
- In-memory database simulating multiple accounts, examples include:
- User's
shipping_address
- Multiple
payment_methods
(such asCARD
,BANK_ACCOUNT
,DIGITAL_WALLET
), cards contain network and billing address, etc.
- User's
- Token lifecycle:
create_token(email, alias)
: Generate and save token (mapping email and payment method alias).update_token(token, payment_mandate_id)
: Bind signedpayment_mandate_id
to token (write once only).verify_token(token, payment_mandate_id)
: Verify if token matches authorization ID, return "raw credentials" of that payment method.
- Account query capabilities:
get_account_shipping_address(email)
get_account_payment_methods(email)
get_payment_method_by_alias(email, alias)
- In-memory database simulating multiple accounts, examples include:
-
Agent capability declaration:
agent.json
capabilities.extensions
declares support for AP2 extensions and sample card network extensions.skills
describe external capabilities (such as "query available payment methods", "get shipping address").
Typical Interaction Sequence (Summary)
- Shopping agent provides merchant-acceptable
PaymentMethodData
anduser_email
, callssearch_payment_methods
to get availablepayment_method_aliases
. - Select a
payment_method_alias
, callcreate_payment_credential_token
to gettoken
. - Shopping agent generates
PaymentMandate
and requests user signature, after signature completion returns it, credentials provider usessigned_payment_mandate
to bindpayment_mandate_id
totoken
. - Merchant payment processor agent calls
get_payment_method_raw_credentials
before completing payment, usingtoken + payment_mandate_id
to verify and exchange for underlying raw payment credentials.
Note: The above data key constants are defined in the ap2.types
module; tools output DataPart
artifacts through TaskUpdater
for upstream agents to continue orchestration.
Extension Development
1. Creating New Payment Methods
To support new payment methods, you need to:
- Declare extension support in
agent.json
- Implement corresponding processing logic
- Update validation rules
2. Adding New Agent Roles
Creating new agents requires:
- Inherit from
BaseServerExecutor
- Implement necessary tool functions
- Configure agent description file
Troubleshooting
Common Issues
-
Google API Key Error
- Ensure API Key is correctly set
- Check if API Key is valid
-
Port Conflicts
- Ensure required ports (8000-8003) are not occupied
- You can modify port settings in configuration files
-
Dependency Installation Failure
- Ensure Python version >= 3.10
- Try clearing cache:
uv cache clean
Debugging Tips
- Check
watch.log
file to understand detailed communication process - Use verbose mode to get more debugging information
- Check console output of each service
Best Practices
- Security: Always validate payment mandate signatures
- Error Handling: Implement comprehensive error handling mechanisms
- Logging: Record key operations for debugging and auditing
- Testing: Thoroughly test all payment flows before production
Summary
AP2 provides a powerful and flexible agent payment protocol framework. Through this tutorial, you should be able to:
- Understand AP2's core concepts and architecture
- Successfully run the sample project
- Develop custom payment agents
- Handle common issues and troubleshooting
For more detailed information, please refer to the specific code implementations and comments in the project.