ConnectyCube / connectycube-reactnative-samples

Chat and Video Chat code samples for React Native, ConnectyCube
https://connectycube.com
Apache License 2.0
125 stars 111 forks source link

Session API request (PHP) #13

Closed godwin12345 closed 4 years ago

godwin12345 commented 4 years ago

Dears,

We are getting this below error while connecting to your api, please check anything missing

Error: {"errors":["Unexpected signature"]}

Php Code:

function callAPI($method, $url, $data){
   $curl = curl_init();

   switch ($method){
      case "POST":
         curl_setopt($curl, CURLOPT_POST, 1);
         if ($data)
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
         break;
      case "PUT":
         curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "PUT");
         if ($data)
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);                              
         break;
      default:
         if ($data)
            $url = sprintf("%s?%s", $url, http_build_query($data));
   }

   // OPTIONS:
   curl_setopt($curl, CURLOPT_URL, $url);
   curl_setopt($curl, CURLOPT_HTTPHEADER, array(
      'Content-Length: ' . strlen($data),
      'Content-Type: application/json',
      //'CB-Token   : '. rand(1000,10000)
   ));
   curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
   curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);

   // EXECUTE:
   $result = curl_exec($curl);
   print_r($result);
   if(!$result){die("Connection Failure");}
   curl_close($curl);
   return $result;
}
$_SESSION["nonce"] = rand(1000,10000);
$has = 'application_id=xxxxx&auth_key=xxxx&nonce="'.$_SESSION["nonce"].'"&timestamp='.time().'';
$has = hash_hmac('sha1',$has,'xxxxx');
//echo strtotime(date('Y-m-d H:i:s')).'<br>';
//echo $_SESSION["nonce"]  .'<br>';
//echo $has.'<br>';//exit;
$data = '{"application_id": "xxx", "auth_key": "xxx", "nonce": "'.$_SESSION["nonce"].'", "timestamp": "'.time().'",  "signature": "'.$has.'"}';
//echo $data;

//echo date('');
callAPI("POST",'https://api.connectycube.com/session',$data);

unset($_SESSION["nonce"]);
DaveLomber commented 4 years ago

Hi @godwin12345

here is a working PHP example on how to generate a signature:

$application_id = 1282;
$auth_key = "wasdiuasd8wex5";
$authSecret = "asdasd786876e";

$nonce = rand();
echo "<br>nonce: " . $nonce;

$timestamp = time();
echo "<br>timestamp: " . $timestamp ."<br>";

$stringForSignature = "application_id=".$application_id."&auth_key=".$auth_key."&nonce=".$nonce."&timestamp=".$timestamp;
echo $stringForSignature."<br>";

$signature = hash_hmac( 'sha1', $stringForSignature , $authSecret);
echo $signature;
godwin12345 commented 4 years ago

Hi @godwin12345

here is a working PHP example on how to generate a signature:

$application_id = 1282;
$auth_key = "wasdiuasd8wex5";
$authSecret = "asdasd786876e";

$nonce = rand();
echo "<br>nonce: " . $nonce;

$timestamp = time();
echo "<br>timestamp: " . $timestamp ."<br>";

$stringForSignature = "application_id=".$application_id."&auth_key=".$auth_key."&nonce=".$nonce."&timestamp=".$timestamp;
echo $stringForSignature."<br>";

$signature = hash_hmac( 'sha1', $stringForSignature , $authSecret);
echo $signature;
godwin12345 commented 4 years ago

Same issue ,

nonce: 1819761929

timestamp: 1570686301

application_id=xx&auth_key=xx&nonce=1819761929&timestamp=1570686301

3eae76fd0bb9b469bff758c43ffdd2a665d1b2c2{"application_id": "xxx", "auth_key": "xx", "nonce": "1819761929", "signature": "3eae76fd0bb9b469bff758c43ffdd2a665d1b2c2", "timestamp": "1570686301"}{"errors":["Unexpected signature"]}

DaveLomber commented 4 years ago

Here is a complete create session request, could you please try it and let us know:

<?php
// Application credentials
DEFINE('APPLICATION_ID', 1292);
DEFINE('AUTH_KEY', "wadasdsadasdsad");
DEFINE('AUTH_SECRET', "BTsdasdsa7823mT");

