How to solve Laravel 504 Gateway Time-out - laravel

I am trying to send images to WooCommerce through API and I am getting 504 Gateway Time-out, the same error I am getting in Postman. I tried with changing max_execution_time but again I got error 504.
public function updateProduct($ecart, $product, $wooId){
//set_time_limit(3600);
//ini_set('max_execution_time', 3600);
//ini_set('memory_limit', '2048M');
$response = Http::withHeaders([
'Content-Type' => 'application/json',
])->withBasicAuth($ecart->client_key, $ecart->client_secret)->put(
$ecart->url.'/wp-json/wc/v3/products/'.$wooId,
$product);
//dd($response);
dump('res',$response);
$body = json_decode($response->getBody(), true);
dd($body);
return $response;
}
What else I can do, because I have this problem in localhost, adn I don't know will this happen in production??
This is my response
Illuminate\Http\Client\Response^ {#9529
#response: GuzzleHttp\Psr7\Response^ {#9583
-reasonPhrase: "Gateway Time-out"
-statusCode: 504
-headers: array:6 [
"Server" => array:1 [
0 => "nginx"
]
"Date" => array:1 [
0 => "Fri, 27 Jan 2023 08:08:48 GMT"
]
"Content-Type" => array:1 [
0 => "text/html"
]
"Content-Length" => array:1 [
0 => "160"
]
"Connection" => array:1 [
0 => "keep-alive"
]
"Strict-Transport-Security" => array:1 [
0 => "max-age=63072000"
]
]
-headerNames: array:6 [
"server" => "Server"
"date" => "Date"
"content-type" => "Content-Type"
"content-length" => "Content-Length"
"connection" => "Connection"
"strict-transport-security" => "Strict-Transport-Security"
]
-protocol: "1.1"
-stream: GuzzleHttp\Psr7\Stream^ {#9580
-stream: stream resource {#1032
wrapper_type: "PHP"
stream_type: "TEMP"
mode: "w+b"
unread_bytes: 0
seekable: true
uri: "php://temp"
options: []
}
-size: null
-seekable: true
-readable: true
-writable: true
-uri: "php://temp"
-customMetadata: []
}
}
#decoded: null
+"cookies": GuzzleHttp\Cookie\CookieJar^ {#9554
-cookies: []
-strictMode: false
}
+"transferStats": GuzzleHttp\TransferStats^ {#9584
-request: GuzzleHttp\Psr7\Request^ {#9577
-method: "PUT"
-requestTarget: null
-uri: GuzzleHttp\Psr7\Uri^ {#9553
-scheme: "https"
-userInfo: ""
-host: "test.myraidbox.de"
-port: null
-path: "/wp-json/wc/v3/products/10612"
-query: ""
-fragment: ""
-composedComponents: "https://test.myraidbox.de/wp-json/wc/v3/products/10612"
}
-headers: array:5 [
"Content-Length" => array:1 [
0 => "1902"
]
"User-Agent" => array:1 [
0 => "GuzzleHttp/7"
]
"Authorization" => array:1 [
0 => "Basic Y2tfYWY4MTFhZmU4OWM2OWNjMWRjY2NiMGRlYjVmYjc2Y2UyODQxYTUyNzpjc182ZThkODlhZDIzNTVlYjA1ZTJhOTY5YThkODE3ZmQ4NWQ0NjY3MDA2"
]
"Host" => array:1 [
0 => "test.myraidbox.de"
]
"Content-Type" => array:1 [
0 => "application/json"
]
]
-headerNames: array:5 [
"content-length" => "Content-Length"
"user-agent" => "User-Agent"
"authorization" => "Authorization"
"host" => "Host"
"content-type" => "Content-Type"
]
-protocol: "1.1"
-stream: GuzzleHttp\Psr7\Stream^ {#9568
-stream: stream resource {#1030
wrapper_type: "PHP"
stream_type: "TEMP"
mode: "w+b"
unread_bytes: 0
seekable: true
uri: "php://temp"
options: []
}
-size: 1902
-seekable: true
-readable: true
-writable: true
-uri: "php://temp"
-customMetadata: []
}
}
-response: GuzzleHttp\Psr7\Response^ {#9583}
-transferTime: 30.163235
-handlerStats: array:38 [
"url" => "https://test.myraidbox.de/wp-json/wc/v3/products/10612"
"content_type" => "text/html"
"http_code" => 504
"header_size" => 200
"request_size" => 2195
"filetime" => -1
"ssl_verify_result" => 0
"redirect_count" => 0
"total_time" => 30.163235
"namelookup_time" => 0.004224
"connect_time" => 0.007388
"pretransfer_time" => 0.103427
"size_upload" => 1902.0
"size_download" => 160.0
"speed_download" => 5.0
"speed_upload" => 63.0
"download_content_length" => 160.0
"upload_content_length" => 1902.0
"starttransfer_time" => 30.163099
"redirect_time" => 0.0
"redirect_url" => ""
"primary_ip" => "::ffff:167.235.133.93"
"certinfo" => []
"primary_port" => 443
"local_ip" => "::ffff:172.18.0.7"
"local_port" => 57572
"http_version" => 2
"protocol" => 2
"ssl_verifyresult" => 0
"scheme" => "HTTPS"
"appconnect_time_us" => 103359
"connect_time_us" => 7388
"namelookup_time_us" => 4224
"pretransfer_time_us" => 103427
"redirect_time_us" => 0
"starttransfer_time_us" => 30163099
"total_time_us" => 30163235
"appconnect_time" => 0.103359
]
-handlerErrorData: 0
}
}
And this is my .docker/nginx/default
server {
listen 80 default_server;
listen 443 ssl;
server_name backend.brandcanyon.de;
root /var/www/html/public;
add_header X-Frame-Options "SAMEORIGIN";
add_header X-XSS-Protection "1; mode=block";
add_header X-Content-Type-Options "nosniff";
index index.html index.htm index.php;
charset utf-8;
ssl_certificate /etc/ssl/certs/localhost.crt;
ssl_certificate_key /etc/ssl/private/localhost.key;
client_max_body_size 100M;
fastcgi_read_timeout 600;
proxy_read_timeout 600;
location / {
try_files $uri $uri/ /index.php?$query_string;
# for OPTIONS return these headers and HTTP 200 status
if ($request_method = OPTIONS) {
add_header Access-Control-Allow-Methods "*";
add_header Access-Control-Allow-Headers "*";
add_header Access-Control-Allow-Origin "*";
return 200;
}
}
location = /favicon.ico { access_log off; log_not_found off; }
location = /robots.txt { access_log off; log_not_found off; }
location ~ \.php$ {
fastcgi_pass php-fpm:9000;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;
include fastcgi_params;
}
location ~ /\.(?!well-known).* {
deny all;
}
}

