Unexpected Signature while obtaining user session token - connectycube

I am using Connecty Cube and following the documentation to get a user session token, however the response is
Client error: POST https://api.connectycube.com/session resulted in a 422 Unprocessable Entity response:
{"errors":["Unexpected signature"]}
I am using the below code to get the session token.
use GuzzleHttp\Psr7;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\ClientException;
use GuzzleHttp\Exception\TransferException;
$client = new Client();
// Create Connecty Cube Session
$application_id = env('CUBE_APPLICATION_ID');
$auth_key = env('CUBE_APPLICATION_KEY');
$timestamp = time();
$nonce = substr($timestamp, 0, 4);
$response = $client->request('POST', 'https://api.connectycube.com/session', [
'form_params' => [
'application_id' => $application_id,
'auth_key' => $auth_key,
'timestamp' => $timestamp,
'nonce' => $nonce,
'signature' => hash_hmac('sha1',
http_build_query([
'application_id' => $application_id,
'auth_key' => $auth_key,
'nonce' => $nonce,
'timestamp' => $timestamp,
]),
env('CUBE_APPLICATION_SECRET')
),
"user" => [
"email" => <email address>,
"password" => <password>
]
]
]);
$contents = json_decode($response->getBody()->getContents(), true);
var_dump($contents);
Please help me to figure out where I am going wrong. Thank You!

// Application credentials
DEFINE('APPLICATION_ID', 1204);
DEFINE('AUTH_KEY', "HhBrEq4BRgT4R8S");
DEFINE('AUTH_SECRET', "TkpdsDSSWyD6Sgb");
// 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);

Related

How to send push to specific member using SNS topic?

