navjot singh
navjot singh

Reputation: 143

Error in Instagram Basic display API: Matching code was not found or was already used

I am trying to access the ACCESS_TOKEN from Instagram Basic Display API. I success full get the code as mentioned below and now I am trying to pass this $_GET['code'] to accesstoken() but getting no responce(error).

 //sample request demo (string(240))  
https://www. mysite.org/dashboard.php?code=AQAWTCkmCLVYUJddAqjcNvhh_BZDJg-68vSK1bun3KdNp3nbLdcjexCncu_LvPtk4jY5bJTCXe4vJ9yldmBsUZzE0heDtkhhd--SrPlCer0Lq5J25qZ_X9OBQ5AokmxCum4kz6kgqN1ilq6ZLT1m84mIJ0_hhLVKXwaPTprUXgRtmm1Gat5NbdbhtuXjOqMgD9yFfe94QVsV-aQ7CwKpAtPTrT9_nSUVDVedF0JhbqvWbQ#_

Here below I just removed the #_ at the end of the $_GET['code'] and pass it on to the function.

$object = new instaAPI();
$code = trim($_GET['code'], "#_"); //removed the tralling #_ from the end.
$access = $object->accesstoken(APP_ID, REDIRECT_URI, APP_SECRET, $code); //calling
echo $access['access_token']; // blank

Curl function

class instaAPI
{
    public function accesstoken($app_id, $redirect_uri, $app_secret, $cod)
    {
      $url = 'https://api.instagram.com/oauth/access_token';


      $curl_post = 'app_id='.$app_id. '&redirect_uri='.$redirect_uri.'&app_secret='.$app_secret.'&code='.$cod.'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, $curl_post);

      $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'.'IG_ERROR_TYPE:'.$data['error_type'].'CODE:'.$data['code'].'MESSAGE'.$data['error_message']);


      return $data;

    } 


}

Response OR Json Response

Error: Failed to receive access token 

IG_ERROR_TYPE: OAuthException 
CODE:400
MESSAGE: Matching code was not found or was already used

or

{
    "error_type": "OAuthException",
    "code": 400,
    "error_message": "Matching code was not found or was already used"
}

I am stuck at this point, any help is appreciated.

Upvotes: 0

Views: 1189

Answers (1)

Nobody
Nobody

Reputation: 792

Change from "$cod" to "$code" in this line:

public function accesstoken($app_id, $redirect_uri, $app_secret, $cod)

and:

 $curl_post = 'app_id='.$app_id. '&redirect_uri='.$redirect_uri.'&app_secret='.$app_secret.'&code='.$cod.'grant_type=authorization_code';

Upvotes: 1

Related Questions