Laravel WebSockets. Issue with App key. How it fix? - php

I can start websocket on
php artisan websockets:serve
But when i try to open my site page it says that
New connection opened for app key websocketkey.
Exception `BeyondCode\LaravelWebSockets\WebSockets\Exceptions\UnknownAppKey` thrown: `Could not find app key `websocketkey`.`
Unknown app id: exception `BeyondCode\LaravelWebSockets\WebSockets\Exceptions\UnknownAppKey` thrown: `Could not find app key `websocketkey`.`.
Connection id sending message {"event":"pusher:error","data":{"message":"Could not find app key `websocketkey`.","code":4001}}
Connection id closed.
Exception `ErrorException` thrown: `Undefined property: Ratchet\Server\IoConnection::$app`
In config/websockets.php i got app key from env
'apps' => [
[
'id' => env('PUSHER_APP_ID'),
'name' => env('APP_NAME'),
'key' => env('PUSHER_APP_KEY'),
'secret' => env('PUSHER_APP_SECRET'),
'enable_client_messages' => true,
'enable_statistics' => true,
],
],
I don't understand where getting websocketkey from. Because there are no such values in env.
I try php artisan config:clear and it didn't help.
Please share who knows how to solve this and why it happens at all.

Restarting the websocket worked for me, while php artisan config:clear did not.

Related

BroadcastException Pusher 404 Laravel/Lumen

