Ratchet: How to connect via PHP to it? - php

I am running a Ratchet Server
$app = new Ratchet\App( 'localhost', 8080 );
$app->route( '/api', new API );
$app->run();
It is very easy to connect via JavaScript (and send some messages to the server):
_connection = new WebSocket( "ws://localhost:8080" );
Now I want the same from PHP (connect and send messages), but I dont know how and I dont find any information in the documentation of Ratchet.
Is it somehow possible? I really need to send messages from PHP to the clients (JavaScript), when there is some event on the server.
Edit: I really just need to "fire&forget" some simple message. Nothing fancy.

It works a bit wrong.
After connecting to the server, you can send a message from the client to the server and from the server to the client.
In the Connection Interface is the "send" method.
And call onSubscribe or onPublish method you have $topic variable.
In the $topic is the "broadcasting" method.
You need call:
$conn->send($message); or $topic->brodcasting($message);
If you need send client message after action on site, use example on ratchet (we need install ZMQ)
It works like this:
You create server. This server recieve message from users and recieve message from ZMQ.
Your site publish on ZMQ message
Your server receive message from ZMQ and broadcasting on users
Regards Maxim

Related

configuring stripe webhook, Test webhook error: Unable to connect

So I am trying to implement a stripe webhook to listen to various events. Basically I have my php application running live, say on "http://example.com". I have installed the stripe CLI and have all the classes. I already have created a webhook on stripe dashboard. But when I test a webhook it gives me this error :
"Test webhook error: Unable to connect. Timed out connecting to remote
host"
I am coding on PhpStorm from where I save the files and they get reflected on my website "abc.com". Here is my php file code
require_once 'abc.com/httpdocs/includes/classes/stripe-sdk/vendor/stripe/stripe-php/configuration.php';
require_once 'abc.com/httpdocs/includes/classes/stripe-sdk/vendor/stripe/stripe-php/init.php';
$endpoint_secret = 'whsec_...';
$payload = file_get_contents('php://input');
$event = null;
$sig_header = $_SERVER['HTTP_STRIPE_SIGNATURE'];
try {
$event = \Stripe\Webhook::constructEvent(
$payload, $sig_header, $endpoint_secret
);
} catch(\Stripe\Exception\SignatureVerificationException $e) {
// Invalid signature
echo '⚠️ Webhook error while validating signature.';
http_response_code(400);
exit();
}
// Handle the event
switch ($event->type) {
case 'account.updated':
$paymentIntent = $event->data->object;
break;
default:
// Unexpected event type
error_log('Received unknown event type');
}
http_response_code(200);
I don't think I have to run the php server on a local host. And do I need to "stripe listen .."?
Hoping to get an answer! Thanks in advance :) Let me know if you need any other information.
It looks like whatever is trying to connect to your webhook endpoint URL can’t reach said endpoint. Can you clarify the following…
If you are testing local code:
Make sure your local PHP server is up and running and make a note of the port it is running on. Then, run stripe listen --forward-to http://localhost:<PHP server’s port>. From there you can trigger sample events from a new CLI window like so: stripe trigger invoice.payment_succeeded. Take a look at the docs for this here.
If you are setting up a live endpoint:
I'd first recommend using something like Postman to verify that you can indeed reach the server where your webhook code is deployed. Then, I’d double check the entry you have for that webhook endpoint URL in the dashboard.
If you can pinpoint where you’re stuck, I can provide a more detailed answer.
So it was the problem with my EC2 server permission. I had to add the stripe "ip's" to the Allowed Hosts! That was it :)

XMPP client receiving server messages

I am implementing my custom XMPP PHP library (Packagist repo) and I have trouble fetching messages (that the client sent) from XMPP server.
Library is using PHP sockets to connect to the server, and I am able to fetch a response from server when initially connecting and authenticating. I can also send a message from server to the client, and that part works.
I can't however receive a message.
This is the code I am using when receiving anything from server:
public function getRawResponse()
{
// Wait max 3 seconds before terminating the socket
socket_set_option($this->socket, SOL_SOCKET, SO_RCVTIMEO, ["sec" => $this->options->getSocketWaitPeriod(), "usec" => 0]);
while ($out = socket_read($this->socket, 2048)) {
echo "*** Data ***\n\n";
echo str_replace("><", ">\n<", $out) . "\n\n";
echo "\n\n************\n";
}
}
This while loop is here to fetch all one-batch responses from the server, and it reads from server while it has something to read, otherwise it terminates the connection.
In the main program I am thus doing a do{...}while(true) and putting this method inside so that it doesn't terminate ever. But still I am not getting any response when sending the other way around, from client back to server.
I have found that I needed to send initial empty presence stanza to server
<presence/>
Once I got the server response back, so did the message responses started incoming.

Sending messages from PHP script to multiple Ratchet Websocket apps (via ZMQ Socket)

