Scroll to Top
💻
Free Code
Users get ready-to-use code at no cost.
📋
Easy Copy
Copy and use the code instantly.
Quick Learning
Understand concepts fast and clearly.
📝
Step-by-Step
Follow simple instructions to implement.
📅 August 6, 2024 💻 Tutorial ⭐ Beginner Friendly

Auto Post In Linkedin

Author Avatar

Ashish Dwivedi

Editorial Team • Tech Writer

About This Tutorial

Automate LinkedIn posting using Google Apps Script by connecting your Google Sheets to LinkedIn’s API. Create a script to schedule and post updates, articles, or media directly to your LinkedIn profile or company page. This automation streamlines content sharing, saving time and ensuring consistent engagement with your audience.
  1. Step 1: Click on the Copy button to copy the code snippet.
  2. Step 2: Paste the copied code into your project’s script editor.

Apps Scripts Blog

Read Blog

📂 javascript
⚡ script1.js
⚡ script1.js
/**
 * 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());
}