The problem
For a Lumen 8 project we are trying to implement Pusher. We got it working locally in a Docker environment, but when we turn to Kubernetes it isn't working anymore. We get this error:
[2021-05-27 17:56:36] production.ERROR: Pusher error: 404 NOT FOUND {"exception":"[object] (Illuminate\\Broadcasting\\BroadcastException(code: 0): Pusher error: 404 NOT FOUND at /var/www/html/vendor/illuminate/broadcasting/Broadcasters/PusherBroadcaster.php:122)
Which means it throws on this piece of code:
114: if ($this->pusherServerIsVersionFiveOrGreater()) {
115: $parameters = $socket !== null ? ['socket_id' => $socket] : [];
116:
117: try {
118: $this->pusher->trigger(
119: $this->formatChannels($channels), $event, $payload, $parameters
120: );
121: } catch (ApiErrorException $e) {
122: throw new BroadcastException(
123: sprintf('Pusher error: %s.', $e->getMessage())
124: );
125: }
126: }
The way it works is like this. The user triggers a function, which creates a Job which will be queued in Redis. Then when the Job is finished, the Event gets triggered.
The Jobs work, except for sending the events, which results in above error.
What we've tried
We tried adding Curl options to the Pusher broadcasting connection:
'pusher' => [
'driver' => 'pusher',
'key' => env('PUSHER_APP_KEY'),
'secret' => env('PUSHER_APP_SECRET'),
'app_id' => env('PUSHER_APP_ID'),
'options' => [
'cluster' => env('PUSHER_APP_CLUSTER'),
'encrypted' => false,
'curl_options' => [
CURLOPT_SSL_VERIFYHOST => 0,
CURLOPT_SSL_VERIFYPEER => 0,
]
],
],
And we tried changing the 'encrypted' option to true/false. None of these worked.
We tried to clear the cache with php artisan cache:clear as well as clearing it by hand rm -r storage/framework/cache.
We tried composer dump-autoloadand composer update.
We triple checked the Environment variables, but it still isn't working.
If you need any more info, let me know!
Okay, so this was a serious case of PEBKAC. Apparently we were using global .env variables but with a wrong name for the PUSHER APP ID. It should be fixed now that we changed the name of it.
So if you get the 404 error, make sure that your app variables are right. Also make sure that the code can actually reach and read them. (You can do so with php artisan tinker).

Laravel beyondcode websockets do not connect

I'm using this Laravel websockets package to have my own websocket server.
As mentioned in package documentation, I have this configuration:
.env setting:
PUSHER_APP_ID=761772
PUSHER_APP_KEY=qwerty
PUSHER_APP_SECRET=secret
PUSHER_APP_CLUSTER=ap2
broadcasting.php:
'pusher' => [
'driver' => 'pusher',
'key' => env('PUSHER_APP_KEY'),
'secret' => env('PUSHER_APP_SECRET'),
'app_id' => env('PUSHER_APP_ID'),
'options' => [
'cluster' => env('PUSHER_APP_CLUSTER'),
'encrypted' => true,
//'host' => '105.208.174.8', <--I did test this too
'host' => '127.0.0.1',
'port' => 6001,
'scheme' => 'https'//<--Tested with http
],
],
websockets.php:
'apps' => [
[
'id' => env('PUSHER_APP_ID'),
'name' => env('APP_NAME'),
'key' => env('PUSHER_APP_KEY'),
'secret' => env('PUSHER_APP_SECRET'),
'enable_client_messages' => false,
'enable_statistics' => true,
],
],
bootstrap.js:
/**
* Echo exposes an expressive API for subscribing to channels and listening
* for events that are broadcast by Laravel. Echo and event broadcasting
* allows your team to easily build robust real-time web applications.
*/
import Echo from 'laravel-echo'
window.Pusher = require('pusher-js');
window.Echo = new Echo({
broadcaster: 'pusher',
key: 'qwerty',
wsHost: window.location.hostname,
wsPort: 6001,
disableStats: true,
encrypted: true,
enabledTransports: ['ws', 'wss'] //This was added from issue 86
});
This is issue number 86 in package repository
I'm using letsencrypt with my directadmin control panel and this is my SSL part of websockets.php configuration:
'ssl' => [
/*
* Path to local certificate file on filesystem. It must be a PEM encoded file which
* contains your certificate and private key. It can optionally contain the
* certificate chain of issuers. The private key also may be contained
* in a separate file specified by local_pk.
*/
//'local_cert' => null,
'local_cert' => '/home/myDomain/domains/myDomain/public_html/vendor/react/socket/examples/localhost.pem',
//'local_cert' => '/usr/local/directadmin/data/users/myDomain/domains/myDomain.ir.cert',
/*
* Path to local private key file on filesystem in case of separate files for
* certificate (local_cert) and private key.
*/
//'local_pk' => null,
'local_pk' => '/usr/local/directadmin/data/users/myDomain/domains/myDomain.ir.key',
/*
* Passphrase for your local_cert file.
*/
'passphrase' => null,
],
But when I use php artisan websockets:serve, It seems there's something wrong about connection and the myDomain.com/laravel-websockets admin panel says:
Channel's current state is unavailable
and the console says:
Firefox can’t establish a connection to the server at wss://myDomain.ir:6001/app/qwerty?protocol=7&client=js&version=4.3.1&flash=false.
pusher.min.js:8:6335
The connection to wss://myDomain.ir:6001/app/qwerty?protocol=7&client=js&version=4.3.1&flash=false was interrupted while the page was loading.
Does anyone know what's my issue and how should I solve this?
I had the same issue and the problem was the read access of the local_cert and local_pk.
You can use sudo php artisan websocket:serve to try if this is the issue.
If it's the case, add read access to the files or use a user with the access in /etc/supervisor/conf.d/websockets.conf
I had the same problem, I was using Homestead, are you on homestead, if so you should be using supervisor(Debian based) or supervisord (REDHat based) OS to run the laravel socket without manually entering the command "php artisan websockets:serve" at all times.
You can refer to this documentation. https://docs.beyondco.de/laravel-websockets/1.0/basic-usage/starting.html#restricting-the-listening-host
For SSL I also followed this documentation with Valet: https://docs.beyondco.de/laravel-websockets/1.0/basic-usage/ssl.html#usage-with-laravel-valet
I had the same issue first you have to make sure that port you are trying to run is open or not. if you are running socket server on shared hosting then its not possible or you can talk with customer support and they will open port for you. if you have vps or dedicated server you can open port from your control panel. first try to run without ssl if its running fine it means that your port is open then config your ssl config.
If you are using Laravel < 8.0, try composer require pusher/pusher-php-server ^4.1.
my be you have not run server
php artisan websockets:serve
http://127.0.0.1:8000/laravel-websockets
I was struggling with 500 Error till I figured it out
Error message: Attempt to read property "key" on null
authEndpoint: `http://localhost:3060/laravel-websockets/auth`,
auth: {
headers: {
'x-app-id': '**App ID**', // => my issue was HERE
Authorization: 'Bearer jwt TOKEN',
'Access-Control-Allow-Origin': '*'
}
}
and I found it by looking into the file in vendor\beyondcode\laravel-websockets\src\Dashboard\Http\Controllers\AuthenticateDashboard.php
$app = App::findById($request->header('x-app-id'));
$broadcaster = new PusherBroadcaster(new Pusher(
$app->key,
$app->secret,
$app->id,
[]
));
and changed the middlware in App\Providers\BroadcastServiceProvider.php
// from
// Broadcast::routes();
// to
Broadcast::routes(['middleware' => ['auth:api']]);
another change in App\config\websockets.php
'middleware' => [
'api', // => changed it from web to api
Authorize::class,
],
hope this help :)

