13

I'm trying to get an access_token from Instagram to use their Basic Display API for a new app (simply display tweets on a webpage).

I followed these steps: https://developers.facebook.com/docs/instagram-basic-display-api/getting-started

But I'm stuck at Step 5: Exchange the Code for a Token

The cURL request always returns a 400 error with the message: "Matching code was not found or was already used"

However, after many tests, I got an access_token one time only, but it expired about one hour later. This seems to be very random.

The Instagram Basic Display API seems rather new. A while ago, I have used apps created on the https://www.instagram.com/developer/ website and it used to work. Now this site display this message:

UPDATE: Starting October 15, 2019, new client registration and permission review on Instagram API platform are discontinued in favor of the Instagram Basic Display API.

... with a link to the developers.facebook.com.

halfer
  • 19,824
  • 17
  • 99
  • 186
Maxime Freschard
  • 1,066
  • 2
  • 15
  • 26
  • where you able to get the access token? I keep getting the same 400 error even using `curl` – Gianfranco P. Oct 27 '19 at 19:29
  • @GianfrancoP. have you tried to publish your Facebook app ? (in the Facebook Developers console for Apps) – Maxime Freschard Oct 28 '19 at 08:25
  • I finally managed to get the access token. My app has been live before but now I'm adding Instagram login so I'm waiting for the approval as of few hours today. I managed to get it to work, not sure what I was doing wrong exactly, tbh – Gianfranco P. Oct 28 '19 at 20:10
  • Check my answer with some code here https://stackoverflow.com/a/59305113/1474270 it might help – patJnr Dec 12 '19 at 12:59
  • https://stackoverflow.com/questions/59526137/my-app-was-rejected-by-instagram-basic-display-api-review-due-to-invalid-reasons – Amrut Bidri Dec 30 '19 at 06:30

8 Answers8

11

I tried using the command-line tool as per the original docs(https://developers.facebook.com/docs/instagram-basic-display-api/getting-started), but no luck...

Here's what to do in 3 easy steps:

  1. First thing: Install Postman https://www.postman.com/downloads/
  2. Make a POST request to https://api.instagram.com/oauth/access_token with the parameters in the body, NOT the params. Make sure that the x-www-form-urlencoded option is enable.
  3. You should now get a status of 200 OK and a response with both access_token and user_id.
{
    "access_token": "IGQVJYUXlDN...",
    "user_id": 17841400...
}

Happy days!!

See the screenshot for the correct settings:

enter image description here

Anas
  • 1,345
  • 14
  • 15
3

I just succeeded by removing the trailing #_ at the end in the code they give you. Not sure if that was your issue?

https://developers.facebook.com/support/bugs/436837360282557/

Emmanuel
  • 41
  • 2
3

I had this problem when i was trying implement a application.
My problem was the code generated when you allow the permissions.
Try to remove #_ from the end of the generated code and try generate the token again

Generated code example: AQBvrqqBJJTM49U1qTQWRMD96oRyMR3B_04JSfjc-nUIi0iGbSc3x_EceggQi9IyG3B3Rj3ocreMThQoPJbPpeXLUM4exJMy4o01fXcRtT_I9NovaNAqmWSneFt3MYv_k7ifAUUeMlC050n5xnjQP6oAvDBfCFQvTdrFaR95-5i71YsfQlmjYWDG6fcWRvOB9nqr6J9mbGMXMi9Y4tKlSfElaYm0YKRijZQDG2B5PaxQ8A #_

Generated code edited: AQBvrqqBJJTM49U1qTQWRMD96oRyMR3B_04JSfjc-nUIi0iGbSc3x_EceggQi9IyG3B3Rj3ocreMThQoPJbPpeXLUM4exJMy4o01fXcRtT_I9NovaNAqmWSneFt3MYv_k7ifAUUeMlC050n5xnjQP6oAvDBfCFQvTdrFaR95-5i71YsfQlmjYWDG6fcWRvOB9nqr6J9mbGMXMi9Y4tKlSfElaYm0YKRijZQDG2B5PaxQ8A

Romulo Milani
  • 81
  • 1
  • 1
  • 5
0

I was using the old Instagram API as well. I had to change a few things to make my code work on the new API. Not sure what you're using, this is how I did it with PHP.

$url = 'https://api.instagram.com/oauth/access_token';

$fields = array(
    'app_id' => 'YOUR_APP_ID',
    'app_secret' => 'YOUR_APP_SECRET_ID',
    'grant_type' => 'authorization_code',
    'redirect_uri' => 'YOUR_REDIRECT_URL',
    'code' => $code
);

$ch = curl_init();

curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_POST, true);
curl_setopt($ch,CURLOPT_POSTFIELDS, $fields);
curl_setopt($ch,CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch,CURLOPT_VERIFYPEER, false);

