question

steve-thomas3166 avatar image
steve-thomas3166 asked ak answered

after successfully authenticated with api, i am getting error code CMN-102

Hi,


Last 3 days, i am trying to access call logs from api using sandbox credentials but getting errors.

I get error of Invalid Authorization header when i am trying to access from PHP curl query.

Even i successfully authenticated with apis and get access token.

$headers = array( 'Accept: application/json',

'Authorization: Bearer' . $_SESSION['access_token']

);

curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

$url='https://platform.devtest.ringcentral.com/restapi/v1.0/account/~/extension/~/call-log';

Kindly tell me how to get call logs from api using PHP curl script



Thanks,

Ajay Gupta

getting started
1 |1500 characters needed characters left characters exceeded

Up to 8 attachments (including images) can be used with a maximum of 1.0 MiB each and 10.0 MiB total.

benjamin-dean avatar image
benjamin-dean answered
Hello Ajay,

Please accept my apologies, since my PHP is a little rusty, but I thought I'd give it a shot to show you how to do this. I have the example file done and working, and the answer is posted below, but I'd like to post it in StackOverflow (with the 'ringcentral' tag) because the code formatting/syntax highlighting looks nicer.

Would you kindly ask this question in StackOverflow and I will provide the example in the answer for you? (you can just copy and paste the question as you have it posted here, and perhaps elaborate a little by providing an example cURL request you used which did not work for fetching the call-log resources)

https://stackoverflow.com/questions/ask (just make sure to add 'ringcentral' in the "Tags" form field).

Thanks,
Benjamin
1 |1500 characters needed characters left characters exceeded

Up to 8 attachments (including images) can be used with a maximum of 1.0 MiB each and 10.0 MiB total.

benjamin-dean avatar image
benjamin-dean answered
<?php    // Configuration vars
    $appKey = '{ {REPLACE_WITH_YOUR_APP_KEY}}';
    $appSecret = '{ {REPLACE_WITH_YOUR_APP_SECRET}}';
    $server = ' https://platform.devtest.ringcentral.com';
    $username = '{ {REPLACE_WITH_YOUR_USERNAME}}';
    $password = '{ {REPLACE_WITH_YOUR_PASSWORD}}';

    // Responses
    $myToken = null;
    $myCallLogs = null;

    // Base64 Encode appKey:appSecret
    $rawApiKeys = $appKey . ':' . $appSecret;
    $encodedApiKeys = base64_encode( $rawApiKeys );
    echo 'Encoded API Keys: ' . $encodedApiKeys;

    // Get Access Token
    $tokenRequest = makeRequest( $server, $encodedApiKeys, "/restapi/oauth/token", null, "POST", "username=" . $username . "&password=" . $password . "&grant_type=password" );
    if( handleTokenResult( $tokenRequest ) ) {
        $myToken = json_decode( $tokenRequest );
        echo "OUTPUT VALUE OF myToken";
        print_r( $myToken );
        echo $myToken->access_token;
        $callLogRequest = makeRequest( $server, $myToken->access_token, "/restapi/v1.0/account/~/extension/~/call-log/" );
        handleCallLogResult( $callLogRequest );
    }

    // HTTP Response Handler
    function handleTokenResult( $responseData ) {
        $myJSON = json_decode( $responseData, true );
        if( isset( $myJSON['access_token'] ) ) {
            echo "\n\n";
            echo "Auth data received.";
            print_r( $myJSON );
            return $myJSON;
        }
        echo "Uh oh, that did not work the way we expected.";
        return false;
    }

    function handleCallLogResult( $responseData ) {
        $myJSON = json_decode( $responseData, true );
        if( isset( $myJSON['records'] ) ) {
            echo "\n\n";
            echo "Call Log data received.";
            print_r( $myJSON );
            return $myJSON;
        }
        echo "Uh oh, we should have had a records property.";
        return false;
    }

    // HTTP Request function
    function makeRequest( $server, $token, $path, $params = null, $method = 'GET', $data = null ) {
        echo 'Preparing API Request...';
        echo "\n\n";

        // Sanity check

        // Make sure base path is always included
        $basePath = '/^\/restapi\//';
        if( 1 !== preg_match( $basePath, $path ) ) {
            $path = "/restapi/" . $path;
        }
        // Make sure params is empty or an array
        if( null !== $params && "array" !== gettype( $params ) ) {
            echo "params either needs to be null or an array";
            echo "\n\n";
        } else {
            // Map to query string and HTML encode entities where appropriate
        }

        // The URL to use
        $ch = curl_init( $server . $path );

        // Set authorization header properly
        $authPath = '/oauth\/token/';

        if( 1 !== preg_match( $authPath, $path ) ) {
            echo "Preparing Non-Auth request...";
            echo "\n\n";
            $authHeader = 'Authorization: Bearer ' . $token;
            $contentType = 'Content-Type: application/json';

            if( "POST" == $method && "array" !== gettype( $data ) ) {
                curl_setopt( $ch, CURLOPT_CUSTOMREQUEST, "POST" );
                $data_string = json_encode( $data );
                curl_setopt( $ch, CURLOPT_POSTFIELDS, $data_string );
            }

        } else {
            echo "Preparing Auth request...";
            echo "\n\n";
            $authHeader = 'Authorization: Basic ' . $token;
            echo "\n\n";
            curl_setopt( $ch, CURLOPT_POST, true );
            curl_setopt( $ch, CURLOPT_POSTFIELDS, $data );
        }
        curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true);

        curl_setopt( $ch, CURLOPT_HTTPHEADER, array(
            $authHeader )
        );

        // Execute request
        $result = curl_exec( $ch );

        // Close Connection
        curl_close( $ch );

        echo $result;

        return $result;
    }