Laravel - Driver [] is Not Supported

I haven't found an example like mine, the others appear to be missing what I already have but anyways, I'm trying to upload to an external FTP site, to which I have the following in my filesystem.php file:
's3' => [
'driver' => 's3',
'key' => env('AWS_ACCESS_KEY_ID'),
'secret' => env('AWS_SECRET_ACCESS_KEY'),
'region' => env('AWS_DEFAULT_REGION'),
'bucket' => env('AWS_BUCKET'),
],
'fourkites-ftp' => [
'driver' => 'ftp',
'host' => 'ftp.site.com',
'username' => 'my-username',
'password' => 'my-password',
],
And I'm trying to send the file along with the following in one of my controllers:
Storage::disk('fourkites-ftp')->put('new/afnloads.csv', $temp);
And as I'm trying testing it, it gives me this error:
(1/1) InvalidArgumentException
Driver [] is not supported.
in FilesystemManager.php line 126
Are there any suggestions? Thanks!
Most probably config cached.
Try clear using
php artisan config:clear
I have solved my problem by following commands
php artisan cache:clear
php artisan config:clear
php artisan clear-compiled
It helped me adding this line to bootstrap/app.php (in 'Create The Application' section)
$app->configure('filesystems');

Error retrieving credentials from the instance profile metadata server. Laravel S3

