I'm a beginner in PHP, so maybe someone could help to fix this ?
My web application is showing Google PageInsights API error..
Here's the code, I tried to change version to /v2/, but it still didn't work..
public function getPageSpeed($domain, $api = "")
{
try
{
$callback_url = "https://www.googleapis.com/pagespeedonline/v1/runPagespeed?";
$data = array(
'url' => 'http://' . $domain,
'key' => (empty($api) ? $_SESSION['GOOGLEAPI_SERVERKEY'] : $api),
'fields' => 'score,pageStats(htmlResponseBytes,textResponseBytes,cssResponseBytes,imageResponseBytes,javascriptResponseBytes,flashResponseBytes,otherResponseBytes)'
);
$curl_response = $this->curl->get($callback_url . http_build_query($data, '', '&'));
if ($curl_response->headers['Status-Code'] == "200") {
$content = json_decode($curl_response, true);
$response = array(
'status' => 'success',
'data' => array(
'pagespeed_score' => (int)$content['score'],
'pagespeed_stats' => $content['pageStats']
)
);
} else {
$response = array(
'status' => 'error',
'msg' => 'Google API Error. HTTP Code: ' . $curl_response->headers['Status-Code']
);
}
}
catch (Exception $e)
{
$response = array(
'status' => 'error',
'msg' => $e->getMessage()
);
}
return $response;
}
<?php
function checkPageSpeed($url){
if (function_exists('file_get_contents')) {
$result = #file_get_contents($url);
}
if ($result == '') {
$ch = curl_init();
$timeout = 60;
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
$result = curl_exec($ch);
curl_close($ch);
}
return $result;
}
$myKEY = "your_key";
$url = "http://kingsquote.com";
$url_req = 'https://www.googleapis.com/pagespeedonline/v1/runPagespeed?url='.$url.'&screenshot=true&key='.$myKEY;
$results = checkPageSpeed($url_req);
echo '<pre>';
print_r(json_decode($results,true));
echo '</pre>';
?>
The code shared by Siren Brown is absolutely correct, except that
while getting the scores we need to send the query parameter &strategy=mobile or &strategy=desktop to get the respective results from Page speed API
$url_mobile = 'https://www.googleapis.com/pagespeedonline/v1/runPagespeed?url='.$url.'&screenshot=true&key='.$myKEY.'&strategy=mobile';
$url_desktop = 'https://www.googleapis.com/pagespeedonline/v1/runPagespeed?url='.$url.'&screenshot=true&key='.$myKEY.'&strategy=desktop';
Related
I'm trying to add an array of players_id to send to push notification to specific mobiles, but I keep getting the error "Incorrect player_id format in include_player_ids (not a valid UUID)"
if ($cons) {
$dado1 = array();
$dado2 = array();
while ($row = sqlsrv_fetch_array($cons, SQLSRV_FETCH_ASSOC)) {
$dado1 = array(
$row['funcionarioId']
);
array_push($dado2, $dado1);
}
//echo json_encode($dado2);
} else {
$dado2 = array();
array_push($dado2, $dado1);
$retornoVazio = array("Retorno" => $dado2);
EnviaEmailComErro($sql, sqlsrv_errors(), "Consulta_NFCe - ConsultaDados");
array_push($dado2, array("Success" => "0", "Error" => "1"));
echo json_encode($retornoVazio);
}
function sendMessage($produto, $mesa, $comanda, $garcom, $dado2)
{
$content = array(
"en" => " Garçom $garcom \n o pedido: $produto está pronto!\n mesa: $mesa \n comanda: $comanda",
);
**That where it should add the IDS**
$fields = array(
'app_id' => "***",
'include_player_ids' => array($dado2),
'channel_for_external_user_ids' => 'push',
'data' => array("foo" => "bar"),
'contents' => $content
);
$fields = json_encode($fields);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://onesignal.com/api/v1/notifications");
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json; charset=utf-8',
'Authorization: Basic ***'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, FALSE);
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
$response = curl_exec($ch);
curl_close($ch);
return $response;
}
$response = sendMessage($produto, $mesa, $comanda, $garcom, $dado2);
$return["allresponses"] = $response;
$return = json_encode($return);
the variable $fields print
{"app_id":"***",
"include_player_ids":[
[
["2610ec53-"],
["045eac07-"],
["8fb19bd9-"]
]
]"
And $response:
{"errors":["Incorrect player_id format in include_player_ids (not a valid UUID): [[\"2610ec53-\"], [\"045eac07-\"], [\"8fb19bd9-\"]]"]}
"The players ID are complete in the code, but I deleted it."
In the if ($cons) { you are pushing all sorts of stuff into arrays, simplify it to
if ($cons) {
$dado2 = array();
while ($row = sqlsrv_fetch_array($cons, SQLSRV_FETCH_ASSOC)) {
$dado2[] = $row['funcionarioId'];
}
} else {
And in the function make this change
'include_player_ids' => $dado2,
I´m trying to create an event and that part works, but it will not for some reason send out the invitations / attendees in the calendar system with google API using PHP. It does create the event but that also it. So I hope someone can help me figuring out what I´m doing wrong.
myfile.php
// Event details
parameters = { title: $("#event-title").val(),
event_time: {
start_time: $("#event-type").val() == 'FIXED-TIME' ? $("#event-start-time").val().replace(' ', 'T') + ':00' : null,
end_time: $("#event-type").val() == 'FIXED-TIME' ? $("#event-end-time").val().replace(' ', 'T') + ':00' : null,
event_date: $("#event-type").val() == 'ALL-DAY' ? $("#event-date").val() : null
},
'attendees': [
{'email': 'test#dds-slagelse.dk'},
],
all_day: $("#event-type").val() == 'ALL-DAY' ? 1 : 0,
};
$("#create-event").attr('disabled', 'disabled');
$.ajax({
type: 'POST',
url: 'ajax.php',
data: { event_details: parameters },
dataType: 'json',
success: function(response) {
$("#create-event").removeAttr('disabled');
alert('Event created with ID : ' + response.event_id);
},
error: function(response) {
$("#create-event").removeAttr('disabled');
alert(response.responseJSON.message);
}
});
ajax.php file
session_start();
header('Content-type: application/json');
require_once('google-calendar-api.php');
error_log($_SESSION['access_token']);
try {
// Get event details
$event = $_POST['event_details'];
error_log(__LINE__);
$capi = new GoogleCalendarApi();
error_log(__LINE__);
// Get user calendar timezone
$user_timezone = $capi->GetUserCalendarTimezone($_SESSION['access_token']);
error_log(__LINE__);
// Create event on primary calendar
error_log($event['attendees0']);
$event_id = $capi->CreateCalendarEvent('primary', $event['title'], $event['all_day'], $event['event_time'], $event['attendees'], $user_timezone, $_SESSION['access_token']);
error_log(__LINE__);
echo json_encode([ 'event_id' => $event_id ]);
}
catch(Exception $e) {
error_log($e->getMessage());
header('Bad Request', true, 400);
echo json_encode(array( 'error' => 1, 'message' => $e->getMessage() ));
}
google-calendar.api.php
class GoogleCalendarApi
{
public function GetAccessToken($client_id, $redirect_uri, $client_secret, $code) {
$url = 'https://accounts.google.com/o/oauth2/token';
$curlPost = 'client_id=' . $client_id . '&redirect_uri=' . $redirect_uri . '&client_secret=' . $client_secret . '&code='. $code . '&grant_type=authorization_code';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_POSTFIELDS, $curlPost);
$data = json_decode(curl_exec($ch), true);
$http_code = curl_getinfo($ch,CURLINFO_HTTP_CODE);
if($http_code != 200)
throw new Exception('Error : Failed to receieve access token');
return $data;
}
public function GetUserCalendarTimezone($access_token) {
$url_settings = 'https://www.googleapis.com/calendar/v3/users/me/settings/timezone';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url_settings);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Authorization: Bearer '. $access_token));
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
$data = json_decode(curl_exec($ch), true); //echo '<pre>';print_r($data);echo '</pre>';
$http_code = curl_getinfo($ch,CURLINFO_HTTP_CODE);
if($http_code != 200)
throw new Exception($http_code);
return $data['value'];
}
public function GetCalendarsList($access_token) {
$url_parameters = array();
$url_parameters['fields'] = 'items(id,summary,timeZone)';
$url_parameters['minAccessRole'] = 'owner';
$url_calendars = 'https://www.googleapis.com/calendar/v3/users/me/calendarList?'. http_build_query($url_parameters);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url_calendars);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Authorization: Bearer '. $access_token));
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
$data = json_decode(curl_exec($ch), true); //echo '<pre>';print_r($data);echo '</pre>';
$http_code = curl_getinfo($ch,CURLINFO_HTTP_CODE);
if($http_code != 200)
throw new Exception('Error : Failed to get calendars list');
return $data['items'];
}
//'primary', $event['title'], $event['all_day'], $event['event_time'], $event['attendees'], $user_timezone, $_SESSION['access_token']
public function CreateCalendarEvent($calendar_id, $summary, $all_day, $event_time, $event_attendees, $event_timezone, $access_token) {
$url_events = 'https://www.googleapis.com/calendar/v3/calendars/' . $calendar_id . '/events';
$curlPost = array('summary' => $summary);
if($all_day == 1) {
$curlPost['start'] = array('date' => $event_time['event_date']);
$curlPost['end'] = array('date' => $event_time['event_date']);
}
else {
$curlPost['start'] = array('dateTime' => $event_time['start_time'], 'timeZone' => $event_timezone);
$curlPost['end'] = array('dateTime' => $event_time['end_time'], 'timeZone' => $event_timezone);
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url_events);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Authorization: Bearer '. $access_token, 'Content-Type: application/json'));
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($curlPost));
$data = json_decode(curl_exec($ch), true);
$http_code = curl_getinfo($ch,CURLINFO_HTTP_CODE);
if($http_code != 200)
throw new Exception($http_code);
return $data['id'];
}
}
I hope this make sense as I have tried so many attempts that I have lost track of it.
The Form Data that is send (after what i can figure out from google chrome is the following:
event_details[title]: Privat
event_details[event_time][start_time]: 2018-08-11T13:00:00
event_details[event_time][end_time]: 2018-08-11T15:30:00
event_details[event_time][event_date]:
event_details[attendees][0][email]: test#dds-slagelse.dk
event_details[all_day]: 0
ADyson, thanks for your help / hint. It was the missing curl that was the solution.
$curlPost['attendees'] = $event_attendees;
I hope it wont be to much of a bother, but it seems that it does not send out the invites for the events as hoped, even thought it does add the "guests" to the event.
The starting point for this solution is found here: http://usefulangle.com/post/29/google-calendar-api-create-event-php and if someone can please helt me to get * "sendNotifications"=>true * inserted or set correctly I would be very thankful. (would like to see how that parameter / function is set).
Best Regards
Jess
This help to me:
$curlPost['attendees'] = [['email'=>$event_data['attendees']]];
$curlPost['sendUpdates'] = array("sendUpdates"=>"all");
$curlPost['reminders'] = array('useDefault' => true, 'overrides' => array('method' => 'email','minutes' => 20));
I have a problem with sendAudio() function in php telegram bot.
if (strtoupper($text) == "MUSIC") {
$voice = curl_file_create('audio.ogg');
$content = array('chat_id' => $chat_id, 'audio' => $voice);
$telegram->sendAudio($content);
}
This don't work with an audio lenghtof 9 or more seconds. I also tried with .mp3 but nothing. Same function with an audio lenght of 6 or less seconds works. I looked in the documentation and it says only 50MB files are restricted. Help pls.
Here's my $telegram.
include("Telegram.php");
$bot_id = "xxxxxxx:yyyyyyyy_mytoken";
$telegram = new Telegram($bot_id);
And here Telegram.php:
class Telegram {
private $bot_id = "mytoken";
private $data = array();
private $updates = array();
public function __construct($bot_id) {
$this->bot_id = $bot_id;
$this->data = $this->getData();
}
public function endpoint($api, array $content, $post = true) {
$url = 'https://api.telegram.org/bot' . $this->bot_id . '/' . $api;
if ($post)
$reply = $this->sendAPIRequest($url, $content);
else
$reply = $this->sendAPIRequest($url, array(), false);
return json_decode($reply, true);
}
public function sendAudio(array $content) {
return $this->endpoint("sendAudio", $content);
}
I am using this code to send mp3 audio file to telegram from my php application and It's working fine for me.
$BOT_TOKEN = 'yourBotToken';
$chat_id = '#yourChannel';
$filePath = 'your/path/file';
define('BOTAPI', 'https://api.telegram.org/bot' . $BOT_TOKEN . '/');
$cfile = new CURLFile(realpath($filePath));
$data = [
'chat_id' => $chat_id,
'audio' => $cfile,
'caption' => $message
];
$ch = curl_init(BOTAPI . 'sendAudio');
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
curl_exec($ch);
curl_close($ch);
Have you tried to use sendVoice for ogg file instead of sendAudio?
Next code did work for me well:
<?php
exec( "curl -i -F 'chat_id=1234567890' -F 'voice=#audio.ogg' 'https://api.telegram.org/bot1234567890:AABBCCDDEEFFGGHH/sendVoice' 2>&1", $output , $return );
print_r( json_decode( end( $output ) ) );
you can use this code to send your audio file
function sendmessage($url, $post_params) {
$cu = curl_init();
curl_setopt($cu, CURLOPT_URL, $url);
curl_setopt($cu, CURLOPT_POSTFIELDS, $post_params);
curl_setopt($cu, CURLOPT_RETURNTRANSFER, true); //get result
$result = curl_exec($cu);
curl_close($cu);
return $result;
}
$telsite = "https://api.telegram.org/bot"."$your_token_id";
$sendAudio_url = $telsite."sendAudio";
$post_parameters = array('chat_id' => $chat_user_id , 'audio' => $dir_of_audio);
sendmessage($sendAudio_url , $post_parameters);
Example using westacks/telebot library:
<?php
use WeStacks\TeleBot\TeleBot;
require 'vendor/autoload.php';
$bot = new TeleBot('123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11');
$bot->sendAudio([
'chat_id' => 1111111111,
'audio' => 'https://file-examples-com.github.io/uploads/2017/11/file_example_MP3_700KB.mp3'
]);
$bot->sendAudio([
'chat_id' => 1111111111,
'audio' => './path/to/local/file.mp3'
]);
I'm trying to create a variable and place it in an array. Like this:
$ch = curl_init('https://apps.net-results.com/api/v2/rpc/server.php?Controller=Contact');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERPWD, 'user:pass');
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS,
json_encode(
array(
'id' => uniqid(),
'method' => 'getMultiple',
'jsonrpc' => '2.0',
'params' => array(
'offset' => 0,
'limit' => 50, // 10, 25, or 50
'order_by' => 'contact_email_address', //'contact_email_address' or 'contact_id'
'order_dir' => 'ASC', //'ASC' or 'DESC'
)
)
)
);
$strResponse = curl_exec($ch);
$strCurlError = curl_error($ch);
if (!empty($strCurlError)) {
//handle curl error
echo "Curl Error<br />$strCurlError<br />";
} else {
//check for bad user/pass
if ($strResponse == "HTTP/1.0 401 Unauthorized: Your username name and/or password are invalid.") {
//handle login error
echo "Error<br />$strResponse<br />";
} else {
//successful call, check for api success or error
$objResponse = json_decode($strResponse);
if (property_exists($objResponse, 'error') && !is_null($objResponse->error)) {
//handle error
$intErrorCode = $objResponse->error->code;
$strMessage = $objResponse->error->message;
$strData = $objResponse->error->data;
echo "Error<br />Code: $intErrorCode<br />Message: $strMessage<br />Data: $strData<br />";
} else {
//handle success
//echo "Success<br />";
$objResult = $objResponse->result;
$intTotalRecords = $objResult->totalRecords;
//echo "Total Records: $intTotalRecords<br />";
$arrContacts = $objResult->results;
//echo $arrContacts[0]->country;
//echo $arrContacts[3]->last_name;
//echo "<pre>";
//print_r($arrContacts);
//echo "<pre/>";
}
}
}
I'm not sure this is possible. I have tried doing different things such as creating a class, and placing the function in the class in the array, but it doesn't work. Can anyone give me the correct syntax of what I should try?
If you pass params via post you should use http_build_query() and you can pass it as CURL post fields.
You should set:
$array = [
'id' => uniqid(),
'method' => 'getContactActivity',
'jsonrpc' => '2.0'
];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,"http://example.site");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($array));
curl_exec($ch);
curl_close($ch);
Leave out the call to json_encode(). The value of the CURLOPT_POSTFIELDS option should be either an associative array or a string in URL-encoded format. If you use an array, it will automatically encode it for you.
I have this url DespegarAPI and as you can see the content is OK. Is a JSON response.
I need that content through my own file and I use curl o file_content but the response I this my file
I have this in my file
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://api.despegar.com/cities?pagesize=30");
curl_setopt($ch, CURLOPT_HEADER, 0);
$response = curl_exec($ch);
curl_close($ch);
echo $response;
Thanks for the response!
It's because the content is gzipped, here's a quick example to get you going.
<?php
function despegar($endpoint, array $params = array()) {
$url = sprintf(
'http://api.despegar.com/%s?%s',
$endpoint,
empty($params) ? null : http_build_query($params)
);
$handle = curl_init($url);
curl_setopt_array($handle, array(
CURLOPT_ENCODING => 'gzip',
CURLOPT_RETURNTRANSFER => true
));
$response = curl_exec($handle);
$code = curl_getinfo($handle, CURLINFO_HTTP_CODE);
if ( ! $response || 200 != $code) {
throw new Exception(
sprintf('(%d) Failed to obtain data from %s.', $code, $url),
$code
);
}
return json_decode($response);
}
try {
$cities = despegar('cities', array('pagesize' => 10));
foreach ($cities->cities as $city) {
printf("%s\n", $city->countryId);
}
}catch(Exception $exception) {
echo $exception->getMessage();
}