// endpoints
DEFINE('CB_API_ENDPOINT', "https://api.connectycube.com");
DEFINE('CB_PATH_SESSION', "session.json");

// Generate signature
$nonce = rand();
$timestamp = time(); // time() method must return current timestamp in UTC but seems like hi is return timestamp in current time zone
$signature_string = "application_id=".APPLICATION_ID."&auth_key=".AUTH_KEY."&nonce=".$nonce."&timestamp=".$timestamp;

echo "stringForSignature: " . $signature_string . "<br><br>";
$signature = hash_hmac('sha1', $signature_string , AUTH_SECRET);

// Build post body
$post_body = http_build_query(array(
                'application_id' => APPLICATION_ID,
                'auth_key' => AUTH_KEY,
                'timestamp' => $timestamp,
                'nonce' => $nonce,
                'signature' => $signature
                ));

// $post_body = "application_id=" . APPLICATION_ID . "&auth_key=" . AUTH_KEY . "&timestamp=" . $timestamp . "&nonce=" . $nonce . "&signature=" . $signature;

 echo "postBody: " . $post_body . "<br><br>";
// Configure cURL
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, CB_API_ENDPOINT . '/' . CB_PATH_SESSION); // Full path is - https://api.connectycube.com/session.json
curl_setopt($curl, CURLOPT_POST, true); // Use POST
curl_setopt($curl, CURLOPT_POSTFIELDS, $post_body); // Setup post body
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); // Receive server response

// Execute request and read responce
$responce = curl_exec($curl);

// Check errors
if ($responce) {
        echo $responce . "\n";
} else {
        $error = curl_error($curl). '(' .curl_errno($curl). ')';
        echo $error . "\n";
}

// Close connection
curl_close($curl);
?>
godwin12345 commented 4 years ago

Thank you it's fixed

DaveLomber commented 4 years ago

In a case somebody needs to create a session with user:

<?php
// Application credentials
DEFINE('APPLICATION_ID', 1232);
DEFINE('AUTH_KEY', "adasdsad7128334");
DEFINE('AUTH_SECRET', "778adbdasddasd");

// User credentials
DEFINE('USER_LOGIN', "bobson12");
DEFINE('USER_PASSWORD', "qweqwesd");

// endpoints
DEFINE('CB_API_ENDPOINT', "https://api.connectycube.com");
DEFINE('CB_PATH_SESSION', "session.json");

// Generate signature
$nonce = rand();
$timestamp = time(); // time() method must return current timestamp in UTC but seems like hi is return timestamp in current time zone
$signature_string = "application_id=".APPLICATION_ID."&auth_key=".AUTH_KEY."&nonce=".$nonce."&timestamp=".$timestamp."&user[login]=".USER_LOGIN."&user[password]=".USER_PASSWORD;

echo "stringForSignature: " . $signature_string . "<br><br>";
$signature = hash_hmac('sha1', $signature_string , AUTH_SECRET);

// Build post body
$post_body = http_build_query(array(
                'application_id' => APPLICATION_ID,
                'auth_key' => AUTH_KEY,
                'timestamp' => $timestamp,
                'nonce' => $nonce,
                'signature' => $signature,
                'user[login]' => USER_LOGIN,
                'user[password]' => USER_PASSWORD
                ));

// $post_body = "application_id=" . APPLICATION_ID . "&auth_key=" . AUTH_KEY . "&timestamp=" . $timestamp . "&nonce=" . $nonce . "&signature=" . $signature . "&user[login]=" . USER_LOGIN . "&user[password]=" . USER_PASSWORD;

 echo "postBody: " . $post_body . "<br><br>";
// Configure cURL
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, CB_API_ENDPOINT . '/' . CB_PATH_SESSION); // Full path is - https://api.connectycube.com/session.json
curl_setopt($curl, CURLOPT_POST, true); // Use POST
curl_setopt($curl, CURLOPT_POSTFIELDS, $post_body); // Setup post body
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); // Receive server response

// Execute request and read responce
$responce = curl_exec($curl);

