I have this code that updates my Google MySQL instance authorized IPs, connection is ok, the code prints me the current IP's but it cannot add a new IP to the settings I tried many ways but it still do not works it doesn't make any change to the Instance configuration.
$client = new Google_Client();
$client->setAuthConfig('../config/service-account.json');
$client->setApplicationName(env("APP_NAME"));
$projectName = env("GOOGLE_PROJECT_NAME");
$instanceName = env("SQL_INSTANCE_NAME");
$scopes = [
"https://www.googleapis.com/auth/sqlservice.admin",
"https://www.googleapis.com/auth/compute",
];
$client->addScope($scopes);
$sql = new Google_Service_SQLAdmin($client);
$sqlAdmin = new Google_Service_SQLAdmin_Settings($client);
$instanceSettings = $sql->instances->get($projectName, $instanceName)->getSettings();
$authNetworks = $instanceSettings->getIpConfiguration();
$newAuthNetwork = new Google_Service_SQLAdmin_AclEntry($client);
$newAuthNetwork->setName("tmp_ip_connection");
$newAuthNetwork->setKind("sql#aclEntry");
$authNetworks->setAuthorizedNetworks($newAuthNetwork);
$ipv4 = file_get_contents('https://api.ipify.org');
$newAuthNetwork->setValue($ipv4);
$ipConfiguration = new Google_Service_SQLAdmin_IpConfiguration($client);
$ipConfiguration->setIpv4Enabled(true);
$ipConfiguration->setAuthorizedNetworks([$newAuthNetwork]);
$instanceSettings->setIpConfiguration($ipConfiguration);
$sql->instances->get($projectName, $instanceName)->setSettings($instanceSettings);
//TODO why it is not working??
print_r($sql->instances->get($projectName, $instanceName)->getSettings()->getIpConfiguration()->getAuthorizedNetworks());
The main thing missing from yours is you never updated the instance after you made the change.
Working example:
$client = new Google_Client();
$client->setAuthConfig('../config/service-account.json');
$client->setApplicationName(env("APP_NAME"));
$projectName = env("GOOGLE_PROJECT_NAME");
$instanceName = env("SQL_INSTANCE_NAME");
$scopes = [
"https://www.googleapis.com/auth/sqlservice.admin",
"https://www.googleapis.com/auth/compute",
];
$client->addScope($scopes);
$sql = new Google_Service_SQLAdmin($client);
$instances = $sql->instances;
$instance = $instances->get('projectId', 'instanceId');
$networks = $instance->getSettings()->getIpConfiguration()->getAuthorizedNetworks();
$values = [];
foreach ($networks as $network) {
$values[$network->getName()] = $network;
}
$values['1.production'] = array_get($values, '1.production', clone head($values));
$external_ip = #file_get_contents('http://ipecho.net/plain');
$values['1.production']->setValue("$external_ip/32");
$values['1.production']->setName('1.production');
$instance->getSettings()->getIpConfiguration()->setAuthorizedNetworks(array_values($values));
$instances->update('projectId', 'instanceId', $instance);
Related
I'm using this composer package https://github.com/basvandorst/StravaPHP
The OAUTH is working fine and its generating me the JSON with the access token and user id, etc..
But whenever I try to use other function it returns me 404 not found.
Output is this :
{"token_type":"Bearer","access_token":"077058e0c800881c72a4b10a04a520d5898d4e3e","athlete":{"id":35670467,"username":"amir_do","resource_state":2,"firstname":"Amir","lastname":"Do","city":null,"state":null,"country":null,"sex":"M","premium":false,"summit":false,"created_at":"2018-10-13T13:55:41Z","updated_at":"2018-10-13T13:56:25Z","badge_type_id":0,"profile_medium":"https://lh5.googleusercontent.com/-ku6v9lKNgYY/AAAAAAAAAAI/AAAAAAAAAAA/ABtNlbASj8KhClhwnVYVqRrEG2oiYzWPbA/mo/photo.jpg","profile":"https://lh5.googleusercontent.com/-ku6v9lKNgYY/AAAAAAAAAAI/AAAAAAAAAAA/ABtNlbASj8KhClhwnVYVqRrEG2oiYzWPbA/mo/photo.jpg","friend":null,"follower":null,"email":"goncalomaia97#gmail.com"}}
35670467
Client error: `GET https://www.strava.com/api/athletes/35670467/stats?access_token=077058e0c800881c72a4b10a04a520d5898d4e3e` resulted in a `404 Not Found` response: {"message":"Record Not Found","errors":[{"resource":"resource","field":"path","code":"invalid"}]}
And this is my current callback.php page code:
<?php
include 'vendor/autoload.php';
use Strava\API\Client;
use Strava\API\Exception;
use Strava\API\Service\REST;
session_start();
$client = new GuzzleHttp\Client();
global $connect;
require_once("configs/database.php");
$connect = new mysqli($config['database']['host'],$config['database']['user'],$config['database']['pass'],$config['database']['db']);
$code = $_GET['code'];
$state = $_GET['state'];
$scope = $_GET['scope'];
$user = $_SESSION['username'];
$check = $connect->query("SELECT * FROM users WHERE email = '$user'");
$fetch = $check->fetch_array(MYSQLI_ASSOC);
$apix = $fetch['api'];
$api_secretx = $fetch['api_secret'];
$client = new GuzzleHttp\Client();
$data = [
"client_id" => $apix,
"client_secret" => $api_secretx,
"code" => $code
];
$result = $client->post('https://www.strava.com/oauth/token', ['json' => $data]);
print "<pre>";
print_r( $result->getBody()->getContents() );
print "</pre>";
$bodyb = $result->getBody();
$varx = json_decode((string) $bodyb, true);
$token = $varx['access_token'];
$id = $varx['athlete']['id'];
$_SESSION['token'] = $token;
printf($id);
try {
// REST adapter (We use `Guzzle` in this project)
$adapter = new \GuzzleHttp\Client(['base_uri' => 'https://www.strava.com/api/v3']);
// Service to use (Service\Stub is also available for test purposes)
$service = new \Strava\API\Service\REST($token, $adapter);
// Receive the athlete!
$client = new Client($service);
$athlete = $client->getAthleteStats($id);
print_r($athlete);
} catch(Exception $e) {
print $e->getMessage();
}
$adapter = new \GuzzleHttp\Client(['base_uri' => 'https://www.strava.com/api/v3']);
Change that to this (It should be trailing) :
$adapter = new \GuzzleHttp\Client(['base_uri' => 'https://www.strava.com/api/v3/']);
With the following code using Google's PHP API Client I am receiving this response.
Google_Service_Exception with message 'Error calling POST https://www.googleapis.com/dns/v1/projects/PROJECT-NAME/managedZones/DNSZONE/changes: (400) The 'entity.change' parameter is required but was missing.
Where PROJECT-NAME and DNSZONE are my project and zone.
$client_email = MYCLIENT;
$private_key = file_get_contents('config/credentials/KEY.p12');
$scopes = array('https://www.googleapis.com/auth/ndev.clouddns.readwrite');
$project = "PROJECT-NAME";
$managedZone = "DNSZONE";
$creds = new Google_Auth_AssertionCredentials($client_email,$scopes,$private_key);
$client = new Google_Client();
$client->setAssertionCredentials($creds);
$resource = new Google_Service_Dns_ResourceRecordSet();
$resource->kind = "dns#resourceRecordSet";
$resource->name = "testing.DNSZONE.net.";
$resource->rrdatas[] = "testing.otherhost.com.";
$resource->ttl = 800;
$resource->type = "CNAME";
$dns = new Google_Service_Dns($client);
$change = new Google_Service_Dns_Change();
$change->kind = "dns#change";
$change->setAdditions($resource);
$dns->changes->create($project,$managedZone,$change);
I am a bit confused as to how to set this parameter. Or where I am even am to define it.
Just for clarify what the answer is, setAdditions expects an array.
$change->setAdditions([ $resource ]);
I seem to have bumped into a google calendar api problem. and I can't really see where I have made the error so an extra set of eyes would be greatly appreciated. The problem in short is that the part of the code that should output the events.. doesn't (the "result" part of the code.
require_once "./google-api-php-client/src/Google/Client.php";
require_once "./google-api-php-client/src/Google/Service/Calendar.php";
// Service Account info
$client_id = "XXXXXX-XXXXXXXXXXXXXXXXXXXXX.apps.googleusercontent.com";
$app_name = "Some-name";
$service_account_name = 'XXXXX-XXXXXXXXXXXXXXXXXXXXXXX#developer.gserviceaccount.com';
$key_file_location = 'google-api-php-client/Some-name-xxxxxxxxxx.p12';
$cal_id = "primary";
// Service Account info
$client_id = $client_id;
$service_account_name = $service_account_name;
$key_file_location = $key_file_location;
// Calendar id
$calName = $cal_id;
$client = new Google_Client();
$client -> setApplicationName($app_name);
$service = new Google_Service_Calendar($client);
$key = file_get_contents($key_file_location);
$cred = new Google_Auth_AssertionCredentials(
$service_account_name,
array('https://www.googleapis.com/auth/calendar.readonly'),
$key
);
$client->setAssertionCredentials($cred);
$cals = $service->calendarList->listCalendarList();
print_r($cals);
echo "<br>events<br>";
$events = $service->events->listEvents($calName);
var_dump($events);
echo "<br>result:<br>";
// the following is what returns nothing, works fine until this point.
$i = 0;
foreach ( $events->getItems() as $event ) {
echo 'i:'.$i.' '.$event->getSummary();
$i++;
}
echo 'end';
Change $events to the below line:
$events = $service->events->listEvents('primary', $params);
Instead of primary, add $calName and also send $params in listEvents method.
Hope this works.
When I use "this solution" I get a blank contacts array.
I'm using "google-api-php-client-0.6.7" with a serviceAccount.php into the examples/contacts folder, and a Google_ContactsService into src/contrib folder.
I have configured the Google Apis Access, with OAUTH 2 as Server Account. I have the p12 file, a client id and a cliend mail address. The project name is "Google Contacts Sample".
serviceAccount.php:
<?php
require_once '../../src/Google_Client.php';
require_once '../../src/contrib/Google_ContactsService.php';
const CLIENT_ID = 'xxxxxxxxxxxxx.apps.googleusercontent.com';
const SERVICE_ACCOUNT_NAME = 'xxxxxxxxxxxxx#developer.gserviceaccount.com';
const KEY_FILE = '/absolute_path/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa-privatekey.p12';
$client = new Google_Client();
$client->setApplicationName("Google Contacts Sample");
session_start();
if (isset($_SESSION['token'])) {
$client->setAccessToken($_SESSION['token']);
}
$key = file_get_contents(KEY_FILE);
$client->setAssertionCredentials(new Google_AssertionCredentials(SERVICE_ACCOUNT_NAME, array('https://www.googleapis.com/auth/contacts'), $key));
$client->setClientId(CLIENT_ID);
if ($client->getAuth()->isAccessTokenExpired()) {
$client->getAuth()->refreshTokenWithAssertion();
}
$token = $client->getAccessToken();
$service = new Google_ContactsService($client);
$result = $service->all();
print '<h2>Contacts Result:</h2><pre>' . print_r($result, true) . '</pre>';
Google_ContactsService.php:
<?php
class Google_ContactsService
{
const SCOPE = "https://www.google.com/m8/feeds";
/**
* #var Google_Client
*/
private $client;
public function __construct($pClient)
{
$this->client = $pClient;
$this->client->setScopes(self::SCOPE);
}
public function all()
{
$result = $this->execute('default/full?max-results=999');
$contacts = array();
foreach($result["feed"]["entry"] as $entry)
{
if(!isset($entry['gd$email']))
$entry['gd$email'] = array();
if(!isset($entry['gd$phoneNumber'])||empty($entry['gd$phoneNumber']))
continue;
$phones = array();
$emails = array();
foreach($entry['gd$phoneNumber'] as $phone)
{
$phone['$t'] = preg_replace('/\+33/', "0", $phone['$t']);
$phone['$t'] = preg_replace('/\-/', '', $phone['$t']);
$phones[] = $phone['$t'];
}
foreach($entry['gd$email'] as $email)
{
$emails[] = $email['address'];
}
$contacts[] = array(
"fullName"=>utf8_decode($entry['title']['$t']),
"phones"=>$phones,
"emails"=>$emails
);
}
return $contacts;
}
private function execute($pUrl)
{
$oauth = Google_Client::$auth;
$request = new Google_HttpRequest("https://www.google.com/m8/feeds/contacts/".$pUrl."&alt=json");
$oauth->sign($request);
$io = Google_Client::$io;
$result_json = $io->makeRequest($request)->getResponseBody();
$result = json_decode($result_json, true);
return $result;
}
}
When I go to "http://server.com/packs/googleapi/examples/contacts/serviceAccount.php" I don't see any contact.
The function Execute return empty.
What can I do?
Thanks.
I realize this is old so you have probably moved on but for other's finding this I believe the reason you don't see any contacts is that you are not delegating to a specific user. Not counting shared contacts on Google Apps Premier and Education Editions domains, contacts are private to that user.
I would change this line
$client->setAssertionCredentials(new Google_AssertionCredentials(SERVICE_ACCOUNT_NAME, array('https://www.googleapis.com/auth/contacts'), $key));
to be more like this
$auth = new Google_AssertionCredentials(SERVICE_ACCOUNT_NAME, array('https://www.google.com/m8/feeds'), $key);
$auth->sub = 'user#domain.com'; //whoever's contacts you want to see
$client->setAssertionCredentials($auth);
You could keep the first two lines together if you look at Google_AssertionCredentials method signature, but I think this makes it more explicit. Depending on what you are trying to achieve, user#domain.com will likely be a variable that is set from some kind of input, database, etc.
i am trying to send a bunch of events via an Batch Request to Google Calendar.
But i cant figur out how to do. https://developers.google.com/google-apps/calendar/batch doesnt help me.
require_once 'google-api-php-client/src/Google_Client.php';
require_once 'google-api-php-client/src/contrib/Google_CalendarService.php';
$client = new Google_Client();
$client->setUseBatch(true);
$batch = new Google_BatchRequest();
$uri = 'http://www.google.com/calendar/feeds/default/private/full/batch';
$batchContent = file_get_contents('xxxxx/google-api-php-client/batch.xml');
$batch->add($batchContent);
batch.xml contains 2 -items.
Thats all so far. But nothing happened.
I also have tried
$batch->execute()
But thats throws error without message.
My question: How to send a Batch via PHP to Google Calendar ?
I'm using the latest version of Google APIs Client Library for PHP (Google Calendar v.3). I use batch operations for pushing instructor lessons to Google Calendar. Here is my example of code for you (multipleInsert function). Good luck!
<?php
require_once(APPPATH . 'libraries/Google/Client.php');
require_once(APPPATH . 'libraries/Google/Http/Batch.php');
require_once(APPPATH . 'libraries/Google/Service/Calendar.php');
class My_google_calendar
{
...
/** Add single Event for Student */
function addEvent($lesson, $instructor, $return_request = false, $enable_attendees = false)
{
$calendar = $this->getGoogleCalendar(); // get calendar service variable
$lesson_from = date(DATE_RFC3339, $lesson->from);
$lesson_to = date(DATE_RFC3339, $lesson->from + $lesson->duration);
$event = new Google_Service_Calendar_Event();
$event->setSummary('Lesson with student: '$lesson->student_full_name);
$start = new Google_Service_Calendar_EventDateTime();
$start->setDateTime($lesson_from);
$start->setTimeZone($this->getGoogleCalendarTimeZone());
$event->setStart($start);
$end = new Google_Service_Calendar_EventDateTime();
$end->setDateTime($lesson_to);
$end->setTimeZone($this->getGoogleCalendarTimeZone());
$event->setEnd($end);
$event->setColorId(4);
$description = "...";
$event->setDescription($description);
if (isset($student->email) && $enable_attendees) {
$attendee1 = new Google_Service_Calendar_EventAttendee();
$attendee1->setResponseStatus('needsAction');
$attendee1->setEmail($student->email);
$attendees = array($attendee1);
$event->setAttendees($attendees);
}
$createdEvent = $this->calendar->events->insert($this->calendar_id, $event, array('fields' => 'id'));
return $return_request ? $createdEvent : $createdEvent->getId();
}
/** Push group of events to the Calendar */
function multipleInsert ($lessons, $instructor)
{
$this->use_batch = true;
$this->client->setUseBatch($this->use_batch);
$batch = new Google_Http_Batch($this->client);
$optParams = array('fields' => 'status,updates');
foreach($lessons as $time => $lesson) {
$lesson = array_shift($group['lessons']);
$req = $this->addEvent($lesson, $instructor, true);
$batch->add($req, $time);
}
}
$results = $batch->execute();
return $results;
}
}
in the newer versions, you should use
$batch = $service->createBatch();
instead of
$batch = new Google_Http_Batch($this->client);
reference