Instagram api at the minimum

image

It all started with the fact that I wanted to make a channel on instagram spending all day searching and testing auto publishing services, then I decided to look at ready-made github packages, I was surprised at the code size of these packages (some php frameworks are smaller than these wrappers over instagram), I spat and decided to write my wrapper with minimal features.

Login


We will pass authorization through the WEB version. To do this, we will need from the beginning to get headers, cookies.

/**  GET    https://www.instagram.com**/
 $curl = curl_init();
 curl_setopt_array($curl, [
        CURLOPT_URL => 'https://www.instagram.com/',
        CURLOPT_HEADER => true,
        CURLOPT_SSL_VERIFYHOST => false,
        CURLOPT_SSL_VERIFYPEER => false,
        CURLOPT_RETURNTRANSFER => true,
        CURLINFO_HEADER_OUT => true,
        CURLOPT_HTTPHEADER => ['user-agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) 
        AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 Safari/537.36'],
 ]);
 $response = curl_exec($curl);
 $headers  = curl_getinfo($curl);
 /**    headers **/
 $header_content = substr($response, 0, $headers['header_size']);
 curl_close($curl);
/**
    csrftoken</b>,     header x-csrftoken    . 

 :
**/
$cookie = [];
preg_match_all("/Set-Cookie:\s*(?<cookie>[^=]+=[^;]+)/mi", $header_content, $matches);
foreach ($matches['cookie'] as $c) {
            if ($c = str_replace(['sessionid=""', 'target=""'], '', $c)) {
                $c = explode('=', $c);
                $cookie = array_merge($cookie, [trim($c[0]) => trim($c[1])]);
            }
        }
if (isset($cookie['csrftoken']) {
/**
      csrftoken
     IP     .
**/
}

Further I will not give examples of the work of CURL.

Authorization:

/**  POST   https://www.instagram.com/accounts/login/ajax/ **/
POST
     https://www.instagram.com/accounts/login/ajax/ 
HEADER
     Content-Type: application/x-www-form-urlencoded
    /** id app      (      )        **/
     x-ig-app-id: 1217981644879628
     x-csrftoken: /**    csrftoken **/
     cookie: /**     **/
     user-agent: /**   **/
BODY
     username=/**   **/&password=/**   **/&queryParams={}&optIntoOneTap=false
 /**         json,         userId **/
{"authenticated": true, "user": true, "userId": "****", "loginNonce": "****", "reactivated": true, "status": "ok"}
 /**       json **/
{"authenticated": false, "user": true, "status": "ok"}
 /**          json    (     ) **/

User Search


To do this, we will need previously received cookies and the x-csrftoken header.

/**  POST   https://www.instagram.com/web/search/topsearch/ **/
GET 
    https://www.instagram.com/web/search/topsearch/?context=blended&query={ }&rank_token={  0.87979}&include_ree=true
HEADER
     x-csrftoken: /**    csrftoken **/
     x-ig-app-id: 1217981644879628
     cookie: /**     **/
     user-agent: /**   **/
/**    **/
 {
    "users": [
                 {"position":0, 
                   "user":{
                               "pk":" "
                               "username":"  "
                               "full_name":" ,  "
                               .....    
                               }
                  },{},{}
    ],
    "places":[   ],
    "hashtags":[  ],
    "has_more": true,
    "rank_token": "0.44093530619864296",
    "clear_client_cache": false,
    "status: "ok"
}

Sending messages to direct


To send messages to direct, we need user id to whom we will send, how to find users I described above.

/**  POST   api instagram **/
POST
       https://i.instagram.com/api/v1/direct_v2/threads/broadcast/text/
HEADER
      /**       **/
      user-agent: Instagram 10.2.2 Android (18/4.3; 320dpi; 720x1280; Huawei; HWEVA; EVA-L18; qcom; en_US)
     x-csrftoken: /**    csrftoken **/
     x-ig-app-id: 1217981644879628
     cookie: /**     **/
     content-type: application/x-www-form-urlencoded
BODY
     text={ }&_uuid=&_csrftoken={   csrftoken}&recipient_users="[[   ]]"&action=send_item&thread_ids=["0"]&client_context={UUID v4  }
/**      **/
{"status":"ok", "payload":{"item_id":" "} ...}

/**   UUID v4 **/
function uuid4()
    {
        if (function_exists('com_create_guid') === true) {
            return trim(com_create_guid(), '{}');
        }
        $data = openssl_random_pseudo_bytes(16);
        $data[6] = chr(ord($data[6]) & 0x0f | 0x40);
        $data[8] = chr(ord($data[8]) & 0x3f | 0x80);
        return vsprintf('%s%s%s%s%s%s%s%s', str_split(bin2hex($data), 4));
    }

Uploading photos via the WEB version


Before sending images, you need to save them in ImageJPEG quality 100 otherwise the instagram will return an error:

$photo = __DIR__ . '/source.jpg';
$file_temp = __DIR__ . '/send_images.jpg';
list($width, $height, $image_type) = getimagesize(realpath($photo));
$srcImage = ImageCreateFromJPEG($photo);
$resImage = ImageCreateTrueColor($width, $height);
ImageCopyResampled($resImage, $srcImage, 0, 0, 0, 0, $width, $height, $width, $height);
ImageJPEG($srcImage, $file_temp, 100);
ImageDestroy($srcImage);

Upload photo:

/**      POST  **/
/** $microtime    microtime    id photo **/
$microtime = round(microtime(true) * 1000);
POST
      https://www.instagram.com/rupload_igphoto/fb_uploader_' . $microtime
HEADER
      content-type: image/jpg
      x-entity-name: 'fb_uploader_' . $microtime /** id photo **/
      offset: 0
      user-agent: Mozilla/5.0 (iPhone; CPU iPhone OS 11_4_1 like Mac OS X; ru-RU) AppleWebKit/537.36 (KHTML, like Gecko)  Version/11.4.1 Mobile/15G77 Safari/537.36 Puffin/5.2.2IP
      x-entity-length: filesize($file_temp) /**   **/
      x-instagram-rupload-params: {"media_type":1,"upload_id":"' . $microtime . '","upload_media_height":' . $height . ',"upload_media_width":' . $width . '}
     x-csrftoken: /**    csrftoken **/
     x-ig-app-id: 1217981644879628
     cookie: /**     **/
BODY
     /**  ,  body      **/
     file_get_contents(realpath($file_temp))
/**     json **/
{"upload_id":"   $microtime", "status":"ok" ...}
 
/**     ,        : **/
 
POST
       https://www.instagram.com/create/configure/
HEADER
      content-type: application/x-www-form-urlencoded
      user-agent: Mozilla/5.0 (iPhone; CPU iPhone OS 11_4_1 like Mac OS X; ru-RU) AppleWebKit/537.36 (KHTML, like Gecko)  Version/11.4.1 Mobile/15G77 Safari/537.36 Puffin/5.2.2IP
      x-csrftoken: /**    csrftoken **/
      x-ig-app-id: 1217981644879628
      cookie: /**     **/
BODY
      upload_id=$microtime&caption={, }&usertags=&custom_accessibility_caption=&retry_timeout=
/**      json   */
{"status":"ok", "media":{"id":"***", ...}}


That's all, I implemented a minimal wrapper over instagram.
I posted the full working version on github .
I will be glad to hear about the implementation, maybe something I did wrong.

Source: https://habr.com/ru/post/undefined/


All Articles