Agent Payments Protocol (AP2)
AP2是一个开源协议,定义了AI代理之间进行安全支付交互的标准。该项目提供了完整的代码示例和演示,支持多种支付场景和编程语言。
功能特性
- 多语言支持: 提供Python、Go和Android三种语言的完整实现示例
- 多种支付方式: 支持卡支付、数字支付凭证(DPC)、x402等多种支付方式
- 安全授权机制: 实现完整的授权流程,包括IntentMandate、CartMandate和PaymentMandate
- OTP挑战机制: 集成一次性密码验证,增强支付安全性
- 模块化架构: 采用清晰的职责分离,包含购物代理、商户代理、凭证提供者代理和支付处理器代理
- 协议扩展性: 支持AP2协议扩展,便于定制化开发
安装指南
前置要求
- Python 3.10或更高版本
uv包管理器- Go 1.21或更高版本(用于Go示例)
- Android Studio(用于Android示例)
环境配置
选项1: Google API密钥(推荐用于开发)
- 从Google AI Studio获取API密钥
- 设置环境变量:
export GOOGLE_API_KEY='your_key'
选项2: Vertex AI(推荐用于生产)
- 配置环境变量:
export GOOGLE_GENAI_USE_VERTEXAI=true
export GOOGLE_CLOUD_PROJECT='your-project-id'
export GOOGLE_CLOUD_LOCATION='global'
- 身份验证:
gcloud auth application-default login
安装AP2类型包
uv pip install git+https://github.com/google-agentic-commerce/AP2.git@main
使用说明
运行场景示例
- 导航到项目根目录:
cd AP2
- 运行场景脚本:
bash samples/python/scenarios/your-scenario-name/run.sh
- 访问购物代理URL开始交互
Android示例运行
bash samples/android/scenarios/digital-payment-credentials/run.sh
Go示例运行
cd samples/go/scenarios/a2a/human-present/cards
bash run.sh
核心代码
Go语言商户代理实现
// Copyright 2025 Google LLC
package main
import (
"log"
"github.com/google-agentic-commerce/ap2/samples/go/pkg/common"
"github.com/google-agentic-commerce/ap2/samples/go/pkg/roles/merchant_agent"
)
const (
MerchantAgentPort = 8001
RPCURL = "/a2a/merchant_agent"
)
func main() {
// 加载代理卡片配置
agentCard, err := common.LoadAgentCard("pkg/roles/merchant_agent")
if err != nil {
log.Fatalf("Failed to load agent card: %v", err)
}
// 创建商户代理执行器
executor := merchant_agent.NewMerchantAgentExecutor(agentCard.Capabilities.Extensions)
// 启动代理服务器
server := common.NewAgentServer(MerchantAgentPort, agentCard, executor, RPCURL)
if err := server.Start(); err != nil {
log.Fatalf("Server error: %v", err)
}
}
Python凭证提供者代理
# Copyright 2025 Google LLC
"""An A2A Agent Executor for the credentials provider agent."""
from typing import Any
from . import tools
from common.base_server_executor import BaseServerExecutor
from common.system_utils import DEBUG_MODE_INSTRUCTIONS
class CredentialsProviderExecutor(BaseServerExecutor):
"""AgentExecutor for the credentials provider agent."""
_system_prompt = """
You are a credentials provider agent acting as a secure digital wallet.
Your job is to manage a user's payment methods and shipping addresses.
Based on the user's request, identify their intent and select the
single correct tool to use. Your only output should be a tool call.
Do not engage in conversation.
%s
""" % DEBUG_MODE_INSTRUCTIONS
def __init__(self, supported_extensions: list[dict[str, Any]] = None):
"""Initializes the CredentialsProviderExecutor."""
agent_tools = [
tools.handle_create_payment_credential_token,
tools.handle_get_payment_method_raw_credentials,
tools.handle_get_shipping_address,
tools.handle_search_payment_methods,
tools.handle_signed_payment_mandate,
tools.handle_payment_receipt,
]
super().__init__(supported_extensions, agent_tools, self._system_prompt)
AP2协议类型定义
# Copyright 2025 Google LLC
"""Contains the definitions of the Agent Payments Protocol mandates."""
from datetime import datetime
from datetime import timezone
from typing import Optional
from pydantic import BaseModel, Field
class IntentMandate(BaseModel):
"""Represents the user's purchase intent."""
user_cart_confirmation_required: bool = Field(
True,
description="If false, the agent can make purchases on the user's behalf"
)
natural_language_description: str = Field(
...,
description="The natural language description of the user's intent"
)
merchants: list[str] = Field(default_factory=list)
skus: list[str] = Field(default_factory=list)
requires_refundability: bool = Field(False)
intent_expiry: str = Field(
default_factory=lambda: (
datetime.now(timezone.utc).replace(hour=0, minute=0, second=0, microsecond=0) +
timedelta(days=1)
).isoformat()
)
支付请求数据结构
// Copyright 2025 Google LLC
package types
type PaymentCurrencyAmount struct {
Currency string `json:"currency"`
Value float64 `json:"value"`
}
type PaymentItem struct {
Label string `json:"label"`
Amount PaymentCurrencyAmount `json:"amount"`
Pending *bool `json:"pending,omitempty"`
RefundPeriod int `json:"refund_period,omitempty"`
}
type PaymentRequest struct {
MethodData []PaymentMethodData `json:"method_data"`
Details PaymentDetailsInit `json:"details"`
Options *PaymentOptions `json:"options,omitempty"`
ShippingAddress *ContactAddress `json:"shipping_address,omitempty"`
}
这些核心代码展示了AP2协议的关键组件,包括代理实现、协议类型定义和支付数据结构,为开发者提供了构建兼容AP2协议的支付代理的坚实基础。