?>


1 |1500 characters needed characters left characters exceeded

Up to 8 attachments (including images) can be used with a maximum of 1.0 MiB each and 10.0 MiB total.

jerry-white5852 avatar image
jerry-white5852 answered
i have use this code stuff but nothing response i am getting from this script,i have changed user name password and key,secret etc. please help what i am missing in this file. this file i have executed from from local server.

1 |1500 characters needed characters left characters exceeded

Up to 8 attachments (including images) can be used with a maximum of 1.0 MiB each and 10.0 MiB total.

ak avatar image
ak answered
Hi Jerry,

Could you please provide the API Request and the Response. Also, may I know what is the API endpoint that you are calling. 
1 |1500 characters needed characters left characters exceeded

Up to 8 attachments (including images) can be used with a maximum of 1.0 MiB each and 10.0 MiB total.

jerry-white5852 avatar image
jerry-white5852 answered
Thanks for reply
i was got the response successfully at that time, but at now again getting no response from the api. in app analytics show me successful hit increase as well.  

when i hit the php file, it just show this output again, same as before.


Encoded API Keys: <<EncodeKeys>>==Preparing API Request... 
1
Preparing Auth request...
Uh oh, that did not work the way we expected.


is it any rate limit issue ? if it is after 60 sec, it should be working.
1 |1500 characters needed characters left characters exceeded

Up to 8 attachments (including images) can be used with a maximum of 1.0 MiB each and 10.0 MiB total.

ak avatar image
ak answered
The above code was updated a while ago and let's go step by step:

1.) You would need to update the Configuration Variables first:
   
    $appKey = '{
                 {REPLACE_WITH_YOUR_APP_KEY}}';
    $appSecret = '{ {REPLACE_WITH_YOUR_APP_SECRET}}';
    $server = 'https://platform.devtest.ringcentral.com';
    $username = '{ {REPLACE_WITH_YOUR_USERNAME}}';
    $password = '{ {REPLACE_WITH_YOUR_PASSWORD}}';
The appKey and appSecret could be found on your application on the Developer Portal . The $username and $password are your sandbox credentials that you would need to login to the Service web on Sandbox:
https://service.devtest.ringcentral.com  ( this is different from your Production credentials )  You can find it on the Developer Portal -> Navigate to Application -> Sandbox Credentials

 2.) Per the code, it looks like you are trying to use the Call-Log API Endpoint. please make sure you have existing call log records by logging into Service web on Sandbox 

You can make inbound or outbound calls on the sandbox number to generate call logs. You can also use our RingCentral Softphone application to login and make and receive phone calls on the sandbox 

3.) Run 'php  index.php' ( assuming you have named the file as index.php )


However, we have a much simpler code if you are planning to use our official PHP SDK here:
https://github.com/ringcentral/ringcentral-php


Please take a look at Demo folder to know more.


 
1 |1500 characters needed characters left characters exceeded

Up to 8 attachments (including images) can be used with a maximum of 1.0 MiB each and 10.0 MiB total.

jerry-white5852 avatar image
jerry-white5852 answered
according to these steps, it's working fine getting response as well. i am using end point 
$callLogRequest = makeRequest( $server, $myToken->access_token, "/restapi/v1.0/account/~/extension/~/authz-profile/" );

during execution it display 

" https://platform.devtest.ringcentral.com/restapi/v1.0/dictionary/permission/UserInfo";, "id" : "UserInfo" }, "effectiveRole" : { "uri" : " https://platform.devtest.ringcentral.com/restapi/v1.0/dictionary/user-role/1";, "id" : "1" }, "scopes" : [ "AllExtensions" ] }, { "permission" : { "uri" : " https://platform.devtest.ringcentral.com/restapi/v1.0/dictionary/permission/Users";, "id" : "Users" }, "effectiveRole" : { "uri" : " https://platform.devtest.ringcentral.com/restapi/v1.0/dictionary/user-role/1";, "id" : "1" }, "scopes" : [ "UserExtensions" ] } ] }
Uh oh, we should have had a records property.

why it print  "Uh oh, we should have had a records property."
and when i hit again index.php  it display 

Encoded API Keys: WGNhdVJ4V3NUZkdEcTFucldGYW9qZzpRTnZsOHBsY1FKT3FBY1N2RXNqODFRV04wMTRvMVNUdGFqNzB0cmV0Ynk5QQ==
Preparing API Request... Preparing Auth request... Uh oh, that did not work the way we expected.

