I can connect to the server but cannot read the acknowledgements messages sent by the gcm server. I want to know how to retrieve the XML sent by gcm server.
Here is my code :
<?php
require 'jaxl/jaxl.php';
$sender = 'sender id';
$client = new \JAXL(array(
'jid'=>$sender,
'pass'=>'pass',
'auth_type'=>'PLAIN',
'host' => 'gcm.googleapis.com',
'port' => '5235',
'force_tls' => true,
'strict' => FALSE,
'ssl' => TRUE,
'log_level' => JAXL_DEBUG,
'log_path'=> 'ex.txt'
));
$client->add_cb('on_message_stanza', function($msg) {
echo 'now what!!';
});
$client->add_cb('on_auth_success', function() {
echo 'it should';
global $client;
global $sender;
$namespace = 'google:mobile:data';
$arr=array("hello"=>"world");
$json_data=json_encode($arr,JSON_UNESCAPED_SLASHES);
$arr = array('to'=>'server','message_id'=>'123','data'=>$arr);
$json = json_encode($arr);
$xml = new JAXLXml('gcm',$namespace,array(),$json);
$msg = new JAXLXml('message','',array('id'=>'123'),'');
$msg->cnode($xml);
$client->send($msg);
});
$client->add_cb('on_error_message',function()
{
global $client;
echo 'error<br/>';
_info('got on_error_message cb jid'.$client->full_jid->to_string());
});
In the callback 'on_auth_success', i am sending a message to gcm server directed to my server id, it is sending a negative acknowledgement 'nack' which i can see in the log, but I don't know how to receive that in php code.
The XML received by gcm as per log is :
<message>
<data:gcm xmlns:data="google:mobile:data">{"message_id":"123","from":"someid",
"error_description":"","error":"BAD_REGISTRATION",
"message_type":"nack"}</data:gcm></message>
Oh, I got it, since the response message didn't had any type, I have to add the callback 'on__message', with 2 underscore, because middle value is the value of type attribute of the message which the response don't have.
For an ACK, you can use message type 'normal', so the cb would look like below (I am just logging response):
$client->add_cb('on_normal_message', function($stanza) {
global $client;
// echo back incoming message stanza
//$stanza->to = $stanza->from;
//$stanza->from = $client->full_jid->to_string();
//$client->send($stanza);
_info('Received response******'.$stanza->to_string());
});
Also: in the example, you need to add
$client->start();
For us newbies.
Then it works fine with GCM.
Related
How are you everyone?
My site is based on PHP.
I am new with twilio and building simple project with this.
So what I should implement is to send messages to users using twilio and then receive message from users again in my site.
<?php
// Update the path below to your autoload.php,
// see https://getcomposer.org/doc/01-basic-usage.md
require_once './vendor/autoload.php';
use Twilio\Rest\Client;
// Find your Account SID and Auth Token at twilio.com/console
// and set the environment variables. See http://twil.io/secure
$sid = 'Azzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz';
$token = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';
$twilio = new Client($sid, $token);
$message = $twilio->messages
->create("+12099216581", // to
[
"body" => "This is test",
"from" => "+15324394442",
"statusCallback" => ""
]
);
print($message->sid);
This is for sending message to one users that I am using now..
Then...
<?php
require_once './vendor/autoload.php';
use Twilio\TwiML\MessagingResponse;
$response = new MessagingResponse();
$response->message('This is message 1 of 2.');
$response->message('This is message 2 of 2.');
echo $response;
I think this code will return text message to users with text...
If I am wrong, Please teach me...
So I am trying to do it now, but I can't know how to receive the content of message in my site.
If you are experience in this fields, Please teach me.
Thanks in advance.
You need to set the webhook for that messaging response
smsUrl = 'url';
$response = $client->request("POST", "IncomingPhoneNumbers/$phone_id.json", ['auth' => [$sid, $token], 'form_params' => array("SmsUrl" => $webhook_url, "BundleSid" => $bundle_id)]);
this URL will post the incoming message and reply message
I'm using the AWS SDK for PHP (version 3.52.33, PHP version 7.2.19) and trying to send emails using the Simple Email Service (SES). I have SES configured, and can run the example code successfully. To make my life easier, I wrote a function to send emails (send_email.php):
<?php
// Path to autoloader for AWS SDK
define('REQUIRED_FILE', "/path/to/vendor/autoload.php");
// Region:
define('REGION','us-west-2');
// Charset
define('CHARSET','UTF-8');
// Specify Sender
define('SENDER', 'sender#xxxx.com');
require REQUIRED_FILE;
use Aws\Ses\SesClient;
use Aws\Ses\Exception\SesException;
function send_email($htmlBody,$textBody,$subject,$recipient) {
$access_key = 'accessKey';
$secret_key = 'secretKey';
$ret_array = array('success' => false,
'message' => 'No Email Sent'
);
$client = SesClient::factory(array(
'version' => 'latest',
'region' => REGION,
'credentials' => array(
'key' => $access_key,
'secret' => $secret_key
)
));
try {
$result = $client->sendEmail([
'Destination' => [
'ToAddresses' => [
$recipient,
],
],
'Message' => [
'Body' => [
'Html' => [
'Charset' => CHARSET,
'Data' => $htmlBody,
],
'Text' => [
'Charset' => CHARSET,
'Data' => $textBody,
],
],
'Subject' => [
'Charset' => CHARSET,
'Data' => $subject,
],
],
'Source' => SENDER,
]);
$messageId = $result->get('MessageId');
$ret_array['success'] = true;
$ret_array['message'] = $messageId;
echo("Email sent! Message ID: $messageId" . "\n");
} catch (SesException $error) {
echo("The email was not sent. Error message: " . $error->getAwsErrorMessage() . "\n");
$ret_array['message'] = $error->getAwsErrorMessage();
}
return $ret_array;
}
This works when called from a simple testing script (test.php) in a terminal:
<?php
ini_set('display_errors','On');
error_reporting(E_ALL | E_STRICT);
require_once './send_email.php';
$email = 'test#email.com';
$htmlbody = 'test';
$txtbody = 'test';
$subject = 'test email';
$success = send_email($htmlbody,$txtbody,$subject,$email);
I get output like:
[~]$ php test.php
Email sent! Message ID: 0101016c8d665369-027be596-f8da-4410-8f09-ff8d7f87181b-000000
which is great. However, I'm doing this to send automated emails from a website (new user registration, password resets, ...) and when I try to use send_email from within a larger script I get a ~%50 success rate (when using a constant email address). Either it works and everything is fine, or it fails without an error message:
The email was not sent. Error message:
I know that an exception is being thrown, as I'm ending up in the catch statement, but I don't know how to get more information about what went wrong since there isn't a message associated with the exception. I've tried expanding what I look for in the catch block:
<snip>
catch (SesException $error) {
echo("The email was not sent. Error message: " . $error->getAwsErrorMessage() . "\n");
$ret_array['message'] = $error->getAwsErrorMessage();
$ret_array['errorCode'] = $error->getAwsErrorCode();
$ret_array['type'] = $error->getAwsErrorType();
$ret_array['response'] = $error->getResponse();
$ret_array['statusCode'] = $error->getStatusCode();
$ret_array['isConnectionError'] = $error->isConnectionError();
}
but when it fails everything is NULL except isConnectionError = false. Anecdotally, it is totally random -- I haven't been able to discern a pattern at all as to when it works and when it fails.
One other potentially relevant note: if I loop the email sending so a new user gets 10 emails, either they all succeed or they all fail.
So, does anyone have any suggestions as to what might be going wrong, or other steps I could take to help diagnose why this is happening?
For anyone running in to a similar issue in the future, I eventually came up with two solutions:
Initially, I gave up hope on the AWS SDK and switched to using PHPMailer which avoided the issue (though I believe at the cost of a loss in performance).
The real issue (I'm fairly certain now) was a mismatch in the versions of PHP between my CLI and what the webserver was providing. This question got me thinking about how that might be the issue. By updating the version of cURL and PHP that the webserver was using, I resolved the issue.
ini_set('max_execution_time', 3000);
require 'Services/Twilio.php';
$version = "2010-04-01";
$sid = 'xxxxxx';
$token = 'xxxxxx';
$phonenumber = 'xxxxxxxxxx';
$client = new Services_Twilio($sid, $token, $version);
try {
$call = $client->account->calls->create($phonenumber, "3104200693", "http://demo.twilio.com/docs/voice.xml", array(
"Method" => "GET",
"StatusCallback" => "http://localhost/twilio/call-response.php",
"StatusCallbackMethod" => "GET",
"StatusCallbackEvent" => array("initiated", "ringing", "answered", "completed"),
"IfMachine" => "Continue",
));
//header("Location: http://localhost/twilio/call-response.php");
} catch (Exception $e) {
echo 'Error: ' . $e->getMessage();
}
This is my twilio code to call a number, i am successfully calling with this, but i want to store response in database like call completed or not and if answered then who answered call human or machine.
Please help.
The Twilio servers will send an HTTP request to the URL given as StatusCallback. Quite obviously, hopefully, Twilio cannot contact your localhost. 1) your computer is probably not physically reachable from outside your network, and 2) localhost is something different for everyone.
You need to provide a URL which is publicly accessible from the internet. That means you either need to run your code in a server, or you use a service like http://ngrok.com to establish a tunnel to your local machine during development.
I dont think "StatusCallback" => "http://localhost/twilio/call-response.php" will make you get call response. You should give a server url.
For example
"StatusCallback" => "http://example.com/twilio/call-response.php"
In call-response.php,
<?php
file_put_contents(__DIR__."/status_log.txt", json_encode($_REQUEST));
// twilio call status and other sata will be written to this file. Please check this file after call.
// I am giving because i dont know correct twilio returning params
?>
More info here
I am trying to send direct message with JAXL in the name of a user (authenticated application with xmpp_login). In the jaxl facebook chat example there exist a message echo structure, still it redirects received XMPPStanza to the sender. But trying to generate XMPPStanza to send performs nothing with
$client->send($stanza);
here is my XMPPStanza initialization code
$stanza = new XMPPMsg(null);
$stanza->from = $client->full_jid->to_string();
$stanza->to = 'example-facebook-id#chat.facebook.com';
$stanza->type = 'chat';
$stanza->body = 'test message';
$client->send($stanza);
To sum it up, How can i send message from server in the name of the client via JAXL?
EDIT
I forgot to mention i am using JAXL v3 and thought about appending full code and system configuration would be more helpful.
<?php
define('FACEBOOKBOT_PHP', TRUE);
// Include XMPP Engine 'JAXL'
// Path might be alter in time.
// require_once ROOT_DIR.'/JAXL/jaxl.php';
require_once '/var/www/JAXL/jaxl.php';
require_once '/var/www/JAXL/xmpp/xmpp_msg.php';
function sendMessage($client)
{
// // $stanza = new XMPPMsg(null);
// // $stanza->from = $client->full_jid->to_string();
// // $stanza->to = $to;
// // $stanza->type = 'chat';
// // $stanza->body = 'test message 1';
// // foreach ($stanza->childrens as $value)
// // {
// // $value->ns = 'jabber:client';
// // }
// // $client->send($stanza);
$msg = new XMPPMsg(array('to'=>'example-user-id-and-it-got-to-work-i-checked-on-below-echo-stanza#chat.facebook.com'), 'test message');
$client->send($msg);
_info("test messages sent");
}
$user = 'gokhanbarisaker'; // my user id (www.facebook.com/gokhanbarisaker)
// $user = $argv[1]; // User name or facebook id
$jidSuffix = '#chat.facebook.com'; // Facebook chat account suffix
$appKey = 'example-app-key'; // Taken from developer.facebook.com
// $appKey = $argv[2]; // Facebook app token
$accessToken = 'example-access-token'; // Facebook user token - tried both app token tool on developer.facebook.com and token provided after user login both posses xmpp-login permission
// $accessToken = $argv[3];
$client = new JAXL( array( // (required) credentials
'jid' => $user.$jidSuffix,
'fb_app_key' => $appKey,
'fb_access_token' => $accessToken,
// force tls (facebook require this now)
'force_tls' => true,
// (required) force facebook oauth
'auth_type' => 'X-FACEBOOK-PLATFORM',
// (optional)
//'resource' => 'resource',
'log_level' => JAXL_INFO,
'priv_dir' => '.'
));
$client->add_cb('on_auth_success', function()
{
global $client;
_info("got on_auth_success cb, jid ".$client->full_jid->to_string());
$client->set_status("available!", "dnd", 10);
// Here is the part where i tried to send message. In addition, i tried to call this function wherever i can on the code.
sendMessage($client);
});
$client->add_cb('on_auth_failure', function($reason)
{
global $client;
$client->send_end_stream();
_info("got on_auth_failure cb with reason $reason");
});
$client->add_cb('on_chat_message', function($stanza)
{
global $client;
// echo back incoming message stanza
$stanza->to = $stanza->from;
$stanza->from = $client->full_jid->to_string();
$client->send($stanza);
_info("echo message sent");
sendMessage($client);
});
$client->add_cb('on_disconnect', function()
{
_info("got on_disconnect cb");
});
$client->start();
echo "done\n";
?>
System configuration:
Ubuntu 12.04.01 LTS
Apache 2.2.22
PHP 5.3.10
Terminal command to execute;
> php facebookbot.php
A few things you should try and see if they help you debug this:
Set 'log_level' => JAXL_DEBUG, and check logs to see what exactly Jaxl sends out to facebook. If you can, update the question with outgoing stanza so that we can verify whats really wrong here.
If you are using facebook id's to send out messages, remember you need to send message 'to'=>'-4#chat.facebook.com'. Note the negative sign.
Facebook is quite smart in catching spammers in their network. If you are trying to send out too many similar messages within a short time, facebook servers will reply back with appropriate error to the bot (they can even disable your chat account temporarily). Check the logs to see if you are gettings any such error response back from the facebook servers.
try:
$msg = new XMPPMsg(array('to'=>'example-facebook-id#chat.facebook.com'), 'test message');
$client->send($msg);
I am going crazy for last two days, i cannot make connection on NodeJS client with durable exchange and durable queue.
So PHP code creates and send message:
<?php
$connection = new AMQPConnection(array(
'host' => 'localhost',
'vhost' => 'bvh',
'port' => 5672,
'login' => 'bizneus',
'password' => 'lozinkus'
));
//$connection = new AMQPConnection();
$connection->connect();
if (!$connection->isConnected()) {
die('Not connected :(' . PHP_EOL);
}
// Open Channel
$channel = new AMQPChannel($connection);
// Declare exchange
$exchange = new AMQPExchange($channel);
$exchange->setName('biznea_e_1');
$exchange->setType('fanout');
$exchange->setFlags(AMQP_DURABLE);
$exchange->declare();
// Create Queue
$queue = new AMQPQueue($channel);
$queue->setName('notify');
$queue->setFlags(AMQP_DURABLE);
$queue->declare();
$message = $exchange->publish(json_encode($s), 'kljuc');
if (!$message) {
echo 'Message not sent', PHP_EOL;
} else {
echo 'Message sent!', PHP_EOL;
}
if ($connection->isConnected()) {
$connection->disconnect();
}
On screen it says that messege is sent.
Next thing is NodeJS client, which should get messages, but it can't:
var amqp = require('amqp');
var conParam = {
host: 'localhost',
port: 5672,
login: 'bizneus',
password: 'lozinkus',
vhost: 'bvh'
}
var connection = amqp.createConnection(conParam);
connection.on('ready', function(){
var exchange = connection.exchange('biznea_e_1');
var queue = connection.queue('notify');
queue.bind('biznea_e_1', 'kljuc');
queue.subscribe( {ack:true}, function(message){
var dj = JSON.parse(message.data.toString());
console.log(JSON.stringify(dj));
queue.shift();
});
});
but I get this error
events.js:66
throw arguments[1]; // Unhandled 'error' event
^
Error: PRECONDITION_FAILED - cannot redeclare exchange 'biznea_e_1' in vhost 'bvh' with different type, durable, internal or autodelete value
at Exchange._onMethod (/home/zijad/node_modules/amqp/amqp.js:1824:15)
at Exchange.Channel._onChannelMethod (/home/zijad/node_modules/amqp/amqp.js:1365:14)
at Connection._onMethod (/home/zijad/node_modules/amqp/amqp.js:922:28)
at AMQPParser.self.addListener.parser.onMethod (/home/zijad/node_modules/amqp/amqp.js:797:12)
at AMQPParser._parseMethodFrame (/home/zijad/node_modules/amqp/amqp.js:442:10)
at frameEnd (/home/zijad/node_modules/amqp/amqp.js:187:16)
at frame (/home/zijad/node_modules/amqp/amqp.js:172:14)
at AMQPParser.header [as parse] (/home/zijad/node_modules/amqp/amqp.js:159:14)
at AMQPParser.execute (/home/zijad/node_modules/amqp/amqp.js:231:21)
at Connection.<anonymous> (/home/zijad/node_modules/amqp/amqp.js:837:12)
I tried to remove var exchange = connection.exchange('biznea_e_1'); that line but than it cannot declare queue.
I just want to send messages from PHP to NodeJS deamon and that is all!
Help :)
Try this: In the node.js code, declare the exchanges and queues with EXACTLY the same parameters as you did in your PHP code. e.g. durable. This may solve your problem.
Cheers!
Looks like you are trying to create the exchange 'biznea_e_1' again in the node.js code. It is already created by the php code. Try only to subscribe.