Issue
The same code, on almost identical servers, fails locally and on production, however works on our staging server. When we attempt to interact with an item in a bucket, we get an Error retrieving credentials....
- Both servers, staging and production, are deployed by Envoyer and provisioned by Forge to AWS EC2 instances.
- Both instances hit the same bucket with the same bucket policy.
- .env settings are same for all, minus the server name and debugging
Error on production:
Aws\Exception\CredentialsException
Error retrieving credentials from the instance profile metadata server. (cURL error 28: Connection timed out after 1003 milliseconds (see http://curl.haxx.se/libcurl/c/libcurl-errors.html))
Server settings
Staging
Ubuntu 16.04.2 LTS on AWS
PHP 7.1.3-3
NPM 3.10.10
Node v6.10.1
Production
Ubuntu 16.04.1 LTS on AWS EC2
PHP 7.1.6-1
npm 3.10.10
Node v6.10.1
Composer.json packages
"laravel/framework": "5.4.*", // 5.4.25
"aws/aws-sdk-php-laravel": "~3.0", // 3.1.0
"guzzlehttp/guzzle": "~6.0", // 6.2.3
Code sample
function getPhoto($personID)
{
$contents = '';
$id = $personID;
$cloudFront = env('AWS_CLOUDFRONT_PHOTO'); // d212rosgvhtylp.cloudfront.net
$fileKey = filePath($id) . '_t.jpg'; // 9ae299a1990e79d62f07c28bb60ecf6f_t.jpg
$fileURL = $cloudFront . '/' . filePath($id) . '_t.jpg'; // d212rosgvhtylp.cloudfront.net/9ae299a1990e79d62f07c28bb60ecf6f_t.jpg
// check if in remote storage then get contents
$contents = Storage::disk('s3photo')->get($fileKey); /* ****** FAILS HERE ****** */
// stream bioPhoto
header('Content-Type: image/jpeg');
echo $contents;
}
After ensuring your .env files contain the correct values for the AWS client, run the following command:
php artisan config:clear
This should clear up your issue if it is caused by initially having incorrect or missing env data, not sure when the cache is updated on it's own but the config cache seems to be pretty persistent.
I encountered this issue after I accedentially had entered the AWS_ACCESS_KEY_ID in the .env file twice.
.env:
AWS_ACCESS_KEY_ID=MYREALID
AWS_SECRET_ACCESS_KEY=myrealkey
...
...a lot of variables..
...
AWS_ACCESS_KEY_ID=
AWS_SECRET_ACCESS_KEY=
The AWS sdk therefor tries to search for these credentials elsewhere, at that's have the error occures.
I recently had this problem. In my case, it worked locally and not on the EC2 instance. I did not understand too much. In the end I realized that I had set up IAM locally in the default folder ~/.aws/credentials, so in local everything was good. So I poked in the laravel sources and I noticed that laravel was going to take the connection configs in the file services.php config folder.
Edit config/services.php and put in the AWS IAM keys.
'mailgun' => [
'domain' => env('MAILGUN_DOMAIN'),
'secret' => env('MAILGUN_SECRET'),
],
'ses' => [
'key' => env('AWS_KEY'),
'secret' => env('AWS_SECRET'),
'region' => env('AWS_REGION'),
],
'sparkpost' => [
'secret' => env('SPARKPOST_SECRET'),
],
'stripe' => [
'model' => App\User::class,
'key' => env('STRIPE_KEY'),
'secret' => env('STRIPE_SECRET'),
],
So I saw that my .env file did not have the AWS IAM login keys, those called in the config /services.php file.
After a small adjustment everything works great.
This issue may occur if you are passing the wrong ENV variables, check your config/filesystems.php:
'key' => env('AWS_ACCESS_KEY_ID'),
'secret' => env('AWS_SECRET_ACCESS_KEY'),
'region' => env('AWS_DEFAULT_REGION'),
'bucket' => env('AWS_BUCKET'),
'url' => env('AWS_URL'),
See: https://github.com/laravel/laravel/blob/master/config/filesystems.php#L60
And make sure the keys are matching in your .env.
Pretty sure they changed the name in the last couple updates.

DynamoDB Local - Connection Refused from PHP

I am running DynamoDB Local on port 8080. This is the command used to start the DB:
java -Djava.library.path=./DynamoDBLocal_lib -jar DynamoDBLocal.jar -port 8080
Going to localhost:8080/shell/ yields the DynamoDB Javascript Shell. The shell works and allows operations to be performed on a local db file. The db file created by using the shell is named cUniqueSessionID_us-west-2.db.
In a PHP project, I have the following code for creating a table using DynamoDB
$db = new \Aws\DynamoDb\DynamoDbClient([
'region' => 'us-west-2',
'version' => 'latest',
'endpoint' => 'http://localhost:8080/',
'credentials' => [
'key' => 'not-a-real-key',
'secret' => 'not-a-real-secret',
],
]);
$db->createTable([
'TableName' =>'SampleTable',
'AttributeDefinitions' => [
[ 'AttributeName' => 'Id', 'AttributeType' => 'N' ]
],
'KeySchema' => [
[ 'AttributeName' => 'Id', 'KeyType' => 'HASH' ]
],
'ProvisionedThroughput' => [
'ReadCapacityUnits' => 5,
'WriteCapacityUnits' => 6
]
]);
But running this yields Error executing "CreateTable" on "http://localhost:8080/"; AWS HTTP error: cURL error 7: Failed to connect to localhost port 8080: Connection refused
I've tried turning off my firewall without success. What could be causing this error?
I found the issue.
My PHP project is running in a Vagrant virtual machine, but I was running DynamoDB on my local machine. Thus, the localhost in my PHP code refered to the vagrant localhost but DynamoDB was running on my machine's localhost.
To solve the problem, I ran DynamoDB from within Vagrant.

Categories