How to fix WebPush 401 error for Google Chrome? - javascript

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()}";
}
}

Related

How to pass JSON response in PHP to Javascript

I have problems passing a JSON request from PHP to Javascript. I am sending a request to my Flask RESTful API and I'm recieving a JSON reponse (I believe).
PHP:
$urlContents = file_get_contents("http://192.168.2.201:5000/dataprovider", false, $context);
$travelArray = json_decode($urlContents);
My Object looks like this:
stdClass Object
(
[1] => stdClass Object
(
[var1] =>
[var2] =>
[var3] => 763
[var4] => 6:22:30
[var5] => München
[var6] => 58
[var7] => Bremen
[var8] => 239
)
[2] => stdClass Object
(
[var1] =>
[var2] =>
[var3] => 145
[var4] => 3:12:23
[var5] => München
[var6] => 583
[var7] => Bremen
[var8] => 9
)
)
JavaScript
<script type="text/javascript">
var response = JSON.parse('<?php echo $travelArray; ?>');
if (response != null) {
console.log(response);
} else {
console.log("test");
}
</script>
When I press F12 and look into sources it says:
var response = JSON.parse('<br />
<b>Recoverable fatal error</b>: Object of class stdClass could not be converted to string in <b>/var/www/html/greenTravelWizard.php</b> on line <b>83</b><br />
I have tried several things like using $urlContents instead of $travelArray in the JavaScript part ([1]: https://i.stack.imgur.com/Tujy3.png), but I haven't figured out how to correctly pass the JSON to a correct JavaScript format.
Also when I haven't send the request via the form yet I get
Notice: Undefined variable: context in /var/www/html/greenTravelWizard.php on line 83 Warning: file_get_contents(192.168.2.201:5000/dataprovider): failed to open stream: HTTP request failed! HTTP/1.0 405 METHOD NOT ALLOWED in /var/www/html/greenTravelWizard.php on line 83
You should not decode it unless you encode it before echoing
You can likely just do
var response = <?php echo $file_get_contents("http://192.168.2.201:5000/dataprovider", false, $context); ?>;
If you have written a proxy, then you just need to do
<?php
header("content-type: application/json");
echo file_get_contents("http://192.168.2.201:5000/dataprovider", false, $context);
?>
and then use fetch to get it from your server

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

PHP Pusher Event Triggering not working

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.

How to use instafeed.js to get logged in users images

I'm building an application where users can click a button to show all of their Instagram images on a page, but in order to do that I need userId and accessToken. How do I get these?
NOTE: If it makes any difference: I'm not trying to get just my own images, but anyone who uses my app to log into their account.
I have this code:
<script>
var feed = new Instafeed ({
get: "user",
userId: ,
accessToken: ""
});
feed.run();
</script>
<div id="instafeed"></div>
And I get a verification code by clicking on a link (note I removed cliend_id and redirect_uri):
Get Instagram images
Then this returns a code like '1251251...' which I grab with GET, but after that what do I do? How do I get userId and accesToken from this?
I'm not sure if I'm on the right track, but any help would be appreciated!
Answering my own question, as I figured it out:
$url = 'https://api.instagram.com/oauth/access_token';
$data = array(
'client_id' => $clientId,
'client_secret' => $clientSecret,
'grant_type' => 'authorization_code',
'redirect_uri' => $redirectUri,
'code' => $code
);
// use key 'http' even if you send the request to https://...
$options = array(
'http' => array(
'header' => "Content-type: application/x-www-form-urlencoded\r\n",
'method' => 'POST',
'content' => http_build_query($data),
),
);
$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);
$clientId, $clientSecret and $redirectUri are taken from: https://instagram.com/developer/clients/manage/
$code is the code from your url and $result contains the userId and accessToken if successful.
Thanks to: How do I send a POST request with PHP?

Posting a link with image and text to Facebook wall

I am trying to replicate the functionality to share a story on a Facebook wall similar to what this site has.
When you click on the share it should ask you to authenticate to facebook, if you are already authenticated it should show you the story to post to facebook.
I got the authentication part to work using the JavaScript SDK . I am not sure how to show the content to post to the wall.
Could anyone please provide an example.
Thanks!
<?php
# We require the library
require("facebook.php");
# Creating the facebook object
$facebook = new Facebook(array(
'appId' => 'YOUR_APP_ID',
'secret' => 'YOUR_APP_SECRET',
'cookie' => true
));
# Let's see if we have an active session
$session = $facebook->getSession();
if(!empty($session)) {
# Active session, let's try getting the user id (getUser()) and user info (api->('/me'))
try{
$uid = $facebook->getUser();
# let's check if the user has granted access to posting in the wall
$api_call = array(
'method' => 'users.hasAppPermission',
'uid' => $uid,
'ext_perm' => 'publish_stream'
);
$can_post = $facebook->api($api_call);
if($can_post){
# post it!
# $facebook->api('/'.$uid.'/feed', 'post', array('message' => 'Saying hello from my Facebook app!'));
# using all the arguments
$facebook->api('/'.$uid.'/feed', 'post', array(
'message' => 'The message',
'name' => 'The name',
'description' => 'The description',
'caption' => 'The caption',
'picture' => 'http://i.imgur.com/yx3q2.png',
'link' => 'http://net.tutsplus.com/'
));
echo 'Posted!';
} else {
die('Permissions required!');
}
} catch (Exception $e){}
} else {
# There's no active session, let's generate one
$login_url = $facebook->getLoginUrl();
header("Location: ".$login_url);
}
?>
http://developers.facebook.com/docs/reference/api/post/

Categories

Resources