I am using AWS SNS to send a push notification, right now i am using publish method of aws-php-sdk to send push specific device. My requirement is sent push to thousands of members within 30 seconds. When i used publish method it takes 5min to send 1000 users.
I have read about topic it sends multiple members at once, but my scenario is i want to send push to specific users, not all topic users.
For example, i register 10,000 members in one topic, but from this 10,000 some time i am sending 9000, sometimes 1000 members.
So anyone has an idea how to send push using topic but specific members only.
I also think another case, every time i create new topic and register member to this topic and then send a message to him and then delete topic, but here every time when register member it is also taking time. So if you have an idea to register multiple members at once then it will also be helpful for me.
Below is my current code to send push.
$arn = "user arn";
$sns = new Aws\Sns\SnsClient(array(
'version' => 'latest',
'key' => my_aws_key,
'secret' => aws_secret,
'region' => region,
'profile' => profile_name,
'debug' => false,
'http' => array('verify' => false)
));
$appArn = "application arn";
$sns->publish(array('Message' => '{ "GCM": "{\"data\": { \"message\": \" This is my message \"} }"}',
'MessageStructure' => 'json',
'TargetArn' => $arn
));
I would recommend to use publishAsync() method.
$userArnCollection = array(
'arn:XXX',
'arn:YYY',
'arn:ZZZ',
);
$sns = new Aws\Sns\SnsClient(array(
'version' => 'latest',
'key' => my_aws_key,
'secret' => aws_secret,
'region' => region,
'profile' => profile_name,
'debug' => false,
'http' => array('verify' => false)
));
foreach ($userArnCollection as $userArn) {
$sns->publishAsync(array(
'Message' => '{ "GCM": "{\"data\": { \"message\": \" This is my message \"} }"}',
'MessageStructure' => 'json',
'TargetArn' => $userArn
));
}
EDIT
Example with promise handling
$userArnCollection = array(
'arn:XXX',
'arn:YYY',
'arn:ZZZ',
);
$sns = new Aws\Sns\SnsClient(array(
'version' => 'latest',
'key' => my_aws_key,
'secret' => aws_secret,
'region' => region,
'profile' => profile_name,
'debug' => false,
'http' => array('verify' => false)
));
$promises = array();
foreach ($userArnCollection as $userArn) {
$promises[] = $sns->publishAsync(array(
'Message' => '{ "GCM": "{\"data\": { \"message\": \" This is my message \"} }"}',
'MessageStructure' => 'json',
'TargetArn' => $userArn
));
}
$results = \GuzzleHttp\Promise\unwrap($promises);
After trying many solutions i am able to send thousands of notification within one minute, here i am showing code how i do it, I have done with php multicurl functionality, so i execute multiple parallel processes and all process send notification simultaneously.
Define multi curl and prepare URL to send notification
Suppose i have 5,000 members and i have array of it's token and other member details $device_type_ids_arr
I part of all member to 500 bunch, so each time curl execute it sends notification to 500 members
$_datas = array_chunk($device_type_ids_arr, 500);
/*initialise multi curl*/
$mh = curl_multi_init();
$handles = array();
/* Perform loop for each 500 members batch */
foreach ($_datas as $batchPart) {
$ch = curl_init();
$postData['devices'] = $batchPart;
$postData['push_content'] = $push_content;
$data_string = json_encode($postData);
curl_setopt($ch, CURLOPT_URL, base_url() . "EmailPipe/sendNotification/"); //your URL to call amazon service (Explain below)
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_USERAGENT, 'User-Agent: curl/7.39.0');
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length:' . strlen($data_string))
);
curl_multi_add_handle($mh, $ch);
$handles[] = $ch;
}
// execute requests and poll periodically until all have completed
$isRunning = null;
do {
curl_multi_exec($mh, $isRunning);
} while ($isRunning > 0);
/* Once all execution are complete remove curl handler */
foreach ($handles as $ch) {
curl_multi_remove_handle($mh, $ch);
}
/* Close multi curl */
curl_multi_close($mh);
Function which is received curl request and send notification
function sendCurlSignal() {
require_once APPPATH . 'libraries/aws-sdk/aws-autoloader.php';
$pipeArr = json_decode(file_get_contents('php://input'), true);
$push_content = $pipeArr["push_content"];
$device_id_arr = $pipeArr["devices"];
$sns = new Aws\Sns\SnsClient(array(
'version' => 'latest',
'key' => "Amazon key",
'secret' => "Amazon secret",
'region' => "region like eu-west-1",
'profile' => "Amazon account user",
'debug' => false,
'http' => array('verify' => false)
));
$appArn = "SNS application arn";
$promises = $results = $retArr = array();
foreach ($device_id_arr as $key => $device_detail) {
$arn = $device_detail['arn']; /* SNS ARN of each device */
$token = $device_detail['token_id']; /* Registered token */
$userid = $device_detail['member_id'];
/* If you don't have arn then add arn for specific token in amazon */
if (empty($arn)) {
try {
$updatedArn = $sns->createPlatformEndpoint(array('PlatformApplicationArn' => $appArn, 'Token' => $token));
$arn = $newArn = isset($updatedArn['EndpointArn']) ? $updatedArn['EndpointArn'] : "";
//update member detail with new arn
if ($newArn != "" && $userid != "" && $token != "") {
/* You can update arn into database for this member */
}
} catch (Exception $e) {
/* Get error if any */
$errorMsg = $e->getMessage();
$newFile = fopen("error_arn_fail.txt", "a+");
fwrite($newFile, "Member Id:" . $userid . "\r\nToken:" . $token . "\r\n" . $errorMsg . "\r\n");
fclose($newFile);
}
}
if (!empty($arn)) {
try {
$promises[$userid] = $sns->publishAsync(array(
'Message' => '{ "GCM": "{\"data\": { \"message\": \"' . $push_content . '\" } }"}',
'MessageStructure' => 'json',
'TargetArn' => $arn
));
$promises[$userid]->arn = $arn;
$promises[$userid]->token = $token;
} catch (Exception $e) {
$errorMsg = $e->getMessage();
$newFile = fopen("error_async_fail_signal.txt", "a+");
fwrite($newFile, $errorMsg . "\r\n");
fclose($newFile);
}
}
}
/* Broadcast push notification */
$results = \GuzzleHttp\Promise\settle($promises)->wait(TRUE);
/* if you want to get result of broadcast and sent message id then do following */
foreach ($results as $key => $value) {
if (isset($value['reason'])) {
/* Reason come in case of fail */
$message = $value['reason']->getMessage();
$token = (isset($promises[$key]->token)) ? $promises[$key]->token : "";
$arn = (isset($promises[$key]->arn)) ? $promises[$key]->arn : "";
if (empty($arn) || empty($token) || empty($key)) {
$newFile = fopen("error_empty_detail_result.txt", "a+");
fwrite($newFile, "Member Id:" . $key . "\r\nArn:" . $arn . "\r\nToken:" . $token . "\r\n");
fclose($newFile);
}
/* Handle error */
if (strpos($message, "Endpoint is disabled") !== false && $token != "" && $arn != "") {
try {
$res = $sns->setEndpointAttributes(array(
'Attributes' => array("Token" => $token, "Enabled" => "true"),
'EndpointArn' => $arn
));
} catch (Exception $e) {
$errorMsg = $e->getMessage();
$newFile = fopen("error_endpoint_disable.txt", "a+");
fwrite($newFile, "Member Id:" . $key . "\r\nArn:" . $arn . "\r\nToken:" . $token . "\r\n" . $errorMsg . "\r\n");
fclose($newFile);
}
}
if (strpos($message, "No endpoint found for the target arn specified") !== false && $token != "") {
try {
$updatedArn = $sns->createPlatformEndpoint(array('PlatformApplicationArn' => $appArn, 'Token' => $token));
$arn = $newArn = isset($updatedArn['EndpointArn']) ? $updatedArn['EndpointArn'] : "";
//update member detail with new arn
if ($newArn != "" && !empty($key) && $token != "") {
/* You can update arn into database for this member */
}
} catch (Exception $e) {
$errorMsg = $e->getMessage();
$newFile = fopen("error_arn_fail.txt", "a+");
fwrite($newFile, "Member Id:" . $key . "\r\nToken:" . $token . "\r\n" . $errorMsg . "\r\n");
fclose($newFile);
}
}
/* After handle error resed notification to this users */
if (!empty($arn)) {
try {
$publishRes = $sns->publish(array(
'Message' => '{ "GCM": "{\"data\": { \"message\": \"' . $push_content . '\" } }"}',
'MessageStructure' => 'json',
'TargetArn' => $arn
));
$retArr[$key] = $publishRes->get("MessageId");
} catch (Exception $e) {
$errorMsg = $e->getMessage();
$newFile = fopen("error_push_not_sent.txt", "a+");
fwrite($newFile, "Member Id:" . $key . "\r\nARN:" . $arn . "\r\nToken:" . $token . "\r\n" . $errorMsg . "\r\n");
fclose($newFile);
}
}
} else {
$retArr[$key] = $results[$key]['value']->get("MessageId");
}
}
/* All member data get into one array to perform database operation */
if (isset($retArr) && !empty($retArr)) {
/* in $retArr you get each member amazon message id */
}
}

