where to use access_token

  • 1
  • Problem
  • Updated 2 years ago
Is there anyone who can help me in using Access_token in my PHP Web Application.
right now i am stuck on access_token and i want to test my Fax function but Using PHP SDK i am stuck on Refresh_token function it is giving error and looks like my SDK is not using Access_token....


i am getting this error
authData.php Auth exception: Refresh token has expired Exception: Unauthorized for this grant type SDK HTTP Error at https://platform.devtest.ringcentral.com/restapi/oauth/token Response text: { "error" : "unauthorized_client", "error_description" : "Unauthorized for this grant type", "errors" : [ { "errorCode" : "OAU-251", "message" : "Unauthorized for this grant type" } ] }
Photo of Tayyab Sajjad

Tayyab Sajjad

  • 364 Points 250 badge 2x thumb

Posted 2 years ago

  • 1
Photo of Paco Vu

Paco Vu

  • 486 Points 250 badge 2x thumb
Hi Tayyab,

It seems you selected the wrong Platform type (other types than the "Server-only/(No UI)" for your RingCentral app. If your Web app uses the PHP SDK to authenticate and access RingCentral APIs directly, you must select the "Server-only/(No UI)" for the Platform type.

Try to create a new app with that platform type and test again.

Kind regards,
Paco
Photo of Tayyab Sajjad

Tayyab Sajjad

  • 364 Points 250 badge 2x thumb
i have created another app with Server no UI but now i am not able to authorize it 
Photo of Paco Vu

Paco Vu

  • 476 Points 250 badge 2x thumb
It would be helpful to diagnose if you can show a little more with your codes?
Photo of Tayyab Sajjad

Tayyab Sajjad

  • 364 Points 250 badge 2x thumb
when i get the access_token after that how to use that token ?
Do you know ?
try {

    $platform->refresh();

    print 'Authorization was restored' . PHP_EOL;

} catch (Exception $e) {

    print 'Auth exception: ' . $e->getMessage() . PHP_EOL;

    $auth = $platform->login($credentials['username'], $credentials['extension'], $credentials['password']);

    print 'Authorized' . PHP_EOL;

}


when i try to run this code , it failed at refresh token and give this error
authData.php Auth exception: Refresh token has expired Exception: Unauthorized for this grant type SDK HTTP Error at https://platform.devtest.ringcentral.com/restapi/oauth/token Response text: { "error" : "unauthorized_client", "error_description" : "Unauthorized for this grant type", "errors" : [ { "errorCode" : "OAU-251", "message" : "Unauthorized for this grant type" } 
Photo of Paco Vu

Paco Vu

  • 476 Points 250 badge 2x thumb
1) You still receiving the same error which related to wrong platform type. So I am not sure if you have changed the appKey and secret accordingly.

2) I saw your other questions relating to problem with sending fax from PHP code and there you mentioned about using 3-leg authentication. If this is the same project, then you probably don't need to create a new app with "server-only" platform type. But you should follow the instructions from this demo project to get the access token from your client side and pass the token to the php via session.

https://github.com/ringcentral/ringcentral-demos-oauth/blob/master/php/index.php

//set the access token using the auth objectif (isset($_SESSION['sessionAccessToken'])) { $platform->auth()->setData((array)json_decode($_SESSION['sessionAccessToken']));}

Hope this helps,
Paco
Photo of Tayyab Sajjad

Tayyab Sajjad

  • 364 Points 250 badge 2x thumb
i am passing this but after this action when i try to refresh token or login it is getting failed...
and using the same $platform any api request is also failed.

help me
Photo of AK

AK, Official Rep

  • 4,402 Points 4k badge 2x thumb
If the accessToken is expired, then you would HAVE to Authorize the same way as you did earlier using the Authorization Code Flow ( 3 Legged OAuth )

Since the accessToken are valid for 1 hour and if you are trying to refresh the tokens before the TTL expiry then you are GOOD to refresh the accessTokens. But once the accessTokens are expired you would no longer be able to refresh the expired token and hence you would need to re-authorize again

Are you following the API ref for Refresh:
https://developer.ringcentral.com/api-docs/latest/index.html#!#RefRefreshTokenFlow
Photo of Tyler Long

Tyler Long, Official Rep

  • 8,884 Points 5k badge 2x thumb
There are two tokens: accessToken and refreshToken. before your accessToken is expired, you need to refresh it using refreshToken.
Photo of Tayyab Sajjad

Tayyab Sajjad

  • 364 Points 250 badge 2x thumb
i run the Authorization Code Flow ( 3 Legged OAuth ) again and i get access token again, through this i got refresh token.
and the code in 3 Legged is


if (isset($_SESSION['sessionAccessToken'])) {
    $platform->auth()->setData((array)json_decode($_SESSION['sessionAccessToken']));
}


I hope this code will set my access token , Now i run the https://github.com/ringcentral/ringcentral-php but again getting error on authData.php 34 line where we have function  $platform->refresh(); . . 


