如何通过PHP调用LinkedIn API在个人主页发布带图片的帖子?
使用PHP调用LinkedIn API发布带图片的个人主页帖子
核心流程说明
发布带图片的LinkedIn帖子需要分三步完成:
- 先向LinkedIn注册图片上传,获取专属上传地址和媒体资产URN
- 将本地图片文件上传到指定地址
- 构造包含该媒体资产的帖子数据并发布
具体实现代码
1. 注册图片上传并获取上传凭证
// 注册上传的接口地址 $register_url = "https://api.linkedin.com/v2/assets?action=registerUpload"; $register_headers = [ "Authorization: Bearer $access_token", "Content-Type: application/json", ]; // 构造注册上传的请求数据 $register_data = [ "registerUploadRequest" => [ "owner" => "urn:li:person:$person_urn", "recipes" => ["urn:li:digitalmediaRecipe:feedshare-image"], "serviceRelationships" => [ [ "relationshipType" => "OWNER", "identifier" => "urn:li:userGeneratedContent" ] ], "supportedUploadMechanism" => ["SYNCHRONOUS_UPLOAD"] ] ]; // 发送注册请求(假设你的publishPost函数支持POST请求) $register_response = json_decode(publishPost($register_url, json_encode($register_data), $register_headers), true); $upload_url = $register_response["value"]["uploadMechanism"]["com.linkedin.digitalmedia.uploading.MediaUploadHttpRequest"]["uploadUrl"]; $asset_urn = $register_response["value"]["asset"];
2. 上传图片到指定地址
// 读取本地图片文件 $image_path = "/path/to/your/image.jpg"; // 替换为实际图片路径 $image_content = file_get_contents($image_path); // 设置上传请求头 $upload_headers = [ "Authorization: Bearer $access_token", "Content-Type: image/jpeg", // 图片类型需匹配实际文件,如image/png ]; // 使用PUT方法上传图片(若你的publishPost不支持PUT,可改用cURL实现) $upload_context = stream_context_create([ "http" => [ "method" => "PUT", "header" => implode("\r\n", $upload_headers), "content" => $image_content ] ]); $upload_response = file_get_contents($upload_url, false, $upload_context);
3. 构造并发布带图片的帖子
$post_url = "https://api.linkedin.com/v2/ugcPosts"; $post_headers = [ "Authorization: Bearer $access_token", "Content-Type: application/json", ]; $post_data = [ "author" => "urn:li:person:$person_urn", "lifecycleState" => "PUBLISHED", "specificContent" => [ "com.linkedin.ugc.ShareContent" => [ "shareCommentary" => [ "text" => "带图片的帖子内容...", // 替换为你的帖子文案 ], "shareMediaCategory" => "IMAGE", "media" => [ [ "status" => "READY", "description" => [ "text" => "图片描述文字" // 可选:图片的描述内容 ], "media" => $asset_urn, "title" => [ "text" => "图片标题" // 可选:图片的标题 ] ] ] ], ], "visibility" => [ "com.linkedin.ugc.MemberNetworkVisibility" => "PUBLIC", ], ]; $post_response = publishPost($post_url, json_encode($post_data), $post_headers);
注意事项
- 确保你的access token拥有
w_member_social权限,这是发布带媒体内容帖子的必要权限 - 图片格式支持JPEG、PNG,文件大小不超过5MB,分辨率建议1200x628及以上(适配LinkedIn feed最佳展示比例)
- 若现有
publishPost函数仅支持POST请求,需修改函数逻辑以支持PUT请求(推荐使用cURL实现更灵活的HTTP请求处理)
内容的提问来源于stack exchange,提问作者MSS LLP
相关产品推荐
相关产品推荐