So, I am running a Ratchet (php) websocket server with multiple routes that connect do multiple Ratchet apps (MessageComponentInterfaces):
//loop
$loop = \React\EventLoop\Factory::create();
//websocket app
$app = new Ratchet\App('ws://www.websocketserver.com', 8080, '0.0.0.0', $loop);
/*
* load routes
*/
$routeOne = '/example/route';
$routeOneApp = new RouteOneApp();
$app->route($routeOne, $routeOneApp, array('*'));
$routeTwo = '/another/route';
$routeTwoApp = new AnotherApp();
$app->route($routeTwo, $routeTwoApp, array('*'));
From here I am binding a ZMQ socket, in order to be able to receive messages sent from php scripts run on the normal apache server.
// Listen for the web server to make a ZeroMQ push after an ajax request
$context = new \React\ZMQ\Context($loop);
$pull = $context->getSocket(\ZMQ::SOCKET_PULL);
$pull->bind('tcp://127.0.0.1:5050'); // Binding to 127.0.0.1 means the only client that can connect is itself
$pull->on('message', array($routeOneApp, 'onServerMessage'));
Finally, the server is started:
//run
$loop->run();
This works perfectly fine as long as i am binding only one of the ratchet apps to the ZMQ socket. However, i would like to be able to separately push messages to both of the Ratchet apps. For this purpose i thought of binding two ZMQ sockets to different routes like:
$pullOne->bind('tcp://127.0.0.1:5050' . $routeOne); // Binding to 127.0.0.1 means the only client that can connect is itself
$pullOne->on('message', array($routeOneApp, 'onServerMessage'));
and
$pullTwo->bind('tcp://127.0.0.1:5050' . $routeTwo); // Binding to 127.0.0.1 means the only client that can connect is itself
$pullTwo->on('message', array($routeTwoApp, 'onServerMessage'));
However, this leads to an error message from ZMQ when binding the second socket, saying the given address is already in use.
So the question is, is there any other way to use routes over a ZMQ socket?
Or should i use other means to distinguish between messages for the separate Ratchet apps, and if so, what would be a good solution?
I thought about binding to 2 different ports, but figured that would be a pretty ugly solution?!
In general in TCP packets are identified by the 4 tuple (sender ip, sender port, receiver ip, receiver port).
When a incoming packet reaches the network layer, it is forwarded to the appropriate application by looking at the receiver ip and port. If you use the same pair for both the apps, it will be impossible for the layer to decide whom to send it to when a connection comes in.
One solution would be to bind a single connection and the write a common handler that looks at the incoming content and then decides (I assume you have some logic) to differentiate the incoming connections to the different instances and then invokes the corresponding handler. The handler can get the connection object and can handle the connection hence forth.
If both your instances are identical and it doesn't matter who gets the request then you can just randomly forward the new connection to any of the handler.
Edit: I have tried to answer the question irrespective of the application type (Racket/ZMQ etc) because the issue you are trying to address is a fundamental one common to any network application.
For this case since you have two apps running and want to listen on the same port, you can have a common handler which can look at the request URL and forward the connection to the appropriate handler.
The request URL can be obtained using
$querystring = $conn->WebSocket->request->getQuery();
Now the clients can connect using
ws://localhost:5050/app1
and
ws://localhost:5050/app2
Your different apps can now handle these connections separately.

socket_write(): unable to write to socket [10053]

I'm using whatsapp api with laravel 5.2
https://github.com/mgp25/Chat-API
And i got this error when i trying to send new message
socket_write(): unable to write to socket [10053]: An established connection was aborted by the software in your host machine.
Send Controller
$massage = "Thanks for subscribe";
Whatsapi::send($massage, function ($send) {
$user = User::Find(1);
$send->to($user->phone);
}
While following this tutorial
I was getting the same error in phperror.log which I have configured in my php.ini. Initially I thought it was due to some firewall issue, but it wasn't.
The problem was, I was running the client first and then the server. Client was probably not able to make a connection with the server when it ran for the first time.
So I resolved it by running the server first and then the client, which can now make a successful web socket connection.
EDIT : This error also comes up when we simply reload the client page without properly terminating the previous connection.

Catching requests made in xampp with fiddler

I have a simple php file which makes SOAP requests. This is running on my local computer with XAMPP as a webserver.
I am trying to catch the request made in fiddler, I can see the request to my php file but that just returns the html for the page. I want to catch the request made when I create the SOAP client to see what is being sent off.
Is there some setting in fiddler I need to change to be able to see the response? Or some sort of proxy I can send my request through so it is visible in fiddler?
You can pass the proxy settings to the SoapClient class like this:
$client = new SoapClient("request.wsdl", array('proxy_host' => "localhost",
'proxy_port' => 8888));
This assumes that fiddler is running on it's default port (8888).

Categories