---
title: 获取访问凭证
description: 使用应用 ID 和 Secret 获取并缓存开放平台访问令牌。
sidebar_label: 获取访问凭证
sidebar_position: 1
---

# 获取访问凭证

业务接口调用前，先通过 OAuth2 client credentials 流程换取访问令牌。令牌应缓存到过期前，不要为每个请求重复申请。

## 请求

```http runtimeOauthTokenEndpoint
POST /oauth2/v2.0/token HTTP/1.1
Host: alimail-cn.aliyuncs.com
Content-Type: application/x-www-form-urlencoded

grant_type=client_credentials&client_id=<client_id>&client_secret=<client_secret>
```

## Python 示例

```python runtimeOauthTokenEndpoint
import os
import time
import requests

TOKEN_URL = "https://alimail-cn.aliyuncs.com/oauth2/v2.0/token"


def get_access_token() -> tuple[str, float]:
    response = requests.post(
        TOKEN_URL,
        data={
            "grant_type": "client_credentials",
            "client_id": os.environ["ALIMAIL_CLIENT_ID"],
            "client_secret": os.environ["ALIMAIL_CLIENT_SECRET"],
        },
        timeout=10,
    )
    response.raise_for_status()
    payload = response.json()
    expires_at = time.time() + int(payload["expires_in"])
    return payload["access_token"], expires_at
```

## 使用建议

- 将 `client_id` 和 `client_secret` 放在密钥管理服务或运行时 Secret 中。
- 在 `expires_at` 前预留刷新窗口，例如提前 5 分钟获取新令牌。
- 多实例服务使用共享缓存和互斥刷新，避免令牌过期时并发申请。
- 不要打印完整响应，响应中包含访问令牌。

参考：[原始示例](https://help.aliyun.com/zh/document_detail/2855420.html)、[API 开放平台概览](/api/alibaba-mail-api)。