// Check errors
if ($responce) {
        echo $responce . "\n";
} else {
        $error = curl_error($curl). '(' .curl_errno($curl). ')';
        echo $error . "\n";
}

// Close connection
curl_close($curl);
?>
eznix86 commented 4 months ago

[!WARNING] Example using http_build_query will not work right away ! See https://github.com/ConnectyCube/connectycube-flutter-samples/issues/323#issuecomment-1964371070

Be careful when using http_build_query when using user[login]. These characters [] is converted into %5 which is invalid.

Try it here: https://onlinephp.io/

<?php

DEFINE('APPLICATION_ID', 1232);
DEFINE('AUTH_KEY', "adasdsad7128334");
DEFINE('AUTH_SECRET', "778adbdasddasd");
DEFINE('USER_LOGIN', "bobson12");
DEFINE('USER_PASSWORD', "qweqwesd");

$nonce = rand();
$timestamp = time();

$signature_string = "application_id=".APPLICATION_ID."&auth_key=".AUTH_KEY."&nonce=".$nonce."&timestamp=".$timestamp."&user[login]=".USER_LOGIN."&user[password]=".USER_PASSWORD;

$signature = hash_hmac('sha1', $signature_string , AUTH_SECRET);

$array = array(
                'application_id' => APPLICATION_ID,
                'auth_key' => AUTH_KEY,
                'timestamp' => $timestamp,
                'nonce' => $nonce,
                'signature' => $signature,
                'user[login]' => USER_LOGIN,
                'user[password]' => USER_PASSWORD
);

echo http_build_query($array);

Expect to see application_id=1232&auth_key=adasdsad7128334&timestamp=1709548037&nonce=240270234&signature=7f3117e4d197428b31f15ab668c8451b4550836a&user%5Blogin%5D=bobson12&user%5Bpassword%5D=qweqwesd

As you can see [] is encoded. You should wrap: http_build_query($array) with urldecode to get the right request:

// copy the above
// replace with
echo urldecode(http_build_query($array));

And now you will get application_id=1232&auth_key=adasdsad7128334&timestamp=1709548267&nonce=2129941075&signature=9d38ea0fab0da83efe1ee68fb93dcb29473737fd&user[login]=bobson12&user[password]=qweqwesd correctly.

Full code but a bit modern:


<?php
require 'vendor/autoload.php'; // Make sure Guzzle is installed and autoloaded

use GuzzleHttp\Client;

// Application credentials
define('APPLICATION_ID', 1232);
define('AUTH_KEY', "adasdsad7128334");
define('AUTH_SECRET', "778adbdasddasd");

// User credentials
define('USER_LOGIN', "bobson12");
define('USER_PASSWORD', "qweqwesd");

// Endpoints
define('CB_API_ENDPOINT', "https://api.connectycube.com");
define('CB_PATH_SESSION', "session.json");

// Generate signature
$nonce = rand();
$timestamp = time();
$signature_string = http_build_query([
    'application_id' => APPLICATION_ID,
    'auth_key' => AUTH_KEY,
    'nonce' => $nonce,
    'timestamp' => $timestamp,
     'user[login]' => USER_LOGIN,
     'user[password]' => USER_PASSWORD
]);

$signature = hash_hmac('sha1', urldecode($signature_string), AUTH_SECRET); // <---- use urldecode

// Build post body
$post_body = [
    'application_id' => APPLICATION_ID,
    'auth_key' => AUTH_KEY,
    'timestamp' => $timestamp,
    'nonce' => $nonce,
    'signature' => $signature,
    'user' => [
        'login' => USER_LOGIN,
        'password' => USER_PASSWORD
    ]
];

// Initialize Guzzle client
$client = new Client();

// Make POST request
try {
    $response = $client->post(CB_API_ENDPOINT . '/' . CB_PATH_SESSION, [
        'json' => $post_body
    ]);

    // Get response body
    $body = $response->getBody()->getContents();

    // Output response
    echo $body;
} catch (\GuzzleHttp\Exception\RequestException $e) {
    // If request fails, catch the exception and handle it
    echo $e->getMessage();
}
DaveLomber commented 4 months ago

@eznix86 thanks for letting everyone know, noted!