after a time i hit again it print half response and then say "Uh oh, we should have had a records property."

kindly tell me how i can resolve it.

also why i need to hit end point  - extension/authz-profile  in developer portal it display x 
i need only (  Call-Log API Endpoint, active-calls API Endpoint) only. due to this i can't met all the graduation requirements for production.

Thanks


1 |1500 characters needed characters left characters exceeded

Up to 8 attachments (including images) can be used with a maximum of 1.0 MiB each and 10.0 MiB total.

ak avatar image
ak answered
The above code is a sample code and I am not sure what exactly your application on RingCentral is doing. 

 
However, you would need to build an application on your side ( please keep in mind that the above code is a sample code ) and make sure that your application exercises all the API permissions on your application and post which your application would be graduated to Production once you have met all the criteria's. 

GET -extension/ authz -profile is basically used to get the permissions assigned to the User. 


If you have any further doubts, you could refer to our Graduation Criteria here:
https://devcommunity.ringcentral.com/ringcentraldev/topics/production-access-request-criteria
1 |1500 characters needed characters left characters exceeded

Up to 8 attachments (including images) can be used with a maximum of 1.0 MiB each and 10.0 MiB total.

jerry-white5852 avatar image
jerry-white5852 answered
hi AK
this sample code is very successful for me and according to my requirement.
i have updated these variables as well with my sandbox credentials 
$appKey = '{
                 {REPLACE_WITH_YOUR_APP_KEY}}';
    $appSecret = '{ {REPLACE_WITH_YOUR_APP_SECRET}}';
    $server = 'https://platform.devtest.ringcentral.com';
    $username = '{ {REPLACE_WITH_YOUR_USERNAME}}';
    $password = '{ {REPLACE_WITH_YOUR_PASSWORD}}';

same as above sample code i have changed end url according to application need, 
with these urls m was successful. 

//$callLogRequest = makeRequest( $server, $myToken->access_token, "/restapi/v1.0/account/~/extension/~/active-calls/" );
//$callLogRequest = makeRequest( $server, $myToken->access_token, "/restapi/v1.0/account/~/" );
//$callLogRequest = makeRequest( $server, $myToken->access_token, "/restapi/v1.0/account/~/extension/~/authz-profile/" );

but now with this end url it is not working.
$callLogRequest = makeRequest( $server, $myToken->access_token, "/restapi/v1.0/account/~/call-log/" );

with above sample code OUTPUT is 

Encoded API Keys: WGNhdVJ4V3NUZkdEcTFucldGYW9qZzpRTnZsOHBsY1FKT3FBY1N2RXNqODFRV04wMTRvMVNUdGFqNzB0cmV0Ynk5QQ==Preparing API Request... Preparing Auth request... Uh oh, that did not work the way we expected.

my app API permissions are
- Read Accounts
-Read Call Log

Application Type (Private)
Platform Type (Server-Only NoUI)

Now i hit again (after 1 minute = 10 ) index.php every time m getting above OUTPUT.

Kindly tell me How i can get successful response as before with different end api url. is it different requirements for different url ?

also i need to hit this url through cron after a 5 minutes in future with production link. it should response every time.

see attachment for need to cover end url.
Thanks
1 |1500 characters needed characters left characters exceeded

Up to 8 attachments (including images) can be used with a maximum of 1.0 MiB each and 10.0 MiB total.

ak avatar image
ak answered jerry-white5852 commented
Hi Jerry,

Could you confirm if the application name on RingCentral is: CVMTest2

Per the latest screenshot of your App Analytics:



Your application has 4xx errors  with the below endpoints:

1.) /account
2.) extension/ringout

Make sure you reduce the number of errors on the API calls and you should be able to ' Apply for Graduation'


1 comment
1 |1500 characters needed characters left characters exceeded

Up to 8 attachments (including images) can be used with a maximum of 1.0 MiB each and 10.0 MiB total.

yes application name is CVMSTest2 
after 1 hour i was got successful response from api. now i have a token and need to use it for increase api calls and reduce error percentage.  

$myToken = 'MyToken Which i have got from my last hit';

$callLogRequest = makeRequest( $server, $myToken, "/restapi/v1.0/account/~/extension/~/call-log/", null, "GET", "username=" . $username . "&password=" . $password . "&grant_type=password" );
handleCallLogResult( $callLogRequest );

it gives me OUTPUT 
Preparing API Request... Preparing Non-Auth request... Uh oh, we should have had a records property.     (what it mean?)
 
 what should i need to change and use token for next api hit. otherwise i get response after 1 hour when this token expire ("token_type" : "bearer", "expires_in" : 3600, ) 

0 Likes 0 ·

Developer sandbox tools

Using the RingCentral Phone for Desktop, you can dial or receive test calls, send and receive test SMS or Fax messages in your sandbox environment.

Download RingCentral Phone for Desktop:

Tip: switch to the "sandbox mode" before logging in the app:

  • On MacOS: press "fn + command + f2" keys
  • On Windows: press "Ctrl + F2" keys