Related

Not hitting a function when posting a route in testing

I'm trying to create a feature test and I'm trying to post to a route, but I'm not hitting that route and what I mean by that
is, when I dd() in that function that I need to get into, I'm not getting the output from the dd() that lets me know that I've hit my function.
Here is my test function
<?php
namespace Tests\Feature;
class CategoryTest extends TestCase
{
protected function setUp(): void
{
parent::setUp();
$user = User::create([
'name' => 'Test User',
'email' => 'test#test.com'
'password' => bcrypt('password')
]);
$this->actingAs($user, 'web');
}
private function createTestCategory()
{
$category = Category::create([
'name' => 'Category 1'
]);
return $category;
}
public function testCategoryVersion()
{
$category = $this->createTestCategory();
$version = [
'version' => 'v1'
];
$response = $this->call('POST', "/api/project/{$category->id}/version", [
'version' => $version
]);
dd($response);
}
}
and this is what I get in return
Illuminate\Testing\TestResponse^ {#12704
+baseResponse: Illuminate\Http\RedirectResponse^ {#13339
#request: Illuminate\Http\Request^ {#13504
#json: Symfony\Component\HttpFoundation\ParameterBag^ {#14972
#parameters: array:1 [
"version" => array:1 [
"version" => "v1"
]
]
}
#convertedFiles: null
#userResolver: Closure($guard = null)^ {#14453
class: "Illuminate\Auth\AuthServiceProvider"
this: Illuminate\Auth\AuthServiceProvider {#16961 …}
use: {
$app: Illuminate\Foundation\Application {#17080 …}
}
file: "./vendor/laravel/framework/src/Illuminate/Auth/AuthServiceProvider.php"
line: "105 to 107"
}
#routeResolver: Closure()^ {#15018
class: "Illuminate\Routing\Router"
this: Illuminate\Routing\Router {#16256 …}
use: {
$route: Illuminate\Routing\Route {#14382 …}
}
file: "./vendor/laravel/framework/src/Illuminate/Routing/Router.php"
line: "655 to 657"
}
+attributes: Symfony\Component\HttpFoundation\ParameterBag^ {#12703
#parameters: []
}
+request: Symfony\Component\HttpFoundation\ParameterBag^ {#14972}
+query: Symfony\Component\HttpFoundation\InputBag^ {#11883
#parameters: []
}
+server: Symfony\Component\HttpFoundation\ServerBag^ {#14949
#parameters: array:19 [
"SERVER_NAME" => "localhost"
"SERVER_PORT" => 80
"HTTP_HOST" => "localhost"
"HTTP_USER_AGENT" => "Symfony"
"HTTP_ACCEPT" => "application/json"
"HTTP_ACCEPT_LANGUAGE" => "en-us,en;q=0.5"
"HTTP_ACCEPT_CHARSET" => "ISO-8859-1,utf-8;q=0.7,*;q=0.7"
"REMOTE_ADDR" => "127.0.0.1"
"SCRIPT_NAME" => ""
"SCRIPT_FILENAME" => ""
"SERVER_PROTOCOL" => "HTTP/1.1"
"REQUEST_TIME" => 1644936692
"REQUEST_TIME_FLOAT" => 1644936692.2835
"HTTP_CONTENT_LENGTH" => 28
"CONTENT_TYPE" => "application/json"
"PATH_INFO" => ""
"REQUEST_METHOD" => "POST"
"REQUEST_URI" => "/api/project/1/version"
"QUERY_STRING" => ""
]
}
+files: Symfony\Component\HttpFoundation\FileBag^ {#14964
#parameters: []
}
+cookies: Symfony\Component\HttpFoundation\InputBag^ {#16109
#parameters: []
}
+headers: Symfony\Component\HttpFoundation\HeaderBag^ {#11625
#headers: array:8 [
"host" => array:1 [
0 => "localhost"
]
"user-agent" => array:1 [
0 => "Symfony"
]
"accept" => array:1 [
0 => "application/json"
]
"accept-language" => array:1 [
0 => "en-us,en;q=0.5"
]
"accept-charset" => array:1 [
0 => "ISO-8859-1,utf-8;q=0.7,*;q=0.7"
]
"content-length" => array:1 [
0 => 28
]
"content-type" => array:1 [
0 => "application/json"
]
"origin" => array:1 [
0 => ""
]
]
#cacheControl: []
}
#content: "{"version":{"version":"v1"}}"
#languages: null
#charsets: null
#encodings: null
#acceptableContentTypes: array:1 [
0 => "application/json"
]
#pathInfo: "/api/project/1/version"
#requestUri: "/api/project/1/version"
#baseUrl: ""
#basePath: null
#method: "POST"
#format: null
#session: null
#locale: null
#defaultLocale: "en"
-preferredFormat: null
-isHostValid: true
-isForwardedValid: true
-isSafeContentPreferred: null
basePath: ""
format: "html"
}
#session: Illuminate\Session\Store^ {#11680
#id: "sGsZ8cj5iRPLBjfLT4quiaal9LjdOEJUakzno0CU"
#name: "laravel_session"
#attributes: array:2 [
"error" => "Your account has been disabled. Please contact us at test#test.com"
"_flash" => array:2 [
"new" => array:1 [
0 => "error"
]
"old" => []
]
]
#handler: Illuminate\Session\ArraySessionHandler^ {#11912
#storage: []
#minutes: "120"
}
#started: false
}
#targetUrl: "http://localhost/login"
+headers: Symfony\Component\HttpFoundation\ResponseHeaderBag^ {#14761
#computedCacheControl: array:2 [
"no-cache" => true
"private" => true
]
#cookies: []
#headerNames: array:5 [
"cache-control" => "Cache-Control"
"date" => "Date"
"location" => "Location"
"content-type" => "Content-Type"
"access-control-allow-origin" => "Access-Control-Allow-Origin"
]
#headers: array:5 [
"cache-control" => array:1 [
0 => "no-cache, private"
]
"date" => array:1 [
0 => "Tue, 15 Feb 2022 14:51:32 GMT"
]
"location" => array:1 [
0 => "http://localhost/login"
]
"content-type" => array:1 [
0 => "text/html; charset=UTF-8"
]
"access-control-allow-origin" => array:1 [
0 => ""
]
]
#cacheControl: []
}
#content: """
<!DOCTYPE html>\n
<html>\n
<head>\n
<meta charset="UTF-8" />\n
<meta http-equiv="refresh" content="0;url='http://localhost/login'" />\n
\n
<title>Redirecting to http://localhost/login</title>\n
</head>\n
<body>\n
Redirecting to http://localhost/login.\n
</body>\n
</html>
"""
#version: "1.1"
#statusCode: 302
#statusText: "Found"
#charset: null
+original: null
+exception: null
}
#streamedContent: null
}

Magento 2.4 Could not validate a connection to Elasticsearch. No alive nodes found in your cluster

I am trying to upgrade my Magento 2.3 store to 2.4. In trying to do so, when I try to run bin/magento setup:upgrade I receive the following error: Could not validate a connection to Elasticsearch. No alive nodes found in your cluster
Here is what I have so far.
I am running nginx, here is the config file:
upstream panam_backend {
server php74:9000;
}
server {
listen 80;
server_name panam.localhost;
set $MAGE_ROOT /var/www/html/panam.localhost;
listen 443 ssl http2;
ssl_certificate /var/www/html/panam.localhost/key/panam.localhost.crt;
ssl_certificate_key /var/www/html/panam.localhost/key/panam.localhost.key;
root $MAGE_ROOT/pub;
index index.php;
autoindex off;
charset UTF-8;
error_page 404 403 = /errors/404.php;
#add_header "X-UA-Compatible" "IE=Edge";
# PHP entry point for setup application
location ~* ^/setup($|/) {
root $MAGE_ROOT;
location ~ ^/setup/index.php {
fastcgi_pass panam_backend;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}
location ~ ^/setup/(?!pub/). {
deny all;
}
location ~ ^/setup/pub/ {
add_header X-Frame-Options "SAMEORIGIN";
}
}
# PHP entry point for update application
location ~* ^/update($|/) {
root $MAGE_ROOT;
location ~ ^/update/index.php {
fastcgi_split_path_info ^(/update/index.php)(/.+)$;
fastcgi_pass panam_backend;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
fastcgi_param PATH_INFO $fastcgi_path_info;
include fastcgi_params;
}
# Deny everything but index.php
location ~ ^/update/(?!pub/). {
deny all;
}
location ~ ^/update/pub/ {
add_header X-Frame-Options "SAMEORIGIN";
}
}
location / {
try_files $uri $uri/ /index.php?$args;
}
location /pub/ {
location ~ ^/pub/media/(downloadable|customer|import|theme_customization/.*\.xml) {
deny all;
}
alias $MAGE_ROOT/pub/;
add_header X-Frame-Options "SAMEORIGIN";
}
location /static/ {
# Uncomment the following line in production mode
# expires max;
# Remove signature of the static files that is used to overcome the browser cache
location ~ ^/static/version {
rewrite ^/static/(version\d*/)?(.*)$ /static/$2 last;
}
location ~* \.(ico|jpg|jpeg|png|gif|svg|js|css|swf|eot|ttf|otf|woff|woff2)$ {
add_header Cache-Control "public";
add_header X-Frame-Options "SAMEORIGIN";
expires +1y;
if (!-f $request_filename) {
rewrite ^/static/(version\d*/)?(.*)$ /static.php?resource=$2 last;
}
}
location ~* \.(zip|gz|gzip|bz2|csv|xml)$ {
add_header Cache-Control "no-store";
add_header X-Frame-Options "SAMEORIGIN";
expires off;
if (!-f $request_filename) {
rewrite ^/static/(version\d*/)?(.*)$ /static.php?resource=$2 last;
}
}
if (!-f $request_filename) {
rewrite ^/static/(version\d*/)?(.*)$ /static.php?resource=$2 last;
}
add_header X-Frame-Options "SAMEORIGIN";
}
location /media/ {
try_files $uri $uri/ /get.php?$args;
location ~ ^/media/theme_customization/.*\.xml {
deny all;
}
location ~* \.(ico|jpg|jpeg|png|gif|svg|js|css|swf|eot|ttf|otf|woff|woff2)$ {
add_header Cache-Control "public";
add_header X-Frame-Options "SAMEORIGIN";
expires +1y;
try_files $uri $uri/ /get.php?$args;
}
location ~* \.(zip|gz|gzip|bz2|csv|xml)$ {
add_header Cache-Control "no-store";
add_header X-Frame-Options "SAMEORIGIN";
expires off;
try_files $uri $uri/ /get.php?$args;
}
add_header X-Frame-Options "SAMEORIGIN";
}
location /media/customer/ {
deny all;
}
location /media/downloadable/ {
deny all;
}
location /media/import/ {
deny all;
}
# PHP entry point for main application
location ~ (index|get|static|report|404|503)\.php$ {
try_files $uri =404;
fastcgi_pass panam_backend;
fastcgi_buffers 16 16k;
fastcgi_buffer_size 32k;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}
location /_cluster/health {
proxy_pass http://192.168.77.75:9250/_cluster/health;
}
gzip on;
gzip_disable "msie6";
gzip_comp_level 6;
gzip_min_length 1100;
gzip_buffers 16 8k;
gzip_proxied any;
gzip_types
text/plain
text/css
text/js
text/xml
text/javascript
application/javascript
application/x-javascript
application/json
application/xml
application/xml+rss
image/svg+xml;
gzip_vary on;
# Banned locations (only reached if the earlier PHP entry point regexes don't match)
location ~* (\.php$|\.htaccess$|\.git) {
deny all;
}
}
#
## Optional override of deployment mode. We recommend you use the
## command 'bin/magento deploy:mode:set' to switch modes instead.
##
## set $MAGE_MODE default; # or production or developer
##
## If you set MAGE_MODE in server config, you must pass the variable into the
## PHP entry point blocks, which are indicated below. You can pass
## it in using:
##
## fastcgi_param MAGE_MODE $MAGE_MODE;
##
## In production mode, you should uncomment the 'expires' directive in the /static/ location block
Here is the env.php file:
<?php
return [
'cache_types' => [
'config' => 1,
'layout' => 1,
'block_html' => 1,
'collections' => 1,
'reflection' => 1,
'db_ddl' => 1,
'eav' => 1,
'customer_notification' => 1,
'target_rule' => 1,
'full_page' => 1,
'config_integration' => 1,
'config_integration_api' => 1,
'translate' => 1,
'config_webservice' => 1,
'compiled_config' => 1,
'vertex' => 1,
'google_product' => 0
],
'db' => [
'connection' => [
'default' => [
'dbname' => 'panam',
'host' => 'db',
'username' => 'root',
'password' => '',
'model' => 'mysql4',
'engine' => 'innodb',
'initStatements' => 'SET NAMES utf8;',
'active' => '1',
'profiler' => '1'
]
],
'table_prefix' => ''
],
'cache' => [
'frontend' => [
'default' => [
'backend' => 'Cm_Cache_Backend_Redis',
'backend_options' => [
'server' => 'redis',
'database' => '0',
'port' => '6379'
]
],
'page_cache' => [
'backend' => 'Cm_Cache_Backend_Redis',
'backend_options' => [
'server' => 'redis',
'port' => '6379',
'database' => '1',
'compress_data' => '0'
]
]
]
],
'MAGE_MODE' => 'developer',
'backend' => [
'frontName' => 'admin'
],
'crypt' => [
'key' => 'abfd843e41c08030189ad4ebaf1191f0'
],
'resource' => [
'default_setup' => [
'connection' => 'default'
]
],
'x-frame-options' => 'SAMEORIGIN',
'session' => [
'save' => 'redis',
'redis' => [
'host' => 'redis',
'port' => '6379',
'password' => '',
'timeout' => '2.5',
'persistent_identifier' => '',
'database' => '2',
'compression_threshold' => '2048',
'compression_library' => 'gzip',
'log_level' => '1',
'max_concurrency' => '6',
'break_after_frontend' => '5',
'break_after_adminhtml' => '30',
'first_lifetime' => '600',
'bot_first_lifetime' => '60',
'bot_lifetime' => '7200',
'disable_locking' => '0',
'min_lifetime' => '60',
'max_lifetime' => '2592000'
]
],
'install' => [
'date' => 'Fri, 06 Apr 2018 22:04:26 +0000'
],
'system' => [
'default' => [
'dev' => [
'debug' => [
'debug_logging' => '0'
]
],
'smile_elasticsuite_core_base_settings' => [
'es_client' => [
'servers' => '192.168.77.75:9250',
'enable_https_mode' => '0',
'enable_http_auth' => '0',
'http_auth_user' => '',
'http_auth_pwd' => ''
]
]
]
]
];
Here is output of curl -XGET 'http://192.168.77.75:9250' on the host computer:
{
"name" : "ebrownserver",
"cluster_name" : "7.6",
"cluster_uuid" : "wWppBNI9SR29XtyhIZ-LnQ",
"version" : {
"number" : "7.6.2",
"build_flavor" : "default",
"build_type" : "deb",
"build_hash" : "ef48eb35cf30adf4db14086e8aabd07ef6fb113f",
"build_date" : "2020-03-26T06:34:37.794943Z",
"build_snapshot" : false,
"lucene_version" : "8.4.0",
"minimum_wire_compatibility_version" : "6.8.0",
"minimum_index_compatibility_version" : "6.0.0-beta1"
},
"tagline" : "You Know, for Search"
}
I've restarted nginx and elasticsearch many times, but it didn't help.
Also, as far as my configuration goes, nginx is setup on the host computer while elasticsearch is on a separate server on the network. I don't know if that changes anything, but that's how it's setup right now.
Also, elasticsearch used to be connected to a docker container on the host computer before it started causing a bunch of problems. The docker container had a different ip address than the one that is currently being used, so maybe a caching issue where it's trying to use the old ip address is occurring? Not sure, just throwing it out there.
Let me know if you need anymore information.
I also faced this issue while upgrading my set on magento2.4.2. Trick here is to disable Elastic Search for a while and use php bin/magento commands easily. Here is the command to disable Elastic search:
php bin/magento module:disable {Magento_Elasticsearch,Magento_InventoryElasticsearch,Magento_Elasticsearch6,Magento_Elasticsearch7}
If you are running elasticsearch in a separate container then localhost is the wrong hostname, you need to use the hostname of the ES container.

laravel websocket with nuxt and nginx reverse proxy returns 502

Im running laravel 7 & trying to run laravel-websockets with nginx proxy using ssl.
unfortunately after I configure everything Im facing
WebSocket connection to 'wss://www.rabter.com:6001/app/174e625ceea907e9e63c?protocol=7&client=js&version=4.3.1&flash=false' failed: Error during WebSocket handshake: Unexpected response code: 502
Before implementing ssl everything was working
/config/websockets.php
use BeyondCode\LaravelWebSockets\Dashboard\Http\Middleware\Authorize;
return [
'dashboard' => [
'port' => env('LARAVEL_WEBSOCKETS_PORT', 6001),
],
'apps' => [
[
'id' => env('PUSHER_APP_ID'),
'name' => env('APP_NAME'),
'key' => env('PUSHER_APP_KEY','174e625ceea907e9e63c'),
'secret' => env('PUSHER_APP_SECRET'),
'path' => env('PUSHER_APP_PATH'),
'capacity' => null,
'enable_client_messages' => true,
'enable_statistics' => true,
],
],
'app_provider' => BeyondCode\LaravelWebSockets\Apps\ConfigAppProvider::class,
'allowed_origins' => [
//
],
'max_request_size_in_kb' => 250,
'path' => 'laravel-websockets',
'middleware' => [
'web',
'api',
Authorize::class,
],
'statistics' => [
'model' => \BeyondCode\LaravelWebSockets\Statistics\Models\WebSocketsStatisticsEntry::class,
'interval_in_seconds' => 60,
'delete_statistics_older_than_days' => 60,
'perform_dns_lookup' => true,
],
'ssl' => [
'local_cert' => env('LARAVEL_WEBSOCKETS_SSL_LOCAL_CERT', null),
'local_pk' => env('LARAVEL_WEBSOCKETS_SSL_LOCAL_PK', null),
'passphrase' => env('LARAVEL_WEBSOCKETS_SSL_PASSPHRASE', null),
],
'channel_manager' => \BeyondCode\LaravelWebSockets\WebSockets\Channels\ChannelManagers\ArrayChannelManager::class,
];
`
/config/broadcasting.php
`
'default' => env('BROADCAST_DRIVER', 'pusher'),
'connections' => [
'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'),
'host' => '127.0.0.1',
'port' => 6001,
'scheme' => 'https',
],
],
'redis' => [
'driver' => 'redis',
'connection' => 'default',
],
'log' => [
'driver' => 'log',
],
'null' => [
'driver' => 'null',
],
],
];
/etc/nginx/conf.d/vhosts/rabter.com.ssl.conf
listen 45.82.136.131:443 ssl;
server_name rabter.com;
return 301 https://www.rabter.com$request_uri;
}
server {
listen 45.82.136.131:443 ssl;
server_name www.rabter.com;
ssl_certificate /etc/pki/tls/certs/rabter.com.bundle;
ssl_certificate_key /etc/pki/tls/private/rabter.com.key;
root /home/rabter/core/public/;
index index.php;
access_log /var/log/nginx/rabter.com.bytes bytes;
access_log /var/log/nginx/rabter.com.log combined;
error_log /var/log/nginx/rabter.com.error.log error;
location / {
proxy_set_header Connection "keep-alive";
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_http_version 1.1;
proxy_pass https://45.82.136.131:3000$uri;
proxy_connect_timeout 300;
proxy_send_timeout 300;
proxy_read_timeout 300;
send_timeout 300;
proxy_intercept_errors on;
error_page 404 = #php;
proxy_set_header Host $host;
proxy_cache_bypass $http_upgrade;
proxy_redirect off;
}
location #php {
try_files $uri $uri/ /index.php?$query_string;
}
location ~ \.php$ {
fastcgi_split_path_info ^(.+\.php)(/.+)$;
fastcgi_pass 45.82.136.131:9000;
fastcgi_index index.php;
include fastcgi_params;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
fastcgi_intercept_errors off;
fastcgi_buffer_size 16k;
fastcgi_buffers 4 16k;
fastcgi_connect_timeout 300;
fastcgi_send_timeout 300;
fastcgi_read_timeout 300;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_set_header Host $host;
}
}
upstream websocket {
server 127.0.0.1:6001;
}
server {
listen 6001 ssl;
ssl_certificate /etc/myssl/certs/rabter.com.bundle;
ssl_certificate_key etc/myssl/private/rabter.com.key;
location / {
proxy_pass https://websocket;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_connect_timeout 43200000;
}
}
laravel-echo configuration
broadcaster: 'pusher',
key: process.env.MIX_PUSHER_APP_KEY,
cluster: process.env.MIX_PUSHER_APP_CLUSTER,
wsHost:'rabter.com',
wsPort:6001,
wssPort: 6001,
disableStats: true,
encrypted: true,
authEndpoint: process.env.CLIENT_URL + '/api/broadcasting/auth',
enabledTransports: ['ws', 'wss'],
}],
Im running nuxtjs as frontend and been stuck on this for more than a month.
Any help would be highly appreciated
The Configuration that I have is now is working on ssl, So Im sharing each file.Ill be giving a brief explanation at the end.
Before you start make sure you have copied your own full ssl_ciphers from YOUR_SITE_NAME.YOUR_DOMAIN_SUFFIX.ssl.conf if you have any.
Laravel V8 ,LaravelWebSocket version 1.4,pusher 4.0
Websockets.php:
<?php
use BeyondCode\LaravelWebSockets\Dashboard\Http\Middleware\Authorize;
return [
/*
* Set a custom dashboard configuration
*/
'dashboard' => [
'port' => env('LARAVEL_WEBSOCKETS_PORT', 6001),
],
/*
* This package comes with multi tenancy out of the box. Here you can
* configure the different apps that can use the webSockets server.
*
* Optionally you specify capacity so you can limit the maximum
* concurrent connections for a specific app.
*
* Optionally you can disable client events so clients cannot send
* messages to each other via the webSockets.
*/
'apps' => [
[
'id' => env('PUSHER_APP_ID'),
'name' => env('APP_NAME'),
'key' => env('PUSHER_APP_KEY'),
'secret' => env('PUSHER_APP_SECRET'),
'path' => env('PUSHER_APP_PATH'),
'capacity' => null,
'enable_client_messages' => true,
'enable_statistics' => true,
],
],
/*
* This class is responsible for finding the apps. The default provider
* will use the apps defined in this config file.
*
* You can create a custom provider by implementing the
* `AppProvider` interface.
*/
'app_provider' => BeyondCode\LaravelWebSockets\Apps\ConfigAppProvider::class,
/*
* This array contains the hosts of which you want to allow incoming requests.
* Leave this empty if you want to accept requests from all hosts.
*/
'allowed_origins' => [
//
],
/*
* The maximum request size in kilobytes that is allowed for an incoming WebSocket request.
*/
'max_request_size_in_kb' => 250,
/*
* This path will be used to register the necessary routes for the package.
*/
'path' => 'laravel-websockets',
/*
* Dashboard Routes Middleware
*
* These middleware will be assigned to every dashboard route, giving you
* the chance to add your own middleware to this list or change any of
* the existing middleware. Or, you can simply stick with this list.
*/
'middleware' => [
'web',
'api',
Authorize::class,
],
'statistics' => [
/*
* This model will be used to store the statistics of the WebSocketsServer.
* The only requirement is that the model should extend
* `WebSocketsStatisticsEntry` provided by this package.
*/
'model' => \BeyondCode\LaravelWebSockets\Statistics\Models\WebSocketsStatisticsEntry::class,
/*
* Here you can specify the interval in seconds at which statistics should be logged.
*/
'interval_in_seconds' => 60,
/*
* When the clean-command is executed, all recorded statistics older than
* the number of days specified here will be deleted.
*/
'delete_statistics_older_than_days' => 60,
/*
* Use an DNS resolver to make the requests to the statistics logger
* default is to resolve everything to 127.0.0.1.
*/
'perform_dns_lookup' => false,
],
/*
* Define the optional SSL context for your WebSocket connections.
* You can see all available options at: http://php.net/manual/en/context.ssl.php
*/
'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' => env('LARAVEL_WEBSOCKETS_SSL_LOCAL_CERT', null),
/*
* Path to local private key file on filesystem in case of separate files for
* certificate (local_cert) and private key.
*/
'local_pk' => env('LARAVEL_WEBSOCKETS_SSL_LOCAL_PK', null),
/*
* Passphrase for your local_cert file.
*/
'passphrase' => env('LARAVEL_WEBSOCKETS_SSL_PASSPHRASE', null),
// 'verify_peer' => false,
],
/*
* Channel Manager
* This class handles how channel persistence is handled.
* By default, persistence is stored in an array by the running webserver.
* The only requirement is that the class should implement
* `ChannelManager` interface provided by this package.
*/
'channel_manager' => \BeyondCode\LaravelWebSockets\WebSockets\Channels\ChannelManagers\ArrayChannelManager::class,
];
broadcasting.php:
<?php
return [
'default' => env('BROADCAST_DRIVER', 'pusher'),
'connections' => [
'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'),
'host' => '127.0.0.1',
'port' => 6001,
'scheme' => 'https',
'encrypted' => true,
],
],
'redis' => [
'driver' => 'redis',
'connection' => 'default',
],
'log' => [
'driver' => 'log',
],
'null' => [
'driver' => 'null',
],
],
];
nuxt.config.js:
buildModules: [
//The start of part that must be included in your buildModules
['#nuxtjs/laravel-echo',{
broadcaster: 'pusher',
key: process.env.MIX_PUSHER_APP_KEY,
cluster: process.env.MIX_PUSHER_APP_CLUSTER,
wsHost:'www.example.com',
wsPort:6001,
wssPort:6001,
enabledTransports: ['ws', 'wss'],
disableStats: true,
encrypted: true,
}]
//End
]
Nginx YOUR_SITE_NAME.YOUR_DOMAIN_SUFFIX.ssl.conf:
server {
listen zzz:zzz:zzz:zzz:443 ssl http2;
server_name example.com;
return 301 https://www.example.com$request_uri;
}
server {
listen zzz:zzz:zzz:zzz:443 ssl http2;
server_name www.example.com;
ssl_certificate /etc/pki/tls/certs/example.bundle;
ssl_certificate_key /etc/pki/tls/private/example.key;
ssl_session_timeout 5m;
ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
ssl_ciphers YOUR CIPHERS
ssl_prefer_server_ciphers on;
root /home/example/core/public/;
index index.php;
access_log /var/log/nginx/example.com.bytes bytes;
access_log /var/log/nginx/example.com.log combined;
error_log /var/log/nginx/example.com.error.log error;
location / {
proxy_set_header Connection "keep-alive";
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_http_version 1.1;
proxy_pass https://zzz:zzz:zzz:zzz:3000$uri;
proxy_connect_timeout 300;
proxy_send_timeout 300;
proxy_read_timeout 300;
send_timeout 300;
}
location #php {
try_files $uri $uri/ /index.php?$query_string;
}
location ~ \.php$ {
fastcgi_split_path_info ^(.+\.php)(/.+)$;
fastcgi_pass 127.0.0.1:9000;
fastcgi_index index.php;
include fastcgi_params;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
fastcgi_intercept_errors off;
fastcgi_buffer_size 16k;
fastcgi_buffers 4 16k;
fastcgi_connect_timeout 300;
fastcgi_send_timeout 300;
fastcgi_read_timeout 300;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_set_header Host $host;
proxy_intercept_errors on;
error_page 404 = #php;
}
location ~ /app/ {
return 404;
}
}
Nginx YOUR_SITE_NAME.YOUR_DOMAIN_SUFFIX.conf:
server {
listen zzz.zzz.zzz:80;
server_name example.com www.example.com;
return 301 https://www.example.com$request_uri;
}
For nginx config if you are running centos 7 try copy this in terminal
cd /etc/nginx/conf.d/vhosts hit enter then ls you will see YOUR_SITE_NAME.YOUR_DOMAIN_SUFFIX.conf and YOUR_SITE_NAME.YOUR_DOMAIN_SUFFIX.ssl.conf
which codes provided above,
Keep in mind in both you have change example to your domain name
and zzz should be your servers IP Address
You can try 127.0.0.1 on zzz too if your internet IP address didnt
work
Keep in mind to check the root and logs address that it might be
different than mine
fastcgi_pass can be localIP or internetIP too which for me was
internetIP before I do a major update which involved backend/frontend/server update but now its localIP
After the setup make sure to restart nginx and websocket services and perform a php artisan cache and config clear.after that do a fresh nuxt build and connect to your laravel-websockets via the link https://www.example.com/laravel-websockets
Im using this configuration for a site with ssl on nginx+nuxtjs+laravel+laravel-websocket+pusher
Hopefully this answer will make you connect successfully

Laravel 5.6 Unit Test maintain login session from beginning until end

class ExampleTest extends TestCase
{
public function setUp()
{
parent::setUp();
$this->base_url = config('app.url');
$response = $this->post($this->base_url . '/auth/login', [
'username' => 'root',
'password' => '123',
]);
// how to get the login session cookie?
}
public function testStep1()
{
// how to set the login session to this POST request?
$response = $this->post($this->base_url . '/step1', [
'attr_1' => 'foo',
'attr_2' => 'bar',
]);
...
}
public function testStep2()
{
// how to set the login session to this POST request?
$response = $this->post($this->base_url . '/step2', [
'attr_1' => 'abc',
'attr_2' => 'xyz',
]);
...
}
}
From the sample code above, what I want to achieve is testStep1 & testStep2 must in order (wizard to create something). Thus, I must maintain the same session.
Is it possible to achieve?
Edit 2018-07-10 14:51 UTC+8
I've tried the output after call the /auth/login, the value of $response->headers->getCookies() is
array:1 [
0 => Symfony\Component\HttpFoundation\Cookie {#940
#name: "XSRF-TOKEN"
#value: "eyJpdiI6IjQwUKxYnZlQ0J3N1B0Vkp4VjBEWVE9PSIsInZhbHVlIj782RKOUh2UFhONFwvaVRPUm56YkJ1ekxxSXlCTmtYSFNyRUF3NTdCTWhBMHhEQis1VVU0OUFcL3pKQUcybTFwQjdad1I1em02V1d4bVhDZWR2NFluUTlxdz09IiwibWFjIjoiZWRjYjk2NWI1MTU3YmJlMGEwMDdiNjNkYmVkMjBjMWU3NTRmZjE5NmMyM2EwOTZlNWJmZmYwMmRmYmExMWE1MSJ9"
#domain: null
#expire: 1531218886
#path: "/"
#secure: false
#httpOnly: false
-raw: false
-sameSite: null
}
]
and the value of $response is
Illuminate\Foundation\Testing\TestResponse {#843
+baseResponse: Illuminate\Http\RedirectResponse {#1040
#request: Illuminate\Http\Request {#856
#json: null
#convertedFiles: null
#userResolver: Closure {#916
class: "Illuminate\Auth\AuthServiceProvider"
this: Illuminate\Auth\AuthServiceProvider {#52 …}
parameters: {
$guard: {
default: null
}
}
use: {
$app: Illuminate\Foundation\Application {#19 …}
}
file: "./vendor/laravel/framework/src/Illuminate/Auth/AuthServiceProvider.php"
line: "85 to 87"
}
#routeResolver: Closure {#860
class: "Illuminate\Routing\Router"
this: Illuminate\Routing\Router {#167 …}
use: {
$route: Illuminate\Routing\Route {#204 …}
}
file: "./vendor/laravel/framework/src/Illuminate/Routing/Router.php"
line: "527 to 529"
}
+attributes: Symfony\Component\HttpFoundation\ParameterBag {#870
#parameters: []
}
+request: Symfony\Component\HttpFoundation\ParameterBag {#867
#parameters: array:2 [
"username" => "root"
"password" => "123"
]
}
+query: Symfony\Component\HttpFoundation\ParameterBag {#911
#parameters: []
}
+server: Symfony\Component\HttpFoundation\ServerBag {#871
#parameters: array:17 [
"SERVER_NAME" => "localhost.com"
"SERVER_PORT" => 80
"HTTP_HOST" => "localhost.com"
"HTTP_USER_AGENT" => "Symfony/3.X"
"HTTP_ACCEPT" => "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"
"HTTP_ACCEPT_LANGUAGE" => "en-us,en;q=0.5"
"HTTP_ACCEPT_CHARSET" => "ISO-8859-1,utf-8;q=0.7,*;q=0.7"
"REMOTE_ADDR" => "127.0.0.1"
"SCRIPT_NAME" => ""
"SCRIPT_FILENAME" => ""
"SERVER_PROTOCOL" => "HTTP/1.1"
"REQUEST_TIME" => 1531204718
"PATH_INFO" => ""
"REQUEST_METHOD" => "POST"
"CONTENT_TYPE" => "application/x-www-form-urlencoded"
"REQUEST_URI" => "/auth/login"
"QUERY_STRING" => ""
]
}
+files: Symfony\Component\HttpFoundation\FileBag {#878
#parameters: []
}
+cookies: Symfony\Component\HttpFoundation\ParameterBag {#869
#parameters: []
}
+headers: Symfony\Component\HttpFoundation\HeaderBag {#913
#headers: array:6 [
"host" => array:1 [
0 => "localhost.com"
]
"user-agent" => array:1 [
0 => "Symfony/3.X"
]
"accept" => array:1 [
0 => "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"
]
"accept-language" => array:1 [
0 => "en-us,en;q=0.5"
]
"accept-charset" => array:1 [
0 => "ISO-8859-1,utf-8;q=0.7,*;q=0.7"
]
"content-type" => array:1 [
0 => "application/x-www-form-urlencoded"
]
]
#cacheControl: []
}
#content: null
#languages: null
#charsets: null
#encodings: null
#acceptableContentTypes: null
#pathInfo: "/auth/login"
#requestUri: "/auth/login"
#baseUrl: ""
#basePath: null
#method: "POST"
#format: null
#session: Illuminate\Session\EncryptedStore {#924
#encrypter: Illuminate\Encryption\Encrypter {#919
#key: b"A╦k>ú8f\x10─ÌÜ8ØýxK\x01²┬Íî·»├\x1A³0▒S┘Ì"
#cipher: "AES-256-CBC"
}
#id: "XPMgecNkwFHbZbujhiuEaBqgMqFTLIqsuIzyvXv"
#name: "laravel_cookie"
#attributes: array:11 [
"_token" => "5lcOcLk9AqvSlWyLdHMKba1lJQ1UqD2rBBVCSav"
"locale" => "en"
"_previous" => array:1 [
"url" => "http://localhost.com/auth/login"
]
"_flash" => array:2 [
"old" => []
"new" => []
]
"sess_user_id" => 123
"sess_user_firstname" => "Foo"
"sess_user_lastname" => "Bar"
"sess_role" => "admin"
"login_web_59ba36add234f940abcf014c987ea4e30989d" => 123
]
#handler: Symfony\Component\HttpFoundation\Session\Storage\Handler\NullSessionHandler {#925
-sessionName: null
-prefetchId: null
-prefetchData: null
-newSessionId: null
-igbinaryEmptyData: "\x00\x00\x00\x02\x14\x00"
}
#started: false
}
#locale: null
#defaultLocale: "en"
-isHostValid: true
-isForwardedValid: true
basePath: ""
format: "html"
}
#session: Illuminate\Session\EncryptedStore {#924}
#targetUrl: "http://localhost.com/dashboard"
+headers: Symfony\Component\HttpFoundation\ResponseHeaderBag {#1039
#computedCacheControl: array:2 [
"no-cache" => true
"private" => true
]
#cookies: array:1 [
"" => array:1 [
"/" => array:1 [
"XSRF-TOKEN" => Symfony\Component\HttpFoundation\Cookie {#940
#name: "XSRF-TOKEN"
#value: "eyJpdiI6IjVyVmRNSmlcL1dYK0VOdiwj8RxamZBPT0iLCJ2YWx1ZSI6IjNSQWFzcVllSEIrSYwZnNNbk1vZ1NERVc2UVdJeGs91D6UG5hNGlHUmRnendJOUVtUnA3Rnk0TnVLYmI5UnJXSTlZR3dxS0wxMElmOFlaWDMzdG9RPT0iLCJtYWMiOiI0ZTZlNTAwNjFkZWFkOTEwN2M1Y2EzMGRjOWMzMmU4NzEzNmM5NWU2MzhhODFjOGJkYTU0YmZlMTM3M2ExNmE3In0="
#domain: null
#expire: 1531219118
#path: "/"
#secure: false
#httpOnly: false
-raw: false
-sameSite: null
}
]
]
]
#headerNames: array:5 [
"cache-control" => "Cache-Control"
"date" => "Date"
"location" => "Location"
"content-type" => "Content-Type"
"set-cookie" => "Set-Cookie"
]
#headers: array:4 [
"cache-control" => array:1 [
0 => "no-cache, private"
]
"date" => array:1 [
0 => "Tue, 10 Jul 2018 06:38:38 GMT"
]
"location" => array:1 [
0 => "http://localhost.com/dashboard"
]
"content-type" => array:1 [
0 => "text/html; charset=UTF-8"
]
]
#cacheControl: []
}
#content: """
<!DOCTYPE html>\n
<html>\n
<head>\n
<meta charset="UTF-8" />\n
<meta http-equiv="refresh" content="0;url=http://localhost.com/dashboard" />\n
\n
<title>Redirecting to http://localhost.com/dashboard</title>\n
</head>\n
<body>\n
Redirecting to http://localhost.com/dashboard.\n
</body>\n
</html>
"""
#version: "1.1"
#statusCode: 302
#statusText: "Found"
#charset: null
+original: null
+exception: null
}
}
So obviously, the session cookie is not in $response->headers->getCookies(), and I don't use actingAs() is because after user successful login, will set a few session values, i.e. sess_user_id, sess_user_firstname, sess_user_lastname, sess_role...
For the first case I would just make a post request and check if the cookie is present or not.
$response = $this->post($this->base_url . '/auth/login', [
'username' => 'root',
'password' => '123',
]);
$response->assertCookieNotExpired($cookieName);
Note: you can get cookies from headers using. $response->headers->getCookies(); but I don't think we need them in our case.
Now we know our authentication works we can use Laravel actingAs helper method for authentication and then make requests as follows.
$user = // get your user.
$response = $this->actingAs($user)->post($this->base_url . '/step1', [
'attr_1' => 'foo',
'attr_2' => 'bar',
]);
Make all kinds of assertion you like (check for cookies, sessions whatever you like)
$response->assertSessionHas($key, $value);
Before we move to the third case you should know that it's better to test each section separately. In simple words your tests shouldn't depend on each other, so what we can do for the third case? We know our third case depends on the second and we have already the tested the previous processes. Now we just want to test if our third case is working or not. So why not we add the session values required for this request ourselves using Laravel helper withSession.
$response = $this->actingAs($user)
->withSession(['foo' => 'bar'])
->post($this->base_url . '/step2', [
'attr_1' => 'abc',
'attr_2' => 'xyz',
]);
Now you can again make assertions. Check list of all available assertions.
Install Mockery Mockery is a simple yet flexible PHP mock object framework for use in unit testing with PHPUnit
composer require mockery/mockery --dev
LoginController
public function authenticate(Request $request)
{
$credentials = $request->only('email', 'password');
if (Auth::attempt($credentials)) {
// Authentication passed...
// Get the currently authenticated user...
$user = Auth::user();
return redirect()->route('profile');
}else{
return redirect()->intended('loginform');
}
}
Example Test
public function testLoginSuccess()
{
$credential = [
'email' => 'xxx',
'password' => 'yyy'
];
Auth::shouldReceive('attempt')->once()->withAnyArgs()->andReturn(true);
Auth::shouldReceive('user')->once()->withAnyArgs()->andReturn(true);
$response = $this->post('/login',$credential);
$response->assertRedirect('/profile');
}
This example show you how to mock Auth Facades in unit test.
Auth::attempt return true
Auth::user return true
You can use Mockery to mock object as you want.
Check phpunit.xml, by default the value of SESSION_DRIVER is set 'array', change it to 'file'

Google Contacts API call return Response ok but empty JSON

Currently building a Laravel app that uses the Socialite package to successfully authenticate users using their Google credentials. However, I'm trying to make a GET request to the Google server to retrieve a given user's contact list, I have been experimenting a bit on Google oAuth 2 Playground and tried to emulate the same request inside my App. I created the following function :
public function getContactList()
{
$client = new \GuzzleHttp\Client();
$email = \Auth::user()->email;
$token = \Session::get('token');
$json = $client->get('https://www.google.com/m8/feeds/contacts/default/full/', [
'headers' => [
'Authorization' => 'Bearer ' . $token,
],
]);
dd($json);
return $json;
}
Following an endless struggle to get past forbidden responses, I finally get a positive one but it's of no use, there's nothing in the body, decoding it with Json_decode gives null, here's the response :
Response {#198 ▼
-reasonPhrase: "OK"
-statusCode: 200
-effectiveUrl: "https://www.google.com/m8/feeds/contacts/default/full/"
-headers: array:11 [▼
"expires" => array:1 [▼
0 => "Mon, 30 Mar 2015 15:19:52 GMT"
]
"date" => array:1 [▼
0 => "Mon, 30 Mar 2015 15:19:52 GMT"
]
"cache-control" => array:1 [▶]
"vary" => array:2 [▶]
"content-type" => array:1 [▶]
"x-content-type-options" => array:1 [▶]
"x-frame-options" => array:1 [▶]
"x-xss-protection" => array:1 [▶]
"content-length" => array:1 [▶]
"server" => array:1 [▶]
"alternate-protocol" => array:1 [▶]
]
-headerNames: array:11 [▼
"expires" => "Expires"
"date" => "Date"
"cache-control" => "Cache-Control"
"vary" => "Vary"
"content-type" => "Content-Type"
"x-content-type-options" => "X-Content-Type-Options"
"x-frame-options" => "X-Frame-Options"
"x-xss-protection" => "X-XSS-Protection"
"content-length" => "Content-Length"
"server" => "Server"
"alternate-protocol" => "Alternate-Protocol"
]
-body: Stream {#197 ▼
-stream: :stream {#8 ▼
wrapper_type: "PHP"
stream_type: "TEMP"
mode: "w+b"
unread_bytes: 0
seekable: true
uri: "php://temp"
options: []
}
-size: null
-seekable: true
-readable: true
-writable: true
-uri: "php://temp"
-customMetadata: []
}
-protocolVersion: "1.1"
}
What can I change or what do I need to change to get the full list of contacts instead of a empty 200 response ?
UPDATE: I have made a few tests to verify the accuracy of my requests, and found out that the above request actually return an ATOM feed, which might be the problem. When I made requests to Drive APIs which returned JSON responses, I could extract without any trouble the appropriate data just by parsing it using json_decode. Which function do I need to use to parse ATOM data within PHP to be able to retrieve it ?
Have you tried to add the 'alt=json' parameter to your GET request ? Like so :
$response = $client->get('https://www.google.com/m8/feeds/contacts/default/full?alt=json', [
'headers' => [
'Authorization' => 'Bearer ' . $token,
],
]);
I have been trying to get the contacts API in JSON and it looked like this is the proper way :
https://developers.google.com/google-apps/contacts/v3/reference#contacts-query-parameters-reference
You're getting a Response object from Guzzle. There is a json method available on the Response object, so you should be able to:
$response = $client->get('https://www.google.com/m8/feeds/contacts/default/full/', [
'headers' => [
'Authorization' => 'Bearer ' . $token,
],
]);
echo $response->json();
Source: http://guzzle.readthedocs.org/en/latest/http-messages.html#id2

Resources