PHP Pusher Event Triggering not working - javascript

I am a newbie when it comes to WebSockets, and I recently came across Pusher. I wanted to integrate it in my website. I am trying to trigger an event via the Pusher.php file, and here is my code:
$pusherArray['success'] = true;
$pusher = new Pusher( $PUSHER_APP_KEY, $PUSHER_APP_SECRET, $PUSHER_APP_ID );
class MyLogger {
public function log( $msg ) {
print_r( $msg . "\n" );
}
}
$pusher->set_logger( new MyLogger() );
$pusher->trigger('8307851079', 'logout', $pusherArray);
$info = $pusher->get_channel_info("$clef_id");
$channel_occupied = $info->occupied;
var_dump($channel_occupied);
And then this is the result I get:
Pusher: curl_init( http://api.pusherapp.com:80/apps/217851/events?auth_key=MY_KEY&auth_signature=SIGNATURE&auth_timestamp=1466342695&auth_version=1.0&body_md5=41b74623d1e5f479b466093805ff36de )
Pusher: trigger POST: {"name":"logout","data":"{\"success\":true}","channels":8307851079}
Pusher: exec_curl response: Array
(
[body] => Expected channels parameter to be an array
[status] => 400
)
Pusher: curl_init( http://api.pusherapp.com:80/apps/217851/channels/8307851079?auth_key=MY_KEY&auth_signature=SIGNATURE&auth_timestamp=1466342696&auth_version=1.0 )
Pusher: exec_curl response: Array
(
[body] => 404 NOT FOUND
[status] => 404
)
NULL
The event is not getting triggered! Need some help!

I got it to work eventually. What had happened was that the view channel info method was causing the error. I did not have proper syntax.
And as pointed out by Rob, the first argument of the trigger function required it to be an array. I changed that and got the script to work. Here's the brief code:
$pusherArray['success'] = true;
$pusher = new Pusher( $PUSHER_APP_KEY, $PUSHER_APP_SECRET, $PUSHER_APP_ID );
class MyLogger { public function log( $msg ) { print_r( $msg . "\n" ); } }
$pusher->set_logger( new MyLogger() );
$pusher->trigger(['8307851079'], 'logout', $pusherArray);
I just simply removed the view channel info because I didn't really need that function. Got a 200 OK status code and my script was able to deliver the
"success":true
Message to the Pusher service.

Related

PayPal Smart Payment Buttons: Error: JSON.parse: unexpected character at line 1 column 1 of the JSON data

I've been trying to figure out this problem for 2 days already..
I want to implement Smart Payment Buttons from PayPal, literally followed every step of the explanation closely but still getting following error:
Error: JSON.parse: unexpected character at line 1 column 1 of the JSON data
My javascript for Button rendering:
paypal.Buttons({
createOrder: function() {
return fetch('vendor/paypal/paypal-checkout-sdk/samples/CaptureIntentExamples/CreateOrder.php', {
method: 'post',
headers: {
'content-type': 'application/json'
}
}).then(function(res) {
return res.json();
}).then(function(data) {
return data.orderID; // Use the same key name for order ID on the client and server
});
},
onApprove: function(data, actions) {
// This function captures the funds from the transaction.
return actions.order.capture().then(function(details) {
// This function shows a transaction success message to your buyer.
alert('Transaction completed by ' + details.payer.name.given_name);
});
},
onError: function(err) {
alert(err);
}
}).render('#paypal-button-container');
My CreateOrder.php:
namespace Sample\CaptureIntentExamples;
require __DIR__ . '/../../../../autoload.php';
use Sample\PayPalClient;
use PayPalCheckoutSdk\Orders\OrdersCreateRequest;
class CreateOrder
{
/**
* Setting up the JSON request body for creating the Order. The Intent in the
* request body should be set as "CAPTURE" for capture intent flow.
*
*/
private static function buildRequestBody()
{
return array(
'intent' => 'CAPTURE',
'application_context' =>
array(
'return_url' => 'https://example.com/return',
'cancel_url' => 'https://example.com/cancel'
),
'purchase_units' =>
array(
0 =>
array(
'amount' =>
array(
'currency_code' => 'USD',
'value' => '220.00'
)
)
)
);
}
/**
* This is the sample function which can be sued to create an order. It uses the
* JSON body returned by buildRequestBody() to create an new Order.
*/
public static function createOrder($debug=false)
{
$request = new OrdersCreateRequest();
$request->headers["prefer"] = "return=representation";
$request->body = self::buildRequestBody();
$client = PayPalClient::client();
$response = $client->execute($request);
if ($debug)
{
print "Status Code: {$response->statusCode}\n";
print "Status: {$response->result->status}\n";
print "Order ID: {$response->result->id}\n";
print "Intent: {$response->result->intent}\n";
print "Links:\n";
foreach($response->result->links as $link)
{
print "\t{$link->rel}: {$link->href}\tCall Type: {$link->method}\n";
}
// To toggle printing the whole response body comment/uncomment below line
echo json_encode($response->result, JSON_PRETTY_PRINT), "\n";
}
return $response;
}
}
if (!count(debug_backtrace()))
{
CreateOrder::createOrder(true);
}
It's basicly all copied from the PayPal walkthough.
If I visit the CreateOrder.php directly it is creating an order and I can see the response without errors.
Status Code: 201 Status: CREATED [...]
What I did was deleting the part of the code which was printing out the response in txt format. This is why you were getting JSON syntax error.
public static function createOrder($debug=false)
{
$request = new OrdersCreateRequest();
$request->prefer('return=representation');
$request->body = self::buildRequestBody();
// 3. Call PayPal to set up a transaction
$client = PayPalClient::client();
$response = $client->execute($request);
// To print the whole response body, uncomment the following line
echo json_encode($response->result, JSON_PRETTY_PRINT);
// 4. Return a successful response to the client.
return $response;
}
By the way, this answer is very helpful: https://stackoverflow.com/a/63019280/12208549

How to fix WebPush 401 error for Google Chrome?

I'm trying to develop my own notification system on my website but I have a problem. I use firebase and his keys (I'm not using VapidKeys). One thing : every works on Firefox but not on Google Chrome.
For my application I followed this link.
and others tutorial on how does firebase works...
<?php
include_once (getenv('DOCUMENT_ROOT') . '/lib/include.php');
...
use Minishlink\WebPush\WebPush;
use Minishlink\WebPush\Subscription;
use Minishlink\WebPush\VAPID;
array of notifications
$notifications = array(
array(
'subscription' => Subscription::create(array(
'endpoint' => 'https://updates.push.services.mozilla.com/wpush/v1/gAAAAABcyExVQOIq3T0hJlKO6awqMrGwo0kcjjqi5mYKLddIfKcvva-2AcIMY1f1X32Zpdo3IlOqKb00eOhgUI_TTYMdmSwA6VxUjsQPgZwFmDQuvWjYnvax6yuV-WraBE9MclHMou6G', // Firefox 43+,
'publicKey' => 'BKVJQAkW1OFebroeetQBX1gVsDXQIs8TRYOk0b7ENCK3NBhOCxqCN2uAAZ5wQq7lqS0AqTu5qkKzNHH2oMQAJes', // base 64 encoded, should be 88 chars
'authToken' => 'PTYrPzIoW96SnYjjmSPvrg', // base 64 encoded, should be 24 chars
)
),
'payload' => 'hello !',
),
array(
'subscription' => Subscription::create(array(
'endpoint' => 'https://fcm.googleapis.com/fcm/send/dgSeLeTBqQs:APA91bGWVsUbkd5R9jOyqjDx5PMzuDtse1X9jGtJ3D_G_1wPehNFCq9-aEkyVSdqnzkuv5pbetE8k0rU_XrSGNvZ6WVG-7zZQJha_WvVK8zvUkGUxBsKzF6kPYMIDGZ6Qx2VjrWIbePS',
)
),
'payload' => null,
)
);
$webPush = new WebPush();
// send multiple notifications with payload
foreach ($notifications as $notification) {
$webPush->sendNotification(
$notification['subscription'],
$notification['payload'] // optional (defaults null)
);
}
foreach ($webPush->flush() as $report) {
$endpoint = $report->getRequest()->getUri()->__toString();
if ($report->isSuccess()) {
echo "[v] Message sent successfully for subscription {$endpoint}.";
} else {
echo "[x] Message failed to sent for subscription {$endpoint}: {$report->getReason()}";
}
}

How to send FCM web data messages to a specific open tab of that website using PHP and Javascript

I am sending a CURL of data message to https://fcm.googleapis.com/fcm/send using my endpoint.
The issue I am facing is I have multiple open tabs of my website. I want to receive data only on specific tab. But currently I am getting data message on another tab where that message is of no use. Can we send that data message to a specific page or to all open tabs. I am new on FCM and have a little knowledge regarding this. Below I am pasting my onMessage() event code.
messaging.onMessage ( function ( payload )
{
if ( typeof payload.notification !== "undefined" )
{
var notificationTitle = payload.notification.title;
var notificationURL = payload.notification.click_action;
var notificationOptions =
{
body: payload.notification.body,
icon: payload.notification.icon,
badge: payload.notification.badge,
subtitle: payload.notification.subtitle
};
navigator.serviceWorker.ready.then ( function ( )
{
var notification = new Notification ( notificationTitle, notificationOptions );
notification.onclick = function ( event )
{
event.preventDefault();
window.open ( notificationURL, '_blank' );
}
});
}
else
{
init_todo_room
(
payload.data.todo_room,
payload.data.title,
payload.data.icon,
payload.data.remove_header,
payload.data.remove_tools,
"",
payload.data.remove_user,
payload.data.data,
);
}
}
I don't know how to achieve that. My basic goal is that I want to reduce AJAX calls using FCM and load data on page as fast as I can. Therefore I am using data messages to initiate the modules of my webpage. Any help is appreciated. Thanks

Semantic-UI search does not read JSON from server response

I'm currently using Semantic-UI in a project. I use the search module to get the results from input. Here's my JavaScript code:
$('.ui.search')
.search({
apiSettings: {
action: 'search',
url: 'process.php?q={query}',
onSuccess(response, element, xhr){
console.log(response);
}
},
fields: {
results: 'songs', // array of results (standard)
title: 'title', // result title
url: 'videoID'
},
showNoResults: true,
onResults(response) {
console.log(response);
}
})
;
I get the JSON response from process.php. Here it is:
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
header("Content-Type: application/json; charset=UTF-8");
if (!file_exists(__DIR__ . '/vendor/autoload.php')) {
throw new \Exception('please run "composer require google/apiclient:~2.0" in "' . __DIR__ .'"');
}
require_once __DIR__ . '/vendor/autoload.php';
// This code will execute if the user entered a search query in the form
// and submitted the form. Otherwise, the page displays the form above.
$videos = array();
// $videos["action"]["url"] = "youtube.com";
if (isset($_GET['q'])) {
/*
* Set $DEVELOPER_KEY to the "API key" value from the "Access" tab of the
* {{ Google Cloud Console }} <{{ https://cloud.google.com/console }}>
* Please ensure that you have enabled the YouTube Data API for your project.
*/
$DEVELOPER_KEY = 'MY_API_KEY';
$client = new Google_Client();
$client->setDeveloperKey($DEVELOPER_KEY);
// Define an object that will be used to make all API requests.
$youtube = new Google_Service_YouTube($client);
try {
// Call the search.list method to retrieve results matching the specified
// query term.
$searchResponse = $youtube->search->listSearch('id,snippet', array(
'q' => $_GET['q'],
'maxResults' => 2
));
// Add each result to the appropriate list, and then display the lists of
// matching videos, channels, and playlists.
foreach ($searchResponse['items'] as $searchResult) {
switch ($searchResult['id']['kind']) {
case 'youtube#video':
$videos["songs"][] = array('title' => $searchResult['snippet']['title'], 'videoID' => $searchResult["id"]["videoId"]);
break;
}
}
} catch (Google_Service_Exception $e) {
die($e->getMessage());
}
}
echo json_encode($videos);
The problem is that once I start typing in the search input, nothing shows up, even though my JSON structure is valid. I have assigned the Semantic UI properties correctly. I'm following the standard JSON response that Semantic UI has suggested. Here's my JSON response
{
"songs":[
{
"title":"Wiz Khalifa - See You Again ft. Charlie Puth [Official Video] Furious 7 Soundtrack",
"videoID":"RgKAFK5djSk"
},
{
"title":"Wiz Khalifa - See You Again ft. Charlie Puth (MattyBRaps ft Carissa Adee Cover)",
"videoID":"Rpm8ZJuGEu4"
}
]
}
I've tried everything. It doesn't work. I would really appreciate your help

Update text in block with Nodejs integration module in drupal 8

Below is information what I have done till now and what I am trying to do.
What I have done till now
Nodejs module and drupal 8 done. Example modules are working fine.
Created a simple module in drupal 8 consists of a form called simple
form. On its submit function, called nodejs module function to enqueue my message to the channel.
Javascript callback function created defined in nodejs enqueue message.
What I have been trying to acheive
When submitting a text form. Just to update the block in drupal 8.( Update the block content with hello world.)
Problem
My javascript callbacks associated with nodejs aren't being called.
Below are my codes.
Submit Function Code
public function submitForm(array &$form, FormStateInterface $form_state) {
/*$message->broadcast = TRUE;
* This would normally be replaced by code that actually does something
* with the title.
*/
$title = $form_state->getValue('title');
$message = (object) array(
'channel' => 'example',
'broadcast' => TRUE,
'callback' => 'example',
'data' => array(
'message' => 'Hello World'
),
);
nodejs_enqueue_message($message);
drupal_set_message(t('You specified a title of %title.', ['%title' => $title]));
}
Javascript callback code
(function ($) {
Drupal.Nodejs.callbacks.example = {
//grab the message and inject into the header
callback: function (message) {
console.log('simple example');
if(message.channel == 'example') {
$('#nodejs-selector').html(message.data.body);
}
}
};
})(jQuery);
Any help on this, I would be very grateful. I would love to provide more information on this, if anyone needed.
You should modify $message as
$message = (object) array(
'channel' => 'example',
'broadcast' => TRUE,
'callback' => 'example',
'data' => array(
'body' => 'Hello World'
),
);
To access the message body as message.data.body

Categories

Resources