I'm using PHP to send browser notifications through cURL (with Firebase) and while notifications are sent to their destination (desktop and mobile browsers), I'm facing two problems:
Each time I send a notification, I get two notifications in the browser. One with the content I have defined (see below) and one empty but considered as a background notification. I think it has something to do with active window but I don't know how to go around this.
When I click on the notification I have received, the link is never working.
I use the following code to send the notification:
$msg = urlencode($message);
$
$data = array(
'title'=>"My title",
'sound' => "default",
'msg'=>"my message",
'data'=>$datapayload,
'body'=>"message",
'color' => "#FF33CC",
'link' => "mylink"
);
if($img)
{
$data["image"] = "xxx";
$data["style"] = "picture";
$data["picture"] = "xxx";
}
$fields = array(
'to'=>$to,
'notification'=>$data,
"priority" => "high",
"link"=>"mylink",
"data"=>$data
);
$headers = array(
'Authorization: key=xxxx',
'Content-Type: application/json'
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://fcm.googleapis.com/fcm/send');
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
$result = curl_exec($ch);
curl_close( $ch );
When I send notifications with this script, I get the following output from the cURL request:
{"multicast_id":xxx,"success":1,"failure":0,"canonical_ids":0,"results":[{"message_id":"xxx"}]}
And here is an example of the JSON send to FCM:
Array
(
[to] => xxx
[notification] => Array
(
[title] => Notification pour Chrome Samsung
[sound] => default
[msg] => blablabla
[data] => Array
(
[ID] => xxxx
)
[body] => blablabla
[color] => #FF33CC
[link] => https://www.something.com
[image] => https://www.something.com/logo.png
[style] => picture
[picture] => https://www.something.com/logo.png
)
[priority] => high
[link] => https://www.something.com
[data] => Array
(
[title] => blabla
[sound] => default
[msg] => blablabla
[data] => Array
(
[ID] => 653804269445
)
[body] => blablabla
[color] => #FF33CC
[link] => https://www.something.com
[image] => https://www.something.com/logo.png
[style] => picture
[picture] => https://www.something.com/logo.png
)
)
I have tried to use only data or only notification but I still end up with 2 non clickable messages. I saw "click_action" in the documentation but it looks like it was only to be used for Android devices.
Any idea?
Thanks!
Update: the generic messages I get in the notification are obviously coming from the service worker but no matter what I do, updating the service worker doesn't seem to change anything.
Related
I am getting errors like: Bad Request: chat not found when I want to forward a message from a group where the bot is an administrator.
Scenario:
A public group called #PucciPruebas where the bot (#Comitentesbot) is an admin along with me (#fpucci).
A test user (#fernandoPucci)
I (#fpucci) and the test user (#fernandopucci) have previously written to the bot privately.
The idea is that when a member writes in the group, the bot forwards the message to me privately.
When I write in the group for example This is a test message, the bot receives this data:
Array (
[update_id] => 768460433
[message] => Array (
[message_id] => 8
[from] => Array (
[id] => 1026410801
[is_bot] =>
[first_name] => ??????????????????????¸ ???
[last_name] => ???????????????
[username] => FPucci
[language_code] => es
)
[chat] => Array (
[id] => -1001511892400
[title] => PucciPruebas
[username] => PucciPublico
[type] => supergroup
)
[date] => 1653597954
[text] => This is a test message
)
)
The code in PHP is:
$tipo = $datain["message"]["chat"]["type"];
$chatid = $datain["message"]["chat"]["id"];
$msgid = $datain["message"]["message_id"];
$title = $datain["message"]["chat"]["title"];
if ("private"==$tipo || "PucciPruebas"==$title)
Reenviar("#fpucci", $chatid, $msgid);
function Reenviar ($a_chat, $from_chat, $message){
global $chatId, $comitentesapi;
$params=[
'chat_id' => "$a_chat",
'from_chat_id' => "$from_chat",
'message_id' => "$message",
];
$ch = curl_init("$comitentesapi/forwardMessage");
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, ($params));
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$result = curl_exec($ch);
curl_close($ch);
}
So, what am I missing, forgetting, or doing wrong?
---------edit--------
I append after the curl_close($ch), the following line as other way to send the message, and get the same result:
file_get_contents("$comitentesapi/forwardMessage?disable_notification=true&chat_id=$a_chat&from_chat_id=$from_chat&message_id=$message&parse_mode=HTML");
I tried to do my first API calls which worked finally with help from this great users here in this community. Thanks again. I want to choose data[1] or the currency with symbol. So i could use a $variable from my CMS. Maybe someone can show me a way how i can change this call to symbol. Here is my API call.
$url = "https://pro-api.coinmarketcap.com/v1/cryptocurrency/listings/latest";
$headers = [
'Accepts: application/json',
'X-CMC_PRO_API_KEY: ___YOUR_API_KEY_HERE___'
];
$request = "{$url}"; // create the request URL
$curl = curl_init(); // Get cURL resource
// Set cURL options
curl_setopt_array($curl, array(
CURLOPT_URL => $request, // set the request URL
CURLOPT_HTTPHEADER => $headers, // set the headers
CURLOPT_RETURNTRANSFER => 1 // ask for raw response instead of bool
));
$response = curl_exec($curl); // Send the request, save the response
$json = json_decode($response);
curl_close($curl); // Close request
$price = $json->data[1]->quote->USD->price; echo $price;
You get the data block IDs with array_column(), then you get the symbol's data block ID with array_search():
$data_ids = array_column($json->data, 'symbol');
$symbol_data_id = array_search('ETH', $data_ids);
$price = $json->data[$symbol_data_id]->quote->USD->price;
Or as an oneliner:
$price = $json->data[array_search('ETH', array_column($json->data, 'symbol'))]->quote->USD->price;
LATER UPDATE: OK, let me elaborate on this. Step by step:
You need a proper URL to acces the API. For this you need the API documentation. Your original question mentioned
$url = "https://pro-api.coinmarketcap.com/v1/cryptocurrency/listings/latest";
while for your comment question you need something like
$url = "https://pro-api.coinmarketcap.com/v1/cryptocurrency/info?symbol=ETH";
A proper URL will give you a JSON response structured according to its purpose. You have this part ironed out, so I'll not insist on this. From your question text:
$headers = [
'Accepts: application/json',
'X-CMC_PRO_API_KEY: 1b58ff56-58b2-4fd0-b184-f9c3dd4ff106',
];
$request = "{$url}"; // create the request URL
$curl = curl_init(); // Get cURL resource
// Set cURL options
curl_setopt_array($curl, [
CURLOPT_URL => $request, // set the request URL
CURLOPT_HTTPHEADER => $headers, // set the headers
CURLOPT_RETURNTRANSFER => 1, // ask for raw response instead of bool
]);
$response = curl_exec($curl); // Send the request, save the response
$json = json_decode($response);
curl_close($curl); // Close request
Then you have to decide how to use the response. For me, the fastest way is to look at its structure (var_dump($json) or print_r($json)). Which will give something like this (the original question):
stdClass Object
(
[status] => stdClass Object
(
[timestamp] => 2021-11-06T18:37:59.447Z
[error_code] => 0
[error_message] =>
[elapsed] => 22
[credit_count] => 1
[notice] =>
[total_count] => 7060
)
[data] => Array
(
[0] => stdClass Object
(
[id] => 1
[name] => Bitcoin
[...]
)
[1] => stdClass Object
(
[id] => 1027
[name] => Ethereum
[symbol] => ETH
[slug] => ethereum
[...]
[quote] => stdClass Object
(
[USD] => stdClass Object
(
[price] => 4445.0743486785
[volume_24h] => 14137477206.072
[volume_change_24h] => -9.6622
[percent_change_1h] => 0.2898806
[percent_change_24h] => -1.29677209
[percent_change_7d] => 3.13286959
[percent_change_30d] => 23.49191199
[percent_change_60d] => 28.79913805
[percent_change_90d] => 48.37310902
[market_cap] => 525560956659.07
[market_cap_dominance] => 19.5198
[fully_diluted_market_cap] => 525560956659.07
[last_updated] => 2021-11-06T18:37:03.000Z
)
)
)
[2] => stdClass Object [...]
or this (the question in the comment):
stdClass Object
(
[status] => stdClass Object
(
[timestamp] => 2021-11-06T18:03:05.201Z
[error_code] => 0
[error_message] =>
[elapsed] => 12
[credit_count] => 1
[notice] =>
)
[data] => stdClass Object
(
[ETH] => stdClass Object
(
[id] => 1027
[name] => Ethereum
[symbol] => ETH
[category] => coin
[description] => Ethereum (ETH) is a cryptocurrency . Users are able to generate ETH through the process of mining. Ethereum has a current supply of 118,233,336.749. The last known price of Ethereum is 4,424.33123326 USD and is down -1.39 over the last 24 hours. It is currently trading on 4537 active market(s) with $14,138,162,060.93 traded over the last 24 hours. More information can be found at https://www.ethereum.org/.
[...]
[platform] =>
[date_added] => 2015-08-07T00:00:00.000Z
[twitter_username] => ethereum
[is_hidden] => 0
)
)
)
So data is a property of the $json object.
In the first case, data is an array and its structure suggests using array functions to retrieve specific data.
In the second case, data and ETH are objects, while description is a property of ETH. Which allows me to get the description using object syntax
$description = $json->data->ETH->description;
I am trying to connect to the external site and get the products there and copy them to another site by using its consumer and secret keys.
I have the a URL Link that links from an External Site1.
Now I get all the JSON Data (including sales, images, data etc.) by using PHP CURL
Here is the code:
function get_wc_api_client() {
$curl = curl_init();
$site = 'https://samplelink.com/wp-json/wc/v2/products?consumer_key=sample-consumer_key&consumer_secret=sample_consumer_secret';
curl_setopt($curl, CURLOPT_URL, $site );
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 60);
$content = curl_exec($curl);
echo "<pre>";
print_r( json_decode($content, true)) ;
echo "</pre>";
}
Any recommendations how to just get the IMAGES and the TITLE of the PRODUCT of the external site, plus the links of each products and display them as a full images and text not JSON text ?
Thanks in advance
UPDATES:
Here is the example code of the Result for the print_r
Array
(
[0] => Array
(
[id] => 4591
[name] => Magic Forest
[slug] => magic-forest
[permalink] => https://samplesite.com/product/magic-forest/
[date_created] => 2019-03-13T19:11:09
[date_created_gmt] => 2019-03-13T19:11:09
[date_modified] => 2019-03-13T19:12:20
[date_modified_gmt] => 2019-03-13T19:12:20
[type] => simple
[status] => publish
[featured] =>
[catalog_visibility] => visible
[description] =>
but as I said, I only need the IMAGE, TITLE of the Products and their links and VIEW them as real IMAGE and TITLE and Link.
[images] => Array
(
[0] => Array
(
[id] => 4932
[date_created] => 2019-03-13T18:54:54
[date_created_gmt] => 2019-03-13T18:54:54
[date_modified] => 2019-03-13T18:55:14
[date_modified_gmt] => 2019-03-13T18:55:14
[src] => https://samplesite.com/wpcom-129014632/wp-content/uploads/2019/03/Pond-image.jpg
[name] => Pond Cover
[alt] =>
[position] => 0
)
FOR IMAGE: I needed the image src link to be a Real image when executed, also the title of the product.
Is it possible?
Use below code
function get_wc_api_client() {
$curl = curl_init();
$site = 'https://samplelink.com/wp-json/wc/v2/products?consumer_key=sample-consumer_key&consumer_secret=sample_consumer_secret';
curl_setopt($curl, CURLOPT_URL, $site );
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 60);
$content = curl_exec($curl);
return json_decode($content, true);
}
Call this function in your view page
$apiData = get_wc_api_client();
foreach($apiData['images'] as $data){
echo '<image src="'.$data['src'].'" title="'.$data['name'].'" alt="'.$data['alt'].'">';
}
I've been working on this SoundCloud website for awhile now and have just got into creating a stream page alternative that will display on our website. I have stumbled into an issue however and I'm sure it's an easy solution I'm just now figuring out how 2 achieve the proper output.
$user_ID = $_GET['id'];
$sc = curl_init();
curl_setopt($sc, CURLOPT_URL, 'http://api.soundcloud.com/users/'.$user_ID.'/followings?client_id='.$client_ID.'&page_size=200&cursor=1419617528000');
curl_setopt($sc, CURLOPT_HEADER, 0);
curl_setopt($sc, CURLOPT_RETURNTRANSFER, true);
$output = curl_exec($sc);
curl_close($sc);
$content = json_decode($output, true);
As you can see above the code currently is suppose to display up to 400 users in which someone is following, however when we do the following 2 return all of the content which is being displayed on that link.
echo "<pre>";
print_r($content);
echo "</pre>";
It appears that it caps at only 200 results ( which is really not that good we need 2 find an alternative 2 display the full amount of users someone is following. ) at the bottom of th page it displays another message.
[199] => Array
(
[avatar_url] => http://a1.sndcdn.com/images/default_avatar_large.png?1485508269
[id] => 72067899
[kind] => user
[permalink_url] => http://soundcloud.com/berthalie30
[uri] => https://api.soundcloud.com/users/72067899
[username] => berthalie30
[permalink] => berthalie30
[last_modified] => 2016/04/06 21:53:03 +0000
[first_name] =>
[last_name] =>
[full_name] =>
[city] =>
[description] =>
[country] =>
[track_count] => 0
[public_favorites_count] => 0
[followers_count] => 21
[followings_count] => 89
[plan] => Free
[myspace_name] =>
[discogs_name] =>
[website_title] =>
[website] =>
[reposts_count] => 32
[comments_count] => 0
[online] =>
[likes_count] => 0
[playlist_count] => 6
)
)
[next_href] => https://api.soundcloud.com/users/24537746/followings?client_id=XXXX&page_size=200&cursor=1406526915000
However, even using this method does nothing (even though I'm more then certain the user I am testing with has more then 200 users he's following.)
EDIT : Someone here is having the same issue, how ever I don't understand the comment solution on how 2 prevent it from happening..
I am getting this json output from yahoo boss api. It goes on for 50 results, but, I have pasted only the first two...
(
[bossresponse] => stdClass Object
(
[responsecode] => 200
[web] => stdClass Object
(
[start] => 0
[count] => 50
[totalresults] => 2750000
[results] => Array
(
[0] => stdClass Object
(
[date] =>
[clickurl] => http://www.apple.com/ipad/
[url] => http://www.apple.com/ipad/
[dispurl] => www.apple.com/<b>ipad</b>
[title] => Apple - <b>iPad</b>
[abstract] => <b>iPad</b> is a magical window where nothing comes between you and what you love. And it comes in two sizes.
)
[1] => stdClass Object
(
[date] =>
[clickurl] => http://en.wikipedia.org/wiki/IPad
[url] => http://en.wikipedia.org/wiki/IPad
[dispurl] => en.wikipedia.org/wiki/<b>IPad</b>
[title] => <b>iPad</b> - Wikipedia, the free encyclopedia
[abstract] => The <b>iPad</b> is a line of tablet computers designed and marketed by Apple Inc., which runs Apple's iOS operating system. The first <b>iPad</b> was released on April 3, 2010; the ...
)
[2] => stdClass Object
(
[date] =>
[clickurl] => http://www.amazon.com/s?ie=UTF8&page=1&rh=i%3Aaps%2Ck%3Aipad
[url] => http://www.amazon.com/s?ie=UTF8&page=1&rh=i%3Aaps%2Ck%3Aipad
[dispurl] => www.amazon.com/s?ie=UTF8&page=1&rh=i%3Aaps%2Ck%3A<b>ipad</b>
[title] => Amazon.com: <b>ipad</b>
[abstract] => Considering an <b>iPad</b>? Compare it to Kindle Fire HD Check out our easy side-by-side comparison chart to see how the newest <b>iPad</b> stacks up to Kindle Fire HD 8.9".
)
I use the following code in php to connect to the api and display the results...
**//connect to yahoo api and get results in json**
<?php
require("OAuth.php");
$cc_key = "**confidential**";
$cc_secret = "**confidential**";
$url = "http://yboss.yahooapis.com/ysearch/web";
$args = array();
$args["q"] = "yahoo";
$args["format"] = "json";
$consumer = new OAuthConsumer($cc_key, $cc_secret);
$request = OAuthRequest::from_consumer_and_token($consumer, NULL,"GET", $url, $args);
$request->sign_request(new OAuthSignatureMethod_HMAC_SHA1(), $consumer, NULL);
$url = sprintf("%s?%s", $url, OAuthUtil::build_http_query($args));
$ch = curl_init();
$headers = array($request->to_header());
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$rsp = curl_exec($ch);
$results = json_decode($rsp);
?>
**// Present results in html/php**
<div id="resultsdiv">
<?php
foreach($results->bossresponse->web->results as $result)
{
echo '<h3><a href='.$result->url.'>'.$result->title.'</br>'.$result->abstract.'</a></h3>';
}
?>
My question is how do I paginate results, since all the 50 results appear on the first web page only. I want to display ten results in every page.
Any help is appreciated.
Thanks.
According to the Yahoo! BOSS documentation, specifically the Universal Arguments section, it looks like you can use the start and count parameters to adjust the pagination of results. It looks like the default return count is 50 which matches what you observed.
In your code example you can adjust by adding:
$args["start"] = 0; // increment as needed
$args["count"] = 10;