at this point i am getting exception of "Refresh token has expired Exception".
Photo of Tyler Long

Tyler Long, Official Rep

  • 8,884 Points 5k badge 2x thumb
Could you please create a gist with all your source code and the instructions to run your code? https://gist.github.com/

Frankly speaking, I don't quite understand the process you described. You need to tell us how to reproduce the problem.
Photo of Tayyab Sajjad

Tayyab Sajjad

  • 364 Points 250 badge 2x thumb
ok let me explain
i have an application of Web based and i an using 3 Legged authentication.
and save the access token and refresh token to platform.json.
Now i run the php SDK and now you know there are few tests in SDK's first index file.
the first file is authData.php and i passed this successfully. 
Now when i try run this code i am getting grant issue
$platform->login('','','');

The error is 
Exception: Unauthorized for this grant type SDK HTTP Error 
Photo of Tyler Long

Tyler Long, Official Rep

  • 8,884 Points 5k badge 2x thumb
If you already got the tokens via 3 legged authorization, you don't need to run $platform->login('','',''). You should go ahead to make API calls with the tokens you already have.

Login is to get token, if you already have the tokens, why login again?
(Edited)
Photo of Tayyab Sajjad

Tayyab Sajjad

  • 364 Points 250 badge 2x thumb
actually in sample Fax of SDK we have Login code.


can you check this request of fax ? i am getting error on this 
$request = $rcsdk->createMultipartBuilder()
                 ->setBody(array(
                     'to'         => array(
                         array('phoneNumber' => '12673314004'),
                     ),
                     'faxResolution' => 'High',
                 ))
                 ->request('/account/~/extension/~/fax');
Photo of Tyler Long

Tyler Long, Official Rep

  • 8,884 Points 5k badge 2x thumb
After you get tokens from 3-legged auth flow, call this method to set your tokens: https://github.com/ringcentral/ringcentral-php/blob/ac9984a8ae2e41239dfe84ae4f698f8a16b22417/src/Pla...

Then go ahead to make API calls
Photo of Tayyab Sajjad

Tayyab Sajjad

  • 364 Points 250 badge 2x thumb
in 3 Legged this code is already working
$platform->auth()->setData((array)json_decode($_SESSION['sessionAccessToken']));


right?
Photo of Tyler Long

Tyler Long, Official Rep

  • 8,884 Points 5k badge 2x thumb
Send the source code as a gist please. It's too hard to troubleshoot without the full context. Please also write down the steps to run your code.  

Please remove the credentials of course.
Photo of Tayyab Sajjad

Tayyab Sajjad

  • 364 Points 250 badge 2x thumb
this is the code for 3 Legged
<?php
require_once('../../../autoload.php');

use RingCentral\SDK\Http\HttpException;
use RingCentral\SDK\Http\ApiResponse;
use RingCentral\SDK\SDK;
use RingCentral\http\Response;

// Start the session
session_start();

$rcsdk = new SDK('', '', 'https://platform.devtest.ringcentral.com', 'app1', '1.0.0');


// Create Platform instance
$platform = $rcsdk->platform();

// Using the authUrl to call the platform function
$url = $platform
    ->authUrl(array(
        'redirectUri' => 'http://localhost/vendor/ringcentral/ringcentral-php/php/callback.php',
        'state' => 'asia',
        'brandId' => '',
        'display' => '',
        'prompt' => ''
    ));

// Store the url in PHP Session Objec;
$_SESSION['url'] = $url;

//set the access token using the auth object
if (isset($_SESSION['sessionAccessToken'])) {
    $platform->auth()->setData((array)json_decode($_SESSION['sessionAccessToken']));
}

?>
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>;
    <script>

        var url = '<?php echo $url; ?>';
        var redirectUri = '<?php echo 'http://localhost/vendor/ringcentral/ringcentral-php/php/callback.php'; ?>';

        var config = {
            authUri: url,
            redirectUri: redirectUri,
        }

        var OAuthCode = function (config) {
            this.config = config;

            this.loginPopup = function () {
                console.log("The URL is :" + url);
                this.loginPopupUri(this.config['authUri'], this.config['redirectUri']);
            }
            this.loginPopupUri = function (authUri, redirectUri) {
                var win = window.open(authUri, 'windowname1', 'width=800, height=600');
                var pollOAuth = window.setInterval(function () {
                    try {
                        console.log(win.document.URL);
                        if (win.document.URL.indexOf(redirectUri) != -1) {
                            window.clearInterval(pollOAuth);

                            //win.close();
                            location.reload();
                        }
                    } catch (e) {
                        console.log(e);
                        // win.close();
                    }
                }, 100);

            }
        }

        var oauth = new OAuthCode(config);

    </script>
</head>
<body>
<h1>RingCentral 3-Legged OAuth Demo in PHP</h1>

<p><input type="button" onclick="oauth.loginPopup()" value="Login with RingCentral"></p>

<p>After retrieving the token use the PHP SDK's auth class's set_data method to load the access_token.</p>