Activation form does not fully work

i hope someone can help with this. At one point i thought i had this working but cannot figure out why it is not.
The script below does everything but include the Zend_Json::encode. It saves the user in the database it emails the person a link, however the link does not have the encryption included with it.
thanks for your help!
public function contribjoinAction()
{
$request = $this->getRequest();
$conn = XXX_Db_Connection::factory()->getMasterConnection();
$userDao = XXX_Model_Dao_Factory::getInstance()->setModule('core')->getUserDao();
$userDao->setDbConnection($conn);
if ($request->isPost()) {
$fullname = $request->getPost('full_name');
$username = $request->getPost('username');
$password = $request->getPost('password');
$password2 = $request->getPost('confirmPassword');
$email = $request->getPost('email');
$islegal = $request->getPost('islegal');
$user = new Core_Models_User(array(
'user_name' => $username,
'password' => $password,
'full_name' => $fullname,
'email' => $email,
'is_active' => 0,
'created_date' => date('Y-m-d H:i:s'),
'logged_in_date' => null,
'is_online' => 0,
'role_id' => 2,
'islegal' => $islegal,
));
$id = $userDao->add($user);
$templateDao = XXX_Model_Dao_Factory::getInstance()->setModule('mail')->getTemplateDao();
$templateDao->setDbConnection($conn);
$template = $templateDao->getByName(Mail_Models_Template::TEMPLATE_ACTIVATE_CONTRIBUTOR);
if ($template == null) {
$message = sprintf($this->view->translator('auth_mail_template_not_found'), Mail_Models_Template::TEMPLATE_ACTIVATE_CONTRIBUTOR);
throw new Exception($message);
}
$search = array(Mail_Models_Mail::MAIL_VARIABLE_EMAIL, Mail_Models_Mail::MAIL_VARIABLE_USERNAME);
$replace = array($user->email, $user->user_name);
$subject = str_replace($search, $replace, $template->subject);
$content = str_replace($search, $replace, $template->body);
/**
* Replace the reset password link
* #TODO: Add security key?
*/
$encodedLink = array(
'email' => $email,
'user_name' => $username,
);
$encodedLink = base64_encode(urlencode(Zend_Json::encode($encodedLink)));
$link = $this->view->serverUrl() . $this->view->url(array('encoded_link' => $encodedLink), 'core_user_emailactivate');
$content = str_replace('%activate_link%', $link, $content);
/**
* Get mail transport instance
*/
$transport = Mail_Services_Mailer::getMailTransport();
$mail = new Zend_Mail();
$mail->setFrom($template->from_mail, $template->from_name)
->addTo($user->email, $user->user_name)
->setSubject($subject)
->setBodyHtml($content)
->send($transport);
if ($id > 0) {
$this->_helper->getHelper('FlashMessenger')
->addMessage($this->view->translator('user_join_success'));
$this->_redirect($this->view->serverUrl() . $this->view->url(array(), 'core_user_contribjoin'));
}
}
}
I have found the error. I somehow did not put the variable encoded_link into the .ini file for that module under routes.

