身份验证
为自己的账户使用 API 密钥。要代表他人的账户发布,请注册 OAuth 应用。
API 密钥
将密钥作为 Bearer 令牌发送:Authorization: Bearer pst_live_...。正式密钥作用于真实账户,测试密钥(pst_test_...)是沙盒环境。
密钥带有 scope,超出 scope 的请求会返回 403。密钥还可以限制 IP 地址并设置有效期。轮换密钥后,旧密钥会在短时间内继续可用。
Scope
| Scope | 权限 |
|---|---|
channels:read | 列出已连接的渠道 |
posts:read | 读取帖子,并接收 post.* webhook 事件 |
posts:write | 创建、修改、删除、定时和发布帖子 |
media:write | 为帖子附加媒体 |
analytics:read | 读取发布和受众分析数据 |
webhooks:manage | 管理 webhook 端点 |
面向应用的 OAuth
在控制台注册应用。用户批准你请求的 scope 后,你会获得其账户的令牌。元数据位于 https://pub.postia.app/.well-known/oauth-authorization-server。
- 将用户跳转到
https://pub.postia.app/oauth/authorize,并携带response_type=code、client_id、redirect_uri、scope(以空格分隔)、state,以及 PKCE 的code_challenge与code_challenge_method=S256。 - 在
POST /oauth/token用grant_type=authorization_code、code、redirect_uri和code_verifier兑换授权码。私有应用还需发送其 client secret。 - 使用访问令牌(
pst_at_...)作为 Bearer 令牌调用 API。令牌有效期为一小时。 - 使用
grant_type=refresh_token刷新。刷新令牌(pst_rt_...)每次使用后都会被替换。通过POST /oauth/revoke撤销。
import { createHash, randomBytes } from "node:crypto";
const verifier = randomBytes(32).toString("base64url");
const challenge = createHash("sha256").update(verifier).digest("base64url");
const url = new URL("https://pub.postia.app/oauth/authorize");
url.search = new URLSearchParams({
response_type: "code",
client_id: CLIENT_ID,
redirect_uri: REDIRECT_URI,
scope: "channels:read posts:write",
state: randomBytes(16).toString("hex"),
code_challenge: challenge,
code_challenge_method: "S256",
});
// Send the user to url, keep verifier with their session.
curl -X POST https://pub.postia.app/oauth/token \
-d grant_type=authorization_code \
-d code=CODE_FROM_THE_REDIRECT \
-d redirect_uri=REDIRECT_URI \
-d client_id=CLIENT_ID \
-d code_verifier=VERIFIER
重定向 URI 必须完全匹配:使用 https,或在 localhost 上使用 http。公开应用需经审核后其他人才能连接;在此之前只有其所有者可以连接。