I have to work on google Calendar Insert API Without Login ...When I run this function that time did not event create On my account but it's function return "SUCCESS"
Also it Authentication is good. If you know please find a solution for that Question..thanks
XAMPP Localhost
require_once ('C:/xampp/htdocs/java_google/google-api-
php/src/Google/autoload.php');
$client_id = 'XXXXX'; //Client ID
$service_account_name = 'XXXXXX'; //Email Address
$key_file_location = 'C:/xampp/htdocs/java_google/java-new-257718-
70d76ac18661.p12'; //key.p12
$client = new Google_Client(); //AUTHORIZE OBJECTS
$client->setApplicationName("Java New");
//INSTATIATE NEEDED OBJECTS (In this case, for freeBusy query, and Create
New Event)
$service = new Google_Service_Calendar($client);
$id = new Google_Service_Calendar_FreeBusyRequestItem($client);
$item = new Google_Service_Calendar_FreeBusyRequest($client);
$event = new Google_Service_Calendar_Event($client);
$startT = new Google_Service_Calendar_EventDateTime($client);
$endT = new Google_Service_Calendar_EventDateTime($client);
if (isset($_SESSION['service_token'])) {
$client->setAccessToken($_SESSION['service_token']);
}
$key = file_get_contents($key_file_location);
$cred = new Google_Auth_AssertionCredentials(
$service_account_name,
array('https://www.googleapis.com/auth/calendar'),
$key
);
$client->setAssertionCredentials($cred);
if ($client->getAuth()->isAccessTokenExpired()) {
$client->getAuth()->refreshTokenWithAssertion($cred);
}
$_SESSION['service_token'] = $client->getAccessToken();
global $service;
global $event;
global $startT;
global $endT;
$calendarId = 'primary';
$summary = 'primary test test';
$location = 'chennai';
$description = 'chennai123';
$date = '2019-11-04T13:22:07+01:00';
$start = '2019-11-04T13:22:07+01:00';
$end = '2019-11-04T13:22:08+01:00';
$startT->setTimeZone("Europe/Rome");
$startT->setDateTime($date);
$endT->setTimeZone("Europe/Rome");
$endT->setDateTime($end);
$event->setSummary($summary);
$event->setLocation($location);
$event->setDescription($description);
$event->setStart($startT);
$event->setEnd($startT);
$insert = $service->events->insert($calendarId, $event);
if($insert) {
echo 'sucess';
return true;
}
Please Add Below Line On your Code
$scope = new Google_Service_Calendar_AclRuleScope($client);
$rule = new Google_Service_Calendar_AclRule($client);
$scope->setType('user');
$scope->setValue( 'your Email' );
$rule->setRole( 'owner' );
$rule->setScope( $scope );
$result = $service->acl->insert('primary', $rule);
Related
I need to search all sales orders for a specific customer ( using customer internal id or entity id ). When I run below script, it returns all sales orders ( 20 for a page). How to filter that result by customer?
require_once 'PHPToolkit/NetSuiteService.php';
$service = new NetSuiteService();
$service->setSearchPreferences(false, 20);
$SearchEnumMultiSelectField = new SearchEnumMultiSelectField();
$SearchEnumMultiSelectField->searchValue = Array('_salesOrder');
$SearchEnumMultiSelectField->operator = 'anyOf';
$search = new TransactionSearchBasic();
$search->type = $SearchEnumMultiSelectField;
//$search->customForm = new SearchMultiSelectField();
//$id = new RecordRef();
//$id->internalId = 'xxxxxx'; customer internal Id
//$search->customForm->searchValue = $id;
$request = new SearchRequest();
$request->searchRecord = $search;
$searchResponse = $service->search($request);
echo print_r($searchResponse,true);
$service = new NetSuiteService(self::_config);
$customerSearchBasic = new CustomerSearchBasic();
$searchValue = new RecordRef();
$searchValue->type = 'customer';
$searchValue->internalId = $customer_id;
$searchMultiSelectField = new SearchMultiSelectField();
setFields($searchMultiSelectField, array('operator' => 'anyOf', 'searchValue' => $searchValue));
$customerSearchBasic->internalId = $searchMultiSelectField;
$transactionSearchBasic = new TransactionSearchBasic();
$searchMultiSelectEnumField = new SearchEnumMultiSelectField();
setFields($searchMultiSelectEnumField, array('operator' => 'anyOf', 'searchValue' => "_salesOrder"));
$transactionSearchBasic->type = $searchMultiSelectEnumField;
$transactionSearch = new TransactionSearch();
$transactionSearch->basic = $transactionSearchBasic;
$transactionSearch->customerJoin = $customerSearchBasic;
$request = new SearchRequest();
$request->searchRecord = $transactionSearch;
$searchResponse = $service->search($request);
if ($searchResponse->searchResult->status->isSuccess) {
if(isset($searchResponse->searchResult->recordList)) {
return $searchResponse->searchResult->recordList->record;
}
}
Please help me to sort out this problem
I am getting this error.
[faultstring] => System.NullPointerException: Attempt to de-reference a null object
I am using custom object integration for Sales force.
require_once ('soapclient/SforcePartnerClient.php');
require_once ('soapclient/SforceHeaderOptions.php');
try {
$mySforceConnection = new SforcePartnerClient();
$mySforceConnection->createConnection("soapclient/partnerwsdl-sb.xml");
$mySforceConnection->login(USERNAME, PASSWORD.SECURITY_TOKEN);
// Define constants for the web service. We'll use these later
$parsedURL = parse_url($mySforceConnection->getLocation());
define ("_SFDC_SERVER_", substr($parsedURL['host'],0,strpos($parsedURL['host'], '.')));
define ("_WS_NAME_", 'WebToLeadServices');
define ("_WS_WSDL_", 'soapclient/WebToLeadServices-SB-V1.1.xml');
define ("_WS_ENDPOINT_", 'https://' . _SFDC_SERVER_ . '.salesforce.com/services/wsdl/class/' . _WS_NAME_);
define ("_WS_NAMESPACE_", 'http://soap.sforce.com/schemas/class/' . _WS_NAME_);
// SOAP Client for Web Service
$client = new SoapClient(_WS_WSDL_);
$sforce_header = new SoapHeader(_WS_NAMESPACE_, "SessionHeader", array("sessionId" => $mySforceConnection->getSessionId()));
$client->__setSoapHeaders(array($sforce_header));
$sObject = new stdclass();
$sObject->fullName = 'Sunil';
$sObject->country = 'India';
$sObject->budget = '1';
$sObject->type = 'Contact';
$sObject->dialingCode = '91';
$sObject->emailAddress = "XXXX";
$sObject->mobileNumber = "XXXXXXXX";
$sObject->source = "google";
$sObject->projectInterested = "Project";
$sObject->capturePoint = "XXXX.php";
$sObject->IPAddress = "XXXX";
$sObject->webbannerSource = "google";
$sObject->webbannerSize = "twitter";
$createResponse = $client->createLeadFromWeb(array($sObject));
} catch (Exception $e) {
echo '<pre>';
print_r($e);
echo '</pre>';
}
?>
</pre>
I have got the solution for it
We need to pass the variable like this with required field.
and its working
$lead = new StdClass();
$lead->fullName = 'sunil';
$lead->mobileNumber = "1234567896";
$lead->emailAddress = "sunil#example.in";
$lead->source = "DIGITAL MARKETING";
$leadData = array('wl'=>$lead);
$response = $client->createLeadfromWeb($leadData);
So, I was wondering if the following code could actually be ported to laravel?
<?php
require_once 'data.php';
require_once 'lib/google-api-php-client-master/src/Google/autoload.php';
session_start();
$client_id = 'CLIENT_ID_HERE';
$client_secret = 'CLIENT_SECRET_HERE';
$redirect_uri = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
$simple_api_key = 'API_KEY_HERE';
$client = new Google_Client();
$client->setApplicationName("APPLICATION_NAME");
$client->setClientId($client_id);
$client->setClientSecret($client_secret);
$client->setRedirectUri($redirect_uri);
$client->addScope("https://www.googleapis.com/auth/analytics.readonly");
$client->setApprovalPrompt('force');
$client->setAccessType('offline');
if(isset($_SESSION['ga_token_time']) && (time() - $_SESSION['ga_token_time'] > 60)){
unset($_SESSION['ga_token']);
unset($_SESSION['ga_token_time']);
}
$result = mysqli_query($con,'SELECT token FROM user WHERE user_id='.$_SESSION['user_id']);
$row = $result->fetch_assoc();
if($row['token'] != '') {
$client->refreshToken($row['token']);
$_SESSION['ga_token'] = $client->getAccessToken();
$_SESSION['ga_token_time'] = time();
} elseif (isset($_GET['code'])) {
$client->authenticate($_GET['code']);
$_SESSION['ga_token'] = $client->getAccessToken();
$_SESSION['ga_token_time'] = time();
$redirect = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
header('Location: ' . filter_var($redirect, FILTER_SANITIZE_URL));
}
if (isset($_SESSION['ga_token']) && trim($_SESSION['ga_token']) !== '') {
$client->setAccessToken($_SESSION['ga_token']);
$token = json_decode($_SESSION['ga_token']);
if(isset($token->refresh_token)) {
mysqli_query($con,'UPDATE user SET token="'.mysqli_real_escape_string($con, $token->refresh_token).'" WHERE user_id='.$_SESSION['user_id']);
}
}
if ($client->getAccessToken()) {
$analytics = new Google_Service_Analytics($client);
$accounts = $analytics->management_accounts->listManagementAccounts();
$properties = $analytics->management_webproperties->listManagementWebproperties('~all');
$items = $properties->getItems();
$list = array();
$i = 0;
foreach ($items as $item) {
$list[$i]['name'] = $item->getName();
$list[$i]['nameurl'] = urlencode($name);
$list[$i]['id'] = $item->getAccountId();
$list[$i]['wpid'] = $item->getId();
$list[$i]['linkurl'] = urlencode($item->getChildLink()->getHref());
$i++;
}
} else {
$authUrl = $client->createAuthUrl();
header('Location: '.$authUrl);
}
I already have started with this one
ConnectionsController.php
<?php
use App\helpers\Common;
class ConnectionsController extends BaseController{
public function getExistingLogins($id){
$ga_user = DB::table('user')->select('*')->where('user_id', $id)->get();
$client_id = $ga_user[0]->client_id;
$client_secret = $ga_user[0]->client_secret;
$token = $ga_user[0]->token;
$api_key = 'API_KEY_HERE';
$application_name = 'APPLICATION_NAME';
$return = new App\Services\GoogleAnalytics($client_id, $client_secret, $application_name, $api_key, $token);
return $return->get();
}
return false;
}
App\Services\GoogleAnalytics.php
<?php
namespace App\Services;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Session;
class GoogleAnalytics {
protected $client;
protected $service;
protected $url;
function __construct($client_id, $client_secret, $application_name, $api_key, $token) {
$host = $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
$http = (isset($_SERVER['HTTP_SCHEMETYPE']) && $_SERVER['HTTP_SCHEMETYPE'] == 'https') ? 'https:' : 'http:';
$this->url = $http . '//' . $host;
/* Set config variables */
$this->client = new \Google_Client();
$this->client->setApplicationName($application_name);
$this->client->setClientId($client_id);
$this->client->setClientSecret($client_secret);
$this->client->setRedirectUri($this->url);
$this->client->addScope("https://www.googleapis.com/auth/analytics.readonly");
$this->client->setApprovalPrompt('force');
$this->client->setAccessType('offline');
$this->client->refreshToken($token);
$this->service = new \Google_Service_Analytics($this->client);
}
public function get(){
$accounts = $this->service->management_accounts->listManagementAccounts();
$properties = $this->service->management_webproperties->listManagementWebproperties('~all');
$items = $properties->getItems();
$list = array();
$i = 0;
foreach ($items as $item) {
$list[$i]['name'] = $item->getName();
$list[$i]['nameurl'] = urlencode($name);
$list[$i]['id'] = $item->getAccountId();
$list[$i]['wpid'] = $item->getId();
$list[$i]['linkurl'] = urlencode($item->getChildLink()->getHref());
$i++;
}
return $list;
}
But I am having trouble with redirect. I am now stuck. How should I proceed? Any help is very much appreciated. Thanks.
You can use
Google API PHP Client (Laravel Bundle)
Which is a much simpler way to integrate google-api.
There is a very versatile library available for google Analytics in laravel 5..
https://github.com/spatie/laravel-analytics
I have used this and it is working well for me..
Using PHP, I am able to run BigQuery manually but I need BigQuery to run as an automatic cron job (without Gmail login). How would I accomplish this? Thanks.
You need to create a service account in the developer console, than you will be able to use from code. Here is a code that we have in our cron files.
properly creates a Google_Client using https://github.com/google/google-api-php-client
runs a job async
displays the running job ID and status
You need to have:
service account created (something like ...#developer.gserviceaccount.com)
your key file (.p12)
service_token_file_location (writable path to store the JSON from the handshake, it will be valid for 1h)
code sample:
function getGoogleClient($data = null) {
global $service_token_file_location, $key_file_location, $service_account_name;
$client = new Google_Client();
$client->setApplicationName("Client_Library_Examples");
$old_service_token = null;
$service_token = #file_get_contents($service_token_file_location);
$client->setAccessToken($service_token);
$key = file_get_contents($key_file_location);
$cred = new Google_Auth_AssertionCredentials(
$service_account_name, array(
'https://www.googleapis.com/auth/bigquery',
'https://www.googleapis.com/auth/devstorage.full_control'
), $key
);
$client->setAssertionCredentials($cred);
if ($client->getAuth()->isAccessTokenExpired()) {
$client->getAuth()->refreshTokenWithAssertion($cred);
$service_token = $client->getAccessToken();
}
return $client;
}
$client = getGoogleClient();
$bq = new Google_Service_Bigquery($client);
/**
* #see https://developers.google.com/bigquery/docs/reference/v2/jobs#resource
*/
$job = new Google_Service_Bigquery_Job();
$config = new Google_Service_Bigquery_JobConfiguration();
$config->setDryRun(false);
$queryConfig = new Google_Service_Bigquery_JobConfigurationQuery();
$config->setQuery($queryConfig);
$job->setConfiguration($config);
$destinationTable = new Google_Service_Bigquery_TableReference();
$destinationTable->setDatasetId(DATASET_ID);
$destinationTable->setProjectId(PROJECT_ID);
$destinationTable->setTableId('table1');
$queryConfig->setDestinationTable($destinationTable);
$sql = "select * from publicdata:samples.github_timeline limit 10";
$queryConfig->setQuery($sql);
try {
// print_r($job);
// exit;
$job = $bq->jobs->insert(PROJECT_ID, $job);
$status = new Google_Service_Bigquery_JobStatus();
$status = $job->getStatus();
// print_r($status);
if ($status->count() != 0) {
$err_res = $status->getErrorResult();
die($err_res->getMessage());
}
} catch (Google_Service_Exception $e) {
echo $e->getMessage();
exit;
}
//print_r($job);
$jr = $job->getJobReference();
//var_dump($jr);
$jobId = $jr['jobId'];
if ($status)
$state = $status['state'];
echo 'JOBID:' . $jobId . " ";
echo 'STATUS:' . $state;
You can grab the results with:
$res = $bq->jobs->getQueryResults(PROJECT_ID, $_GET['jobId'], array('timeoutMs' => 1000));
if (!$res->jobComplete) {
echo "Job not yet complete";
exit;
}
echo "<p>Total rows: " . $res->totalRows . "</p>\r\n";
//see the results made it as an object ok
//print_r($res);
$rows = $res->getRows();
$r = new Google_Service_Bigquery_TableRow();
$a = array();
foreach ($rows as $r) {
$r = $r->getF();
$temp = array();
foreach ($r as $v) {
$temp[] = $v->v;
}
$a[] = $temp;
}
print_r($a);
You can see here the classes that you can use for your other BigQuery calls. When you read the file, please know that file is being generated from other sources, hence it looks strange for PHP, and you need to learn reading it in order to be able to use the methods from it.
https://github.com/google/google-api-php-client/blob/master/src/Google/Service/Bigquery.php
like:
Google_Service_Bigquery_TableRow
Also check out the questions tagged with [php] and [google-bigquery]
https://stackoverflow.com/questions/tagged/google-bigquery+php
All the question about examples are like 2 years old, and I can't find ANY working example for current API client version (https://github.com/google/google-api-php-client). Every single one is missing something or throwing exception....
Could anybody provide working example? There is no documentation AT ALL, anywhere.
This is the most working one:
<?php
require_once 'inc/google-api/autoload.php'; // or wherever autoload.php is located
$client = new Google_Client();
$client->setApplicationName("whatever");
$client->setDeveloperKey("some key");
$service = new Google_Service_Bigquery($client);
$postBody = "[
'datasetReference' => [
'datasetId' => $datasetId,
'projectId' => $projectId,
],
'friendlyName' => $name,
'description' => $description,
'access' => [
['role' => 'READER', 'specialGroup' => 'projectReaders'],
['role' => 'WRITER', 'specialGroup' => 'projectWriters'],
['role' => 'OWNER', 'specialGroup' => 'projectOwners'],
],
]";
$dataset = $service->datasets->insert($projectId, new Google_Dataset($postBody));
$postBody = "[
'tableReference' => [
'projectId' => 'test_project_id',
'datasetId' => 'test_data_set',
'tableId' => 'test_data_table'
]
]";
$table = $service->tables->insert($projectId, $datasetId, new Google_Table($postBody));
?>
But I am getting Fatal errors about Google_Dataset and Google_Table not defined...
Here is a code that
properly creates a Google_Client
runs a job async
displays the running job ID and status
You need to have:
service account created (something like ...#developer.gserviceaccount.com)
your key file (.p12)
service_token_file_location (writable path to store the JSON from the handshake, it will be valid for 1h)
code sample:
function getGoogleClient($data = null) {
global $service_token_file_location, $key_file_location, $service_account_name;
$client = new Google_Client();
$client->setApplicationName("Client_Library_Examples");
$old_service_token = null;
$service_token = #file_get_contents($service_token_file_location);
$client->setAccessToken($service_token);
$key = file_get_contents($key_file_location);
$cred = new Google_Auth_AssertionCredentials(
$service_account_name, array(
'https://www.googleapis.com/auth/bigquery',
'https://www.googleapis.com/auth/devstorage.full_control'
), $key
);
$client->setAssertionCredentials($cred);
if ($client->getAuth()->isAccessTokenExpired()) {
$client->getAuth()->refreshTokenWithAssertion($cred);
$service_token = $client->getAccessToken();
}
return $client;
}
$client = getGoogleClient();
$bq = new Google_Service_Bigquery($client);
/**
* #see https://developers.google.com/bigquery/docs/reference/v2/jobs#resource
*/
$job = new Google_Service_Bigquery_Job();
$config = new Google_Service_Bigquery_JobConfiguration();
$config->setDryRun(false);
$queryConfig = new Google_Service_Bigquery_JobConfigurationQuery();
$config->setQuery($queryConfig);
$job->setConfiguration($config);
$destinationTable = new Google_Service_Bigquery_TableReference();
$destinationTable->setDatasetId(DATASET_ID);
$destinationTable->setProjectId(PROJECT_ID);
$destinationTable->setTableId('table1');
$queryConfig->setDestinationTable($destinationTable);
$sql = "select * from publicdata:samples.github_timeline limit 10";
$queryConfig->setQuery($sql);
try {
// print_r($job);
// exit;
$job = $bq->jobs->insert(PROJECT_ID, $job);
$status = new Google_Service_Bigquery_JobStatus();
$status = $job->getStatus();
// print_r($status);
if ($status->count() != 0) {
$err_res = $status->getErrorResult();
die($err_res->getMessage());
}
} catch (Google_Service_Exception $e) {
echo $e->getMessage();
exit;
}
//print_r($job);
$jr = $job->getJobReference();
//var_dump($jr);
$jobId = $jr['jobId'];
if ($status)
$state = $status['state'];
echo 'JOBID:' . $jobId . " ";
echo 'STATUS:' . $state;
You can grab the results with:
$res = $bq->jobs->getQueryResults(PROJECT_ID, $_GET['jobId'], array('timeoutMs' => 1000));
if (!$res->jobComplete) {
echo "Job not yet complete";
exit;
}
echo "<p>Total rows: " . $res->totalRows . "</p>\r\n";
//see the results made it as an object ok
//print_r($res);
$rows = $res->getRows();
$r = new Google_Service_Bigquery_TableRow();
$a = array();
foreach ($rows as $r) {
$r = $r->getF();
$temp = array();
foreach ($r as $v) {
$temp[] = $v->v;
}
$a[] = $temp;
}
print_r($a);
You can see here the classes that you can use for your other BigQuery calls. When you read the file, please know that file is being generated from other sources, hence it looks strange for PHP, and you need to learn reading it in order to be able to use the methods from it.
https://github.com/google/google-api-php-client/blob/master/src/Google/Service/Bigquery.php
like:
Google_Service_Bigquery_TableRow