<p>Access Token</p>
<pre>
    <style="background-color:#efefef;padding:1em;overflow-x:scroll"><?php if ($platform->loggedIn()){
echo json_encode($platform->auth()->data(), JSON_PRETTY_PRINT);
$fp = fopen('../demo/_cache/platform.json', 'w');
fwrite($fp, json_encode($platform->auth()->data(), JSON_PRETTY_PRINT));
fclose($fp);
}
else{echo "No";}
?></pre>


<p>More info:</p>
<ul>
    <li><a href="https://developer.ringcentral.com/api-docs/latest/index.html#!#AuthorizationCodeFlow">RingCe... API
            Developer Guide</a></li>
    <li><a href="https://github.com/grokify/ringcentral-oauth-demos">GitHub repo</a>
    <li><a href="https://github.com/grokify/ringcentral-oauth-demos/tree/master/python-bottle">GitHub repo Python
            README</a></p></li>
</ul>
</body>
</html>


after authorization and getting access token and refresh token in platform.json

I am trying to send Fax 
<?php

require_once(__DIR__ . '/_bootstrap.php');

use RingCentral\SDK\SDK;

// Create SDK instance

$credentials = require(__DIR__ . '/_credentials.php');

$rcsdk = new SDK('', '', 'https://platform.devtest.ringcentral.com', 'app1', '1.0.0');


$platform = $rcsdk->platform();


// Send Fax

$request = $rcsdk->createMultipartBuilder()
                 ->setBody(array(
                     'to'         => array(
                         array('phoneNumber' => '12673314004'),
                     ),
                     'faxResolution' => 'High',
                 ))
                 ->request('/account/~/extension/~/fax');

//print $request->getBody() . PHP_EOL;

$response = $platform->sendRequest($request);

print 'Sent Fax ' . $response->json()->uri . PHP_EOL;
Photo of Tyler Long

Tyler Long, Official Rep

  • 8,884 Points 5k badge 2x thumb
The 3 legged oauth app and the fax app are 2 separate apps.The first app writes tokens into platform.json, but the second app doesn't read tokens from platform.json. Correct me if I am wrong. 

If what I said above is correct, it means the fax app doesn't get tokens from the oauth app at all.
(Edited)
Photo of Tayyab Sajjad

Tayyab Sajjad

  • 364 Points 250 badge 2x thumb
Fax is in demo of SDK and before testing Fax we have to get access token...how SDK can work without authentication ?

i am getting "token has expired" on sending Fax ... if token is not usefull then why is this error ... :) 

I am new to all this and stuck on this.
Photo of Tyler Long

Tyler Long, Official Rep

  • 8,884 Points 5k badge 2x thumb
The overall idea is: you get token via the 3-legged oauth and save the token.

Then in another app, you restore the saved token before making any api calls.

The demo fax app uses login to get token, so it doesn't need to restore a saved token.

But you need to do the restore step.
Photo of Tyler Long

Tyler Long, Official Rep

  • 8,884 Points 5k badge 2x thumb
The exception message from API server side could be misleading. When it says token expired. it might mean token missing/invalid
Photo of Tayyab Sajjad

Tayyab Sajjad

  • 364 Points 250 badge 2x thumb
my basic target is to send Fax and in demo fax i am not able to login it is saying grant issue if i dont use the stored access token 
Photo of Tayyab Sajjad

Tayyab Sajjad

  • 364 Points 250 badge 2x thumb
Ohh I have done :)
but attachment is missing can you see
$request = $rcsdk->createMultipartBuilder()
                 ->setBody(array(
                     'to'         => array(
                         array('phoneNumber' => '12673314004'),
                     ),
                     'faxResolution' => 'High',
                 ))
                 ->add('Plain Text', 'file.txt')
                 ->add(fopen('D:/wamp/www/vendor/ringcentral/ringcentral-php/demo/file.txt', 'r'))
                 ->request('/account/~/extension/~/fax');
Photo of Tyler Long

Tyler Long, Official Rep

  • 8,884 Points 5k badge 2x thumb
There are two ways to get token:

#1 The first is to call login. It's not an option for you because your app doesn't support that grant type.


#2 The second is to get token via 3-legged oauth. If you use this way, please do not login because it doesn't make sense to login here since it's way #1. But please don't forget to restore the token saved by 3-legged oauth flow! Otherwise you got a token but didn't use it at all!

Here is a sample for you to restore a token: https://github.com/ringcentral/ringcentral-php/blob/master/demo/authData.php
Photo of Tyler Long

Tyler Long, Official Rep

  • 8,884 Points 5k badge 2x thumb
If you are done with the authorization issue. Please create a new thread to track new issues.
Photo of Tayyab Sajjad

Tayyab Sajjad

  • 364 Points 250 badge 2x thumb
sure :)
Can you help me in attachment ?
Photo of Tyler Long

Tyler Long, Official Rep

  • 8,884 Points 5k badge 2x thumb
Sure. I am here to help RingCentral API users.


But let's continue with a new thread. :)