Home > Enterprise >  PHP Laravel Callback upon API authentication
PHP Laravel Callback upon API authentication

Time:10-14

I am trying to implement a call back method in PHP. I am successfully calling an instagram API to authorise the user but I do not know how to capture the token after the user authorises.

Below is my code:

 public function oAuthBasic()
    {
            $instagramBasic = new InstagramBasicDisplay([
                'appId' => 'xxx',
                'appSecret' => 'xxx',
                'redirectUri' => 'xxx'
            ]);
            
            session()->forget('instagramErrorMessage');
            $faceBookLoginUrl = $instagramBasic->getLoginUrl();
            return response()->json(['redirectUrl' => $faceBookLoginUrl]);
            
    }

This successfully brings up the sign in pop up. However after authorisation, how can I capture the user access token?

enter image description here

Any help is greatly appreciated.

CodePudding user response:

I managed to fix the issue with the help of @CBore's comment:

Created a new route in my web.php

Route::get('linkinstagramBasic','InstagramController@linkBasic')->name('instagram.linkBasic');

Included the URL under Valid OAuth Redirect URIs on facebook app settings page.

enter image description here

Finally wrote the callback:

 /*
     * Function that works as the call back after Instagram basic display api authorisation
     * Get the code and call access_token API
     * AUTHOR : DON
     * DATE : 12/10/2022
     */
    public function linkBasic(InstagramLinkRequest $instagramRequest) {
        
        if (isset($_GET['code'])) {
            // Get the OAuth callback code
            $code = $_GET['code'];
            $ig_atu = "https://api.instagram.com/oauth/access_token";
            $ig_data = [];
            $ig_data['client_id'] = Config::get('instagram_basic.app_id');
            $ig_data['client_secret'] = Config::get('instagram_basic.app_secret');
            $ig_data['grant_type'] = 'authorization_code';
            $ig_data['redirect_uri'] = Config::get('instagram_basic.redirect_uri');
            $ig_data['code'] = $code;

            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $ig_atu);
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($ig_data));
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            $ig_auth_data = curl_exec($ch);
            curl_close($ch);
            $ig_auth_data = json_decode($ig_auth_data, true);

            dd($ig_auth_data);

            //$accessTok = $ig_auth_data['access_token'];
            //$UID = $ig_auth_data['user_id'];
            //echo "<script>window.close();</script>";
        }
    }
  • Related