使用Next.js调用LinkedIn API自动发帖遇422错误求排查
Next.js自动发布LinkedIn帖子返回422 Unprocessable Entity的排查方案
问题背景
我用Next.js搭建了Web应用,想实现发布新内容时自动同步到自己的LinkedIn主页。已经创建了LinkedIn App,拿到了Client ID和Client Secret,但找到的资料都是针对代其他用户发帖的OAuth场景,不符合我给自己主页发帖的需求。按照方案写了调用代码后,接口返回422 Unprocessable Entity。
调用代码
const linkedinPost = await fetch(`https://api.linkedin.com/v2/ugcPosts`, { method: "post", headers: { "Authorization": `Bearer ${process.env.NEXT_PUBLIC_LINKEDIN_ACCESS_TOKEN_DRJ_2}`, "Content-Type": "application/json" }, body: JSON.stringify({ "author": "urn:li:person:8675309", "lifecycleState": "PUBLISHED", "specificContent": { "com.linkedin.ugc.ShareContent": { "shareCommentary": { "text": "This text is to be posted", }, "shareMediaCategory": "NONE" } }, "visibility": { "com.linkedin.ugc.MemberNetworkVisibility": "PUBLIC" } }) });
响应日志
Response { [Symbol(realm)]: null, [Symbol(state)]: { aborted: false, rangeRequested: false, timingAllowPassed: true, requestIncludesCredentials: true, type: 'default', status: 422, timingInfo: { startTime: 492846.5113720894, redirectStartTime: 0, redirectEndTime: 0, postRedirectStartTime: 492846.5113720894, finalServiceWorkerStartTime: 0, finalNetworkResponseStartTime: 0, finalNetworkRequestStartTime: 0, endTime: 0, encodedBodySize: 0, decodedBodySize: 0, finalConnectionTimingInfo: null }, cacheState: '', statusText: 'Unprocessable Entity', headersList: HeadersList { cookies: [Array], [Symbol(headers map)]: [Map], [Symbol(headers map sorted)]: null }, urlList: [ URL {} ], body: { stream: undefined } }, [Symbol(headers)]: HeadersList { cookies: [ 'bcookie="v=2&07f3a4fc-656e-4486-8277-7f8de8a53e92"; domain=.linkedin.com; Path=/; Secure; Expires=Thu, 05-Dec-2024 10:13:09 GMT; SameSite=None', 'lidc="b=OB72:s=O:r=O:a=O:p=O:g=3281:u=14:x=1:i=1701857588:t=1701859352:v=2:sig=AQFr_d1F9snHikizALVmxzSowEosPeV0"' ], [Symbol(headers map)]: Map(14) { 'x-li-responseorigin' => [Object], 'content-type' => [Object], 'x-linkedin-error-response' => [Object], 'x-restli-gateway-error' => [Object], 'x-restli-protocol-version' => [Object], 'content-length' => [Object], 'date' => [Object], 'connection' => [Object], 'x-li-fabric' => [Object], 'x-li-pop' => [Object], 'x-li-proto' => [Object], 'x-li-uuid' => [Object], 'set-cookie' => [Object], 'x-li-route-key' => [Object] }, [Symbol(headers map sorted)]: null } }
可能的原因及解决方法
1. 请求体存在语法错误
代码中shareCommentary.text字段末尾多了一个逗号:"text": "This text is to be posted",,严格的JSON解析会识别为语法错误,导致接口无法处理请求。去掉该逗号即可。
2. 缺少必要的请求头
LinkedIn UGC Posts API要求必须携带X-Restli-Protocol-Version头,值为2.0.0,否则会返回格式错误。在headers中添加该字段。
3. Access Token权限不足
发布内容到自己主页需要w_member_social权限,若获取token时未申请该权限,接口会拒绝请求。需重新生成包含该权限的access token。
4. Author URN错误
author字段的urn:li:person:8675309是示例ID,需替换为你自己的LinkedIn用户ID。可以通过LinkedIn的用户信息接口获取自己的正确ID。
5. Access Token暴露风险(额外提示)
不要用NEXT_PUBLIC_开头的环境变量存储access token,这类变量会暴露在客户端代码中,导致token泄露。应将接口调用放在Next.js的API路由中,使用普通环境变量存储敏感信息。
修改后的示例代码
const linkedinPost = await fetch(`https://api.linkedin.com/v2/ugcPosts`, { method: "post", headers: { "Authorization": `Bearer ${process.env.LINKEDIN_ACCESS_TOKEN}`, "Content-Type": "application/json", "X-Restli-Protocol-Version": "2.0.0" }, body: JSON.stringify({ "author": "urn:li:person:你的真实用户ID", "lifecycleState": "PUBLISHED", "specificContent": { "com.linkedin.ugc.ShareContent": { "shareCommentary": { "text": "This text is to be posted" }, "shareMediaCategory": "NONE" } }, "visibility": { "com.linkedin.ugc.MemberNetworkVisibility": "PUBLIC" } }) }); // 建议添加响应解析,查看具体错误信息 const responseData = await linkedinPost.json(); console.log(responseData);
内容的提问来源于stack exchange,提问作者26ph19
相关产品推荐
相关产品推荐

