如何通过Notion API(curl)为指定用户授予页面权限?
如何通过Notion API(PHP curl)为特定用户授予页面权限
可以通过Notion API为特定用户授予页面权限,你的代码存在几个关键问题导致未生效,下面是修正方案:
问题分析
- 接口路径与请求方法错误:添加页面权限需要用
PATCH请求调用/v1/pages/{page_id}接口,而非POST到/permissions子路径 - 参数格式错误:权限配置需要嵌套在
permissions数组中,且用户标识不能直接用邮箱,必须使用Notion用户ID(需先通过API获取) - 旧版本API:你的
Notion-Version是2021-05-13,部分权限接口逻辑已更新,建议使用2022-06-28及以上版本
修正后的实现步骤与代码
- 先获取目标用户的Notion ID
需要调用搜索用户接口匹配邮箱,拿到用户的Notion内部ID:
private function getNotionUserId($userEmail) { $url = 'https://api.notion.com/v1/users/search'; $headers = [ 'Authorization: Bearer NOTION_TOKEN', 'Content-Type: application/json', 'Notion-Version: 2022-06-28' ]; $data = ['query' => $userEmail]; $ch = curl_init($url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data)); $response = json_decode(curl_exec($ch), true); curl_close($ch); // 返回第一个匹配的用户ID(确保邮箱唯一) return $response['results'][0]['id'] ?? null; }
- 授予页面权限的修正代码
使用PATCH请求,正确构造权限参数结构:
private function grantFullAccessToUser($userEmail, $pageId) { // 先获取用户ID $userId = $this->getNotionUserId($userEmail); if (!$userId) { echo '找不到对应用户:' . $userEmail; return; } $url = 'https://api.notion.com/v1/pages/' . $pageId; $headers = [ 'Authorization: Bearer NOTION_TOKEN', 'Content-Type: application/json', 'Notion-Version: 2022-06-28' ]; // 正确的权限参数结构 $data = [ 'permissions' => [ [ 'type' => 'user', 'user' => ['id' => $userId], 'role' => 'editor' ] ] ]; $ch = curl_init($url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PATCH'); // 使用PATCH方法 curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data)); $response = json_decode(curl_exec($ch), true); curl_close($ch); // 根据响应判断是否成功 if (isset($response['id']) && $response['id'] === $pageId) { echo '已成功为用户 ' . $userEmail . ' 授予页面编辑权限'; } else { echo '权限授予失败:' . ($response['message'] ?? '未知错误'); } }
注意事项
- 确保你的Notion集成token拥有页面的管理权限(即token所属用户是页面的所有者或有编辑+权限管理权限)
- 目标用户必须属于当前Notion工作空间,否则无法添加权限
- 可以根据需求修改
role字段,可选值:reader、commenter、editor
内容的提问来源于stack exchange,提问作者aadish ajay
相关产品推荐
相关产品推荐