$result = curl_exec($ch);
curl_close($ch);

//get the access token from the string sent from Instagram
$splitString = explode('"access_token":', $result);
$removeRest = explode(',', $splitString[1]);
$withSpace = str_replace('"','', $removeRest[0]);
$access_token = str_replace(' ','', $withSpace);
Community
  • 1
  • 1
Nobody
  • 101
  • 1
  • Hi @Nobody, I'm using PHP too with Guzzle (cURL library). My code is similar to yours. It worked once yesterday, but most of the time it does not work... – Maxime Freschard Oct 23 '19 at 07:31
  • Hi @Nobody, how do you call the https://api.instagram.com/oauth/authorize endpoint to get a code with cURL ? When I do that I'm redirected to the Instagram login page. – Maxime Freschard Oct 23 '19 at 08:41
  • Maxime, you don't have to use cURL. Instagram include the code in the URL after it redirects to your site. You can use HTTP GET to pick up the code: $code = $_GET['code']; – Nobody Oct 23 '19 at 18:51
0

I was also having the same problem, I solved clearing the cache, coockie and other browser data.

Then I made a new request.

Try it, it worked with me.

0

I found the solution.

The direct uri must the same as you use in the beginning.

ex. You use

www.abc.com/auth 

to get the code. When you exchange the token the redirect_uri must be the same as

www.abc.com/auth
JackWu
  • 1,036
  • 1
  • 12
  • 22
0

Some of the solutions worked for me:

Browser environment:

// parameters (fill the empty strings)
const accessTokenParams = {
  client_id: "",
  client_secret: "",
  grant_type: "authorization_code",
  redirect_uri: "",
  code: ""
};

const response = await fetch("https://api.instagram.com/oauth/access_token", {
  method: "POST",
  headers: {
    "Content-Type": "application/x-www-form-urlencoded"
  },
  body: JSON.stringify(accessTokenParams),
})

Node environment

The solution above didn't worked for me. Thus, I've installed the node-libcurl library.

yarn add node-libcurl

After, I got a successful response with the code below:

const querystring = require('querystring');
const { Curl } = require('node-libcurl');

// parameters (fill the empty strings)
const accessTokenParams = {
  client_id: "",
  client_secret: "",
  grant_type: "authorization_code",
  redirect_uri: "",
  code: ""
};

// Prepare the request
const curlTest = new Curl();

curlTest.setOpt(Curl.option.URL, "https://api.instagram.com/oauth/access_token");

curlTest.setOpt(Curl.option.POST, true);

curlTest.setOpt(
  Curl.option.POSTFIELDS,
  querystring.stringify(accessTokenParams)
);
curlTest.on("end", function (statusCode:number, data:any, headers:any) {
  console.info("Our response: " + data);
  if (statusCode !== 200) {
    // Error case
  }
  // Do what you need with data

  this.close();
});
const terminate = curlTest.close.bind(curlTest);
curlTest.on('error', terminate);
curlTest.perform();
-1

I am using PHP but without using any lib. Maybe this one help you.

curl.php

class InstagramApi 
{

public function GetAccessToken($client_id, $redirect_uri, $client_secret, $code) {      
    $url = 'https://api.instagram.com/oauth/access_token';

    $curlPost = 'app_id='. $client_id . '&redirect_uri=' . $redirect_uri . '&app_secret=' . $client_secret . '&code='. $code . '&grant_type=authorization_code';
    $ch = curl_init();      
    curl_setopt($ch, CURLOPT_URL, $url);        
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_POST, 1);      
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $curlPost);            
    $data = json_decode(curl_exec($ch), true);  
    $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE); 
    curl_close($ch);    

    if($http_code != '200')         
        throw new Exception('Error : Failed to receieve access token');

    return $data;

  }

index.php

include "curl.php";
include "instagram_keys.php"; // holding APP ID, SECRET KEY, REDIRECT URI

 $instagram_ob = new InstagramApi();
 $insta_data = $instagram_ob->GetAccessToken(INSTAGRAM_CLIENT_ID, INSTAGRAM_REDIRECT_URI, INSTAGRAM_CLIENT_SECRET, $_GET['code']);  
  echo  $insta_data['access_token'];
  echo  $insta_data['user_id'];

NOTE: $_GET['code'] is required and you should know how to get the code. Read here

Ns789
  • 531
  • 10
  • 21