
本文详解如何正确调用 Microsoft Graph API 的 driveItem: invite 接口分享 OneDrive 或 SharePoint 文档,重点解决因请求体结构错误(如 recipients 类型不匹配、roles 格式非法)导致的 400 Bad Request 错误。
本文详解如何正确调用 microsoft graph api 的 `driveitem: invite` 接口分享 onedrive 或 sharepoint 文档,重点解决因请求体结构错误(如 `recipients` 类型不匹配、`roles` 格式非法)导致的 400 bad request 错误。
在使用 Microsoft Graph API 实现文档协作共享时,/driveItem/invite 是核心接口之一。但开发者常因请求体(request body)结构不符合 REST 规范而收到如下典型错误:
{
"error": {
"code": "BadRequest",
"message": "The request is malformed or incorrect. Expected array for value of property: Collection(microsoft.graph.driveRecipient)"
}
}该错误明确指出:recipients 字段必须为 driveRecipient 对象数组(即 Collection
✅ 正确请求体结构要点
| 字段 | 类型 | 要求 | 示例 |
|---|---|---|---|
| recipients | array of objects | 必须是数组,每个元素含 email(或 objectId)字段 | [{"email": "user@contoso.com"}] |
| roles | string[] | 必须是字符串数组,仅支持 "read" 或 "write" | ["read"] 或 ["write"] |
| requireSignIn | boolean | 控制是否强制登录访问 | true |
| sendInvitation | boolean | 是否发送邮件邀请 | true |
| message | string | 邀请邮件正文(可选) | "Here is the file." |
? Laravel 中的修复示例(PHP SDK)
以下为修正后的 Laravel 控制器方法,关键修改已加注释:
public function send()
{
$graphs = $this->getGraph();
$body = [
'requireSignIn' => true,
'sendInvitation' => true,
'roles' => ['read'], // ✅ 修正1:必须是数组,非字符串
'recipients' => [ // ✅ 修正2:外层数组包裹 recipient 对象
['email' => 'user@contoso.com'] // ✅ 每个 recipient 是独立数组元素
],
'message' => 'Here is the file.'
];
try {
$response = $graphs->createRequest('POST', '/me/drive/root:/operations.xlsx:/invite')
->attachBody($body)
->execute();
return response()->json([
'success' => true,
'data' => $response->getBody()
]);
} catch (\Microsoft\Graph\Exception\GraphException $e) {
return response()->json([
'success' => false,
'error' => $e->getMessage(),
'code' => $e->getCode()
], 400);
}
}⚠️ 注意事项与最佳实践
- 路径安全性:/me/drive/root:/operations.xlsx:/invite 中的文件路径需确保存在且当前用户有权限访问;若文件在 SharePoint 站点中,请改用 /sites/{site-id}/drives/{drive-id}/items/{item-id}/invite。
- 权限要求:应用需至少拥有 Files.ReadWrite(个人 OneDrive)或 Sites.ReadWrite.All(SharePoint)委托权限,并在 Azure AD 中完成管理员同意。
- 邮箱格式:recipients[].email 必须为已验证的 Microsoft 365 或 Azure AD 用户邮箱;外部邮箱需开启外部共享策略。
-
批量邀请:如需邀请多人,直接扩展 recipients 数组即可:
'recipients' => [ ['email' => 'user1@contoso.com'], ['email' => 'user2@contoso.com'], ['email' => 'user3@contoso.com'] ] - 无邮件邀请场景:若仅需生成可共享链接(不发邮件),设 "sendInvitation": false 并配合 "requireSignIn": true 即可获得受保护的登录后访问链接。
✅ 验证成功响应
成功调用后,API 将返回 200 OK 及包含共享链接与权限信息的 JSON 响应,例如:
{
"value": [
{
"id": "xyz...",
"roles": ["read"],
"invitation": {
"email": "user@contoso.com",
"signInRequired": true
},
"shareId": "s!Ap...",
"link": {
"type": "view",
"scope": "organization",
"webUrl": "https://contoso-my.sharepoint.com/:x:/r/personal/.../operations.xlsx?e=..."
}
}
]
}掌握请求体的严格类型约束,是调用 Graph API 的关键门槛。务必以数组形式传递 recipients 和 roles,并确保 SDK 层未对 payload 进行意外序列化干扰——这是规避 400 BadRequest 最高效的方式。










