/**
* Main function to register, upload, and post an image to LinkedIn
*/
function uploadImageToLinkedIn() {
const accessToken = 'YOUR_ACCESS_TOKEN_HERE'; // Replace with your LinkedIn access token
const profileId = 'urn:li:person:YOUR_PROFILE_ID'; // Replace with your LinkedIn profile ID
// Step 1: Register the upload
const registerUploadUrl = 'https://api.linkedin.com/v2/assets?action=registerUpload';
const payload = {
registerUploadRequest: {
recipes: ["urn:li:digitalmediaRecipe:feedshare-image"],
owner: profileId,
serviceRelationships: [
{ relationshipType: "OWNER", identifier: "urn:li:userGeneratedContent" }
]
}
};
const options = {
method: 'post',
headers: {
Authorization: 'Bearer ' + accessToken,
'Content-Type': 'application/json',
'X-Restli-Protocol-Version': '2.0.0'
},
payload: JSON.stringify(payload)
};
const response = UrlFetchApp.fetch(registerUploadUrl, options);
const responseData = JSON.parse(response.getContentText());
const uploadUrlFromResponse = responseData.value.uploadMechanism['com.linkedin.digitalmedia.uploading.MediaUploadHttpRequest'].uploadUrl;
const asset = responseData.value.asset;
Logger.log('Upload URL: ' + uploadUrlFromResponse);
Logger.log('Asset URN: ' + asset);
// Step 2: Upload the image to LinkedIn
uploadImageToLinkedInEndpoint(uploadUrlFromResponse, asset, accessToken, profileId);
}
/**
* Upload the image file to LinkedIn using the registered upload URL
*/
function uploadImageToLinkedInEndpoint(uploadUrl, asset, accessToken, profileId) {
const imageUrl = 'https://images.freeimages.com/images/large-previews/3ff/chain-link-fence-1187948.jpg'; // Image to upload
const imageBlob = UrlFetchApp.fetch(imageUrl).getBlob();
const options = {
method: 'put',
headers: {
Authorization: 'Bearer ' + accessToken,
'Content-Type': imageBlob.getContentType()
},
payload: imageBlob
};
const response = UrlFetchApp.fetch(uploadUrl, options);
Logger.log('Upload response: ' + response.getContentText());
// Step 3: Post the uploaded image to LinkedIn feed
postImageToLinkedIn(asset, accessToken, profileId);
}
/**
* Create a LinkedIn post using the uploaded image
*/
function postImageToLinkedIn(asset, accessToken, profileId) {
const postUrl = 'https://api.linkedin.com/v2/ugcPosts';
const payload = {
author: profileId,
lifecycleState: 'PUBLISHED',
specificContent: {
'com.linkedin.ugc.ShareContent': {
shareCommentary: { text: 'Hello Rajnish' },
shareMediaCategory: 'IMAGE',
media: [{
status: 'READY',
description: { text: 'Description of the image' },
media: asset,
title: { text: 'Title of the image' }
}]
}
},
visibility: { 'com.linkedin.ugc.MemberNetworkVisibility': 'PUBLIC' }
};
const options = {
method: 'post',
headers: {
Authorization: 'Bearer ' + accessToken,
'Content-Type': 'application/json',
'X-Restli-Protocol-Version': '2.0.0'
},
payload: JSON.stringify(payload)
};
const response = UrlFetchApp.fetch(postUrl, options);
Logger.log('Post response: ' + response.getContentText());
}
📋 Copy Code