Auto Post In Linkedin

August 13, 2024 | 2 minutes read


Ashish Dwivedi

blog-image
Automate Linkedin Post
Automate Linkedin Post

function uploadImageToLinkedIn() {
  const accessToken = 'AQVvMMoM5WFOoTXgW3Snm06gUtyPhg6fLXB-2i8mF3FMMYilIEx7X_hkSSx6RRUiznbe2rp0mB0NvxyDxT3XmoAtGfopvgpDDaLRXToalMDy88VmnnLCWjVJ2o9ZTQ6gs1-9fjRB-wBb00uQGJStA1lCu7AsturstZW8OBKQk1MyeZRUrHuv6xUefMvutue-lq5aDi0kOyiBaiEo44NXcX9GAHJZaKc8z6yZ_SixrAfFgFSFhdLvjoBa0srijUDcYKPUtfA8OK5cHGczX9RimjZssIQuwqvJTIEBnqS9-slccp-07dK87gsCAmr0dYMIdkjUazX-9OowIx1MOKeZwpYxcGZIrw';
 // Replace with your LinkedIn access token
  const uploadUrl = 'https://api.linkedin.com/v2/Aassets?action=registerUpload';


  // Payload to register the upload
  const payload = {
    "registerUploadRequest": {
      "recipes": ["urn:li:digitalmediaRecipe:feedshare-image"],
      "owner": "urn:li:person:y6F3vFE2Fb", // Replace with your LinkedIn profile ID
      "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(uploadUrl, options);
  const responseData = JSON.parse(response.getContentText());
  Logger.log(responseData);


  const uploadUrlFromResponse = responseData.value.uploadMechanism['com.linkedin.digitalmedia.uploading.MediaUploadHttpRequest'].uploadUrl;
  const asset = responseData.value.asset;


  Logger.log('Upload URL: ' + uploadUrlFromResponse);
  Logger.log('Asset: ' + asset);


  // Call the function to upload the image to the provided URL
  uploadImage(uploadUrlFromResponse, asset, accessToken);
}


function uploadImage(uploadUrlFromResponse, asset, accessToken) {
  const imageUrl = 'https://images.freeimages.com/images/large-previews/3ff/chain-link-fence-1187948.jpg'; // Replace with the URL of the image you want 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(uploadUrlFromResponse, options);
  Logger.log(response.getContentText());


  // After uploading the image, post the image to LinkedIn
  postImageToLinkedIn(asset, accessToken);
}


function postImageToLinkedIn(asset, accessToken) {
  const uploadUrl = 'https://api.linkedin.com/v2/ugcPosts';


  const payload = {
    'author': 'urn:li:person:y6F3vFE2Fb', // Replace with your LinkedIn profile ID
    '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(uploadUrl, options);
  Logger.log(response.getContentText());
}