A2A Protocol

AP2 (Agent Payments Protocol) Usage Tutorial

MILO
Share
AP2 (Agent Payments Protocol) Usage Tutorial

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:

  1. Start Merchant Agent
# AP2/samples/python
uv run --package ap2-samples python -m roles.merchant_agent
  1. Start Credentials Provider
# AP2/samples/python
uv run --package ap2-samples python -m roles.credentials_provider_agent
  1. Start Merchant Payment Processor Agent
# AP2/samples/python
uv run --package ap2-samples python -m roles.merchant_payment_processor_agent
  1. Start Shopping Agent
# AP2/samples/python
uv run --package ap2-samples adk web src/roles

Interaction Flow

  1. Access Interface: Open browser and visit http://0.0.0.0:8000/dev-ui
  2. Select Agent: Choose shopping_agent from the dropdown menu
  3. Initiate Request: Input purchase intent, such as "I want to buy a coffee machine"
  4. Product Search: Shopping agent delegates to merchant agent to find matching products
  5. Create Cart: Merchant agent creates CartMandate and shares with shopping agent
  6. Select Product: Choose from displayed products
  7. Link Credentials Provider: Connect to your preferred credentials provider
  8. Select Payment Method: Choose from available payment methods
  9. Create Payment Authorization: Shopping agent creates PaymentMandate and requests signature
  10. OTP Verification: Enter simulated OTP 123
  11. 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.
  • Executor: agent_executor.py

    • CredentialsProviderExecutor inherits from BaseServerExecutor, 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
    • Key processing functions:
      • handle_get_shipping_address
        • Input: user_email
        • Action: Query corresponding shipping address from account manager, output to CONTACT_ADDRESS_DATA_KEY.
      • handle_search_payment_methods
        • Input: user_email and a set of PaymentMethodData (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": [...]}.
      • 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"}.
      • handle_signed_payment_mandate
        • Input: PaymentMandate (containing payment_mandate_id and token in payment details).
        • Action: Bind signed payment_mandate_id to previously generated token for subsequent verification.
      • handle_get_payment_method_raw_credentials
        • Input: PaymentMandate (containing payment_mandate_id and token).
        • Action: Verify consistency of token and payment_mandate_id, return underlying raw payment credentials (e.g., card network, DPAN/encrypted data) for payment processor to complete charge.
  • Account and token management: account_manager.py

    • In-memory database simulating multiple accounts, examples include:
      • User's shipping_address
      • Multiple payment_methods (such as CARD, BANK_ACCOUNT, DIGITAL_WALLET), cards contain network and billing address, etc.
    • Token lifecycle:
      • create_token(email, alias): Generate and save token (mapping email and payment method alias).
      • update_token(token, payment_mandate_id): Bind signed payment_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)
  • 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)

  1. Shopping agent provides merchant-acceptable PaymentMethodData and user_email, calls search_payment_methods to get available payment_method_aliases.
  2. Select a payment_method_alias, call create_payment_credential_token to get token.
  3. Shopping agent generates PaymentMandate and requests user signature, after signature completion returns it, credentials provider uses signed_payment_mandate to bind payment_mandate_id to token.
  4. Merchant payment processor agent calls get_payment_method_raw_credentials before completing payment, using token + 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:

  1. Declare extension support in agent.json
  2. Implement corresponding processing logic
  3. Update validation rules

2. Adding New Agent Roles

Creating new agents requires:

  1. Inherit from BaseServerExecutor
  2. Implement necessary tool functions
  3. Configure agent description file

Troubleshooting

Common Issues

  1. Google API Key Error

    • Ensure API Key is correctly set
    • Check if API Key is valid
  2. Port Conflicts

    • Ensure required ports (8000-8003) are not occupied
    • You can modify port settings in configuration files
  3. Dependency Installation Failure

    • Ensure Python version >= 3.10
    • Try clearing cache: uv cache clean

Debugging Tips

  1. Check watch.log file to understand detailed communication process
  2. Use verbose mode to get more debugging information
  3. Check console output of each service

Best Practices

  1. Security: Always validate payment mandate signatures
  2. Error Handling: Implement comprehensive error handling mechanisms
  3. Logging: Record key operations for debugging and auditing
  4. 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.

AP2 (Agent Payments Protocol) Usage Tutorial