Vtiger Webform issue

I am trying to store data in vtiger leads module. i can send variable via file_get_contents()
but its not working . here is my code
$moduleName = $_POST['moduleName'];
$company = $_POST['company'];
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$website = $_POST['website'];
$phone = $_POST['phone'];
$email = $_POST['email'];
$city = $_POST['city'];
$state = $_POST['state'];
$code = $_POST['code'];
$post = http_build_query(array(
"firstname" => "$firstname",
"lastname" => "$lastname",
"website"=>"$website",
"phone"=>"$phone",
"email"=>"$email",
"city"=>"$city",
"state"=>"$state",
"code"=>"$code",
"moduleName" => "$moduleName",
"company " => "$company",
));
$context = stream_context_create(array("http"=>array(
"method" => "POST",
"header" => "Content-Type: application/x-www-form-urlencoded\r\n" .
"Content-Length: ". strlen($post) . "\r\n",
"content" => $post,
)));
$page = file_get_contents("http://vtiger.com/modules/Webforms/post.php", false, $context);
Please help me.
Use web forms correctly, in vtiger 5.4 you can create webforms ealsily with its interface. oru user vtiger webservices to create,edit,delte data

I'm getting 'The request must contain the parameter Signature' although I'm actually supplying it

I'm trying the AWS Product Advertisement API in PhP.
Here is the PhP code that I've copied from net.
function callSOAPFunction($function, $array){
$timeStamp = gmdate("Y-m-d\TH:i:s\Z");
//service is always the same, $function is operation
$string = 'AWSECommerceService'.$function.$timeStamp;
$signature = base64_encode(hash_hmac("sha256", $string, 'MySecretKey', True));
$params = array('Service' => 'AWSECommerceService',
'AssociateTag' => 'Wassup?',
**'Signature' => $signature,**
'AWSAccessKeyId' => 'MyKey'
'Request' => array($array),
'Timestamp' => $timeStamp
);
$client = new
SoapClient("http://webservices.amazon.com/AWSECommerceService/AWSECommerceService.wsdl",
array('exceptions' => 0));
return $client->__soapCall($function, array($params));
}
$array = array('Operation' => 'ItemSearchRequest',
'ItemPage' => 3,
'SearchIndex' => 'DVD',
'ResponseGroup' => 'Large',
'Keywords' => 'Karate');
$result = callSOAPFunction("ItemSearch", $array);
Although I'm including the signature parameter, I'm still getting the error.

Could you explain me how i get news tickers from facebook into my app?

In my app. i get user's feed and user's news ticker. With first i have no questions, but with the second i have some troubles. How a can access to the ticker using php?
From my experience the ticker is just a shortened version of a users news feed using "story"
Here is a sample batch request "with only 1 request" i use to display ticker info from a users news feed.
user / home https://developers.facebook.com/docs/reference/api/user/#home
filtering results based on user lists https://developers.facebook.com/docs/reference/fql/stream_filter/
API Request:
<?php
$Ticker = $facebook->api('/me/home?fields=id,story%26'.$access_token.'');
echo '<pre>';
print_r($Ticker);
echo '</pre>';
?>
Batch API Request:
<?php
$Ticker = '/me/home?fields=id,story%26'.$access_token.'';
$queries = array(
array('method' => 'GET', 'relative_url' => ''.$Ticker.'')
);
$batchResponse = $facebook->api('?batch='.json_encode($queries), 'POST');
$MEticker = json_decode($batchResponse[0]['body'], true);
echo '<pre>';
print_r($MEticker);
echo '</pre>';
?>
Thank you very much! I almost understood! :)
Another way to get ticker:
<?php
$res = $app->facebook->get_friends_news('me',$access_token);
print_r($res);
print "Ticker:"."\r\n";
foreach ($res['data'] as $value){
if (isset($value['story'])){
echo $value['story']."\r\n";
}
}
?>
where
<?php
function get_friends_news($user_id ='me',$token)<br/>
{
$url = $this->url_base_graph.$user_id.'/home?access_token='.$token;
$res = json_decode($this->httpQuery($url),true);
return $res;
}
?>
And:
<?php
function httpQuery($url, $method = 'GET', $post_data = array(), $CONNECTTIMEOUT = 30) {
// type of query
if ($method == 'POST')
$method = 1;
elseif ($method == 'GET')
$method = 0;
if ($this->access_token != false)
$url = $url . 'access_token=' . $this->access_token;
//echo $url;
//traverse array and prepare data for posting (key1=value1)
if (count($post_data)) {
foreach ($post_data as $key => $value) {
$post_items[] = $key . '=' . $value;
}
//create the final string to be posted using implode()
$post_string = implode('&', $post_items);
} else {
$post_string = '';
}
// echo $url;
//create cURL connection
$curl_connection = curl_init($url);
//set options
curl_setopt($curl_connection, CURLOPT_CONNECTTIMEOUT, $CONNECTTIMEOUT);
curl_setopt($curl_connection, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)");
curl_setopt($curl_connection, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl_connection, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl_connection, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($curl_connection, CURLOPT_URL, $url);
curl_setopt($curl_connection, CURLOPT_POST, $method);
//set data to be posted
if ($post_string != '') {
curl_setopt($curl_connection, CURLOPT_POSTFIELDS, $post_string);
}
//perform our request
$result = curl_exec($curl_connection);
//close the connection
curl_close($curl_connection);
return $result;
}?>