Google API PHP Client - retrieve calendar list and events - google-calendar-api

The documentation for google calendar api is out of date, I am unable to get even a simple calendar list. Here is my code so far.
<?php
require_once "includes/partials/_header.php";
set_include_path(get_include_path() . '/google-api-php-client/src');
$client_id = 'xxxx.apps.googleusercontent.com';
$service_account = 'xxxx#developer.gserviceaccount.com';
$p12 = 'xxxx-privatekey.p12';
session_start();
require_once 'Google/Client.php';
require_once 'Google/Service/Calendar.php';
$client = new Google_Client();
$client->setApplicationName("Calendrier");
if (isset($_SESSION['token'])) {
$client->setAccessToken($_SESSION['token']);
}
$key = file_get_contents($p12);
$client->setClientId($client_id);
$cred = new Google_Auth_AssertionCredentials(
$service_account,
array('https://www.googleapis.com/auth/calendar'),
$key);
$client->setAssertionCredentials($cred);
if($client->getAuth()->isAccessTokenExpired()) {
$client->getAuth()->refreshTokenWithAssertion($cred);
}
$_SESSION['service_token'] = $client->getAccessToken();
$cal = new Google_Service_Calendar($client);
$events = $cal->calendarList->listCalendarList();
echo "<pre>";
print_r($events);
echo"</pre>";
while(true) {
foreach ($events->getItems() as $event) {
echo $event->getSummary();
print_r($event);
}
$pageToken = $events->getNextPageToken();
if ($pageToken) {
$optParams = array('pageToken' => $pageToken);
$events = $service->calendarList->listCalendarList($optParams);
} else {
break;
}
}
?>
I got a lot of this code from different sites because the docs were out of date, now I'm totally stuck as I've been googling all day. Any insight?
All i get so far is a response like this with no "items"
Google_Service_Calendar_CalendarList Object
(
[etag] => "xxxxxxxxxxxx"
[itemsType:protected] => Google_Service_Calendar_CalendarListEntry
[itemsDataType:protected] => array
[kind] => calendar#calendarList
[nextPageToken] =>
[nextSyncToken] => 00001401741798955000
[collection_key:protected] => items
[modelData:protected] => Array
(
[items] => Array
(
)
)
[processed:protected] => Array
(
)
)

Allright, this is embarassing after all the time I spent on this. For some reason I never tried making the calendar public. I just assumed that with all the authorization steps that you could access the calendar from project account. Guess not.
Easy fix... just make the calendar public in its settings.
for events replace $cal->calendarlist part with
$cal->events->listEvents('calendarID', $optionalParams);
Note: I'm not even sure all the authorization/access token stuff in session is needed it seems the docs page of google cal still uses the old php client. I believe it should work using only the service account (setAssertionCredentials) the rest with the session im not sure.

Related

Get list of Webhooks from Woocommerce

I have built a Wordpress plugin that among other things, creates several Woocommerce Webhooks upon activation. This is done using internal API classes and functions, as per below:
function createWebhook($userID,$topic,$secret,$deliveryURL,$status)
{
$webhook = new WC_Webhook();
$webhook->set_user_id($userID); // User ID used while generating the webhook payload.
$webhook->set_topic( $topic ); // Event used to trigger a webhook.
$webhook->set_secret( $secret ); // Secret to validate webhook when received.
$webhook->set_delivery_url( $deliveryURL ); // URL where webhook should be sent.
$webhook->set_status( $status ); // Webhook status.
$save = $webhook->save();
return $save;
}
This works well.
What I want to be able to do is remove these Webhooks upon deactivation of the plugin. Is there any way to fetch the Woocommerce Webhooks via the internal Wordpress or Woocommerce API, so I can loop through and remove the relevant ones?
I would just remove all Webhooks where the delivery URL has a domain of xyz.com. This part is straight-forward, I just don't know how to fetch the Webhooks.
I don't want to use the external Woocommerce API, which requires an API key and HTTP requests.
Thanks
I ended up querying the database to get the webhooks, which looks to be working well. I'm not sure there's any other way. Please let me know if there is!
global $wpdb;
$results = $wpdb->get_results( "SELECT webhook_id, delivery_url FROM {$wpdb->prefix}wc_webhooks" );
foreach($results as $result)
{
if(strpos($result->delivery_url, 'domain.com') !== false)
{
$wh = new WC_Webhook();
$wh->set_id($result->webhook_id);
$wh->delete();
}
}
#greg's answer points you in the right direction, but the returned data is just an array of ID's for each webhook, to get more data you need to parse those ID's into webhook objects - which has protected props, but public getter methods, like so:
$data_store = \WC_Data_Store::load( 'webhook' );
$webhooks = $data_store->search_webhooks([ 'status' => 'active', 'paginate' => true ] );
$_items = array_map( 'wc_get_webhook', $webhooks->webhooks );
$_array = [];
foreach( $_items as $_item ){
$_array[] = [
'id' => $_item->get_id(),
'name' => $_item->get_name(),
'topic' => $_item->get_topic(),
'delivery_url' => $_item->get_delivery_url(),
'secret' => $_item->get_secret(),
];
}
You can get an array of all webhook IDs with the following:
$data_store = WC_Data_Store::load( 'webhook' );
$webhooks = $data_store->search_webhooks();
That's what WooCommerce does when building the table list:
https://github.com/woocommerce/woocommerce/blob/master/includes/admin/class-wc-admin-webhooks-table-list.php

From Wordpress plugin data is not getting inserted into custom table

I have created a plugin to insert and fetch records. When I save record, record is getting saved from localhost but when I try it on online server it is not getting saved. Here is what I am trying to do.
function data_custom_ajax(){
global $wpdb;
$tbl = "tripplan";
$table_name=$wpdb->prefix . $tbl;
$custom_val = $_POST['text'];
$totaltime = $_COOKIE['totalduration'];
$totaldistance = $_COOKIE['totaldistance'];
$origin_address = $custom_val['originaddress'];
$end_address = $custom_val['destinationaddress'];
$waypoints = $custom_val['waypts'];
$wpdb->insert($table_name,
array(
'startpoint' => $origin_address,
'endpoint' => $end_address,
'waypoints' => json_encode($waypoints),
'totaldistance' => $totaldistance,
'totalduration' => $totaltime
),
array('%s','%s','%s','%f','%f')
);
echo "data has been saved";
}
function data_custom_ajax(){
global $wpdb;
$tbl = "tripplan";
$table_name=$wpdb->prefix . $tbl;
$custom_val = $_POST['text'];
$totaltime = $_COOKIE['totalduration'];
$totaldistance = $_COOKIE['totaldistance'];
$origin_address = $custom_val['originaddress'];
$end_address = $custom_val['destinationaddress'];
$waypoints = $custom_val['waypts'];
$data = array(
'startpoint' => $origin_address,
'endpoint' => $end_address,
'waypoints' => json_encode($waypoints),
'totaldistance' => $totaldistance,
'totalduration' => $totaltime
)
$lastInsertedId = $wpdb->insert($table_name,$data);
if($lastInsertedId != '')
{
echo "data has been saved";
}else{
$wpdb->print_error();
}
die();
}
After lot of reading and debugging I got to know the problem. My cookie was not getting saved correctly. Even though it was working on localhost, it was not working on website. After reading this [PHP cannot read javascript cookies and then after I modified my cookie while saving.
I was setting cookie like this and it was not working-
document.cookie="cookiename="+value
after setting this way it worked -
document.cookie = 'cookiename='+value+'; path=/'

What I am doing wrong with twitter API?

I am making a widget using https://github.com/j7mbo/twitter-api-php.
My widget is working fine there is no problem in my widget.
So what's the problem:
Inside my TwitterWidget Class whichi is extending WP_Widget inside the widget( $args, $instance ). I have make a function inside :
Here is it:
function get_Connection_With_Twitter_API( $scr_name, $cons_key, $cons_secret, $acce_token_key, $acce_token_secret ) {
$settings = array(
'oauth_access_token' => $acce_token_key,
'oauth_access_token_secret' => $acce_token_secret,
'consumer_key' => $cons_key,
'consumer_secret' => $cons_secret
);
$url = 'https://api.twitter.com/1.1/followers/ids.json';
$getfield = '?screen_name='.$scr_name;
$requestMethod = 'GET';
$twitter = new TwitterAPIExchange($settings);
echo $twitter->setGetfield($getfield)
->buildOauth($url, $requestMethod)
->performRequest();
// $twitter = new TwitterAPIExchange($settings);
// return $twitter->buildOauth($url, $requestMethod)
// ->setPostfields($postfields)
// ->performRequest();
}
$connection = get_Connection_With_Twitter_API( $instance['twitter_username'], $instance['twitter_consumerkey'], $instance['twitter_consumersecret'], $instance['twitter_accesstoken'], $instance['twitter_accesstokensecret'] );
I am getting this message:
{"errors":[{"code":89,"message":"Invalid or expired token."}]}
What I am doing wrong.
I assume you have your access tokens and you are being careful not displaying them here, and you have created a new app on the twitter account. On that light, I strongly suggest you change the permission of your app to "Read, Write and Direct Message".
For the perfect and most simple and well documented api, I suggest Twit.

wordpress site integration with rest API

I'm trying to integrate with zoom.us, they have their guides here - https://support.zoom.us/hc/en-us/articles/201363053-Meeting-API
When someone schedules a meeting, the scheduler creates a post, which I pick up and call this function:
function scheduler_zoom_integration($post_id) {
$postdata = get_post($post_id);
$appointment_id = get_post_meta( $post_id, '_birs_appointment_id', true );
if (!empty($appointment_id)) {
$conference_details = schedule_meeting();
add_post_meta($appointment_id,'appointment_zoom_details', $conference_details, true);
}
}
add_action('publish_post', 'scheduler_zoom_integration');
Inside that function I call the schedule_meeting function that is using the REST API from zoom to get the meeting details including the link people will click to join the meeting.
function schedule_meeting($coach_id, $appointment_id, $start_time) {
$api_key = 'xxxxxxxxxxxxxxxxxxxxxxx';
$api_secret = 'xxxxxxxxxxxxxxxxxxxxxxxxxxx';
$coach_zoom_id = get_user_meta($coach_id, 'coachzoomid', true);
$url = 'https://api.zoom.us/v1/meeting/create?api_key='.$api_key.'&api_secret='.$api_secret.'&data_type=JSON&host_id='.$coach_zoom_id.'&topic=health&type=2&start_time='.$start_time.'&duration=30&timezone=GMT-7:00&option_jbh=true&option_start_type=video';
$opts = array(
'http'=>array(
'method'=>"GET",
'header'=>"Accept-language: en\r\n" .
"Cookie: foo=bar\r\n"
)
);
$context = stream_context_create($opts);
$response = fopen($url, 'r', false, $context);
fpassthru($response);
$response = json_decode($response);
fclose($response);
return $response;
}
I'm looking to get feedback on how I'm performing this function as I've never done a REST API before. Should I use fopen / fclose? How do I make the call to begin with? Any help is appreciated.
You should try using WordPress' built in HTTP API. It has helper functions for doing HTTP calls. I see you're doing a GET so check out:
http://codex.wordpress.org/Function_Reference/wp_remote_get
Note that it returns WP_Error class on failure.

prestashop user login integration

I have to integrate PrestaShop 1.5 with pre-existing symfony application.
Through webservices, I can keep the databases in sync so a user can perform login with the same data on both PrestaShop and application software.
Now I want to to ensure that logging in application, the user is automatically logged in the PrestaShop platform.
Can you help me?
I don't know if you're still searching for a solution but there is a way actually.
DO MAKE SURE IT IS A SECURE LOGIN.
Since you're giving access to all prestashop data do make sure the login is very secure. I've been able to recreate it with PHP I think that with some additions you're able to recreate it the way you want it. See it as a guideline.
To create a login system by using the prestashop webservice you'll need three things
Access through webservice to the customers table
The COOKIE_KEY, defined in app/config -> parameters.php:: 'cookie_key' => '12321test';
Some expierence with PHP
The first thing is to get the customers table from the webservice.
// code placeholder
require_once('./../PSWebServiceLibrary.php');
/**
* get information from PrestaShop
*/
$webService = new PrestaShopWebservice($url, $key, $debug);
$COOKIE_KEY = 'CookieKey';
$email = $_REQUEST['email'];
$password = $_REQUEST['password'];
$optUser = array(
'resource' => 'customers',
'filter[email]' => '[' . $email . ']',
'display' => '[id,email,lastname,firstname,passwd]'
);
$resultUser = ($webService->get($optUser));
$json = json_encode($resultUser);
The second and most important thing is to Check the user input
// code placeholder
foreach ($resultUser->customers->customer as $info) {
// Prestashop uses the cookie_key in combination with a salt key. To check the password use the php function: password_verify();
$salt = substr($info->passwd, strrpos($info->passwd, ':') + 1, 2);
$ZCpassword = md5($COOKIE_KEY . $password) . ':' . $salt;
// Check if password comparison is true or false
if (password_verify($password, $info->passwd) == true) {
session_start();
$response = array();
$response['status'] = 'succes';
$response['message'] = "You did it!";
setcookie("userId", $info->id);
header('Content-type: application/json');
echo json_encode($response);
} else {
$response = array();
$response['status'] = 'error';
$response['message'] = 'Wrong password';
header('Content-type: application/json');
echo json_encode($response);
}
}
This is how to reproduce the issue to a working example.
What i've used is setting a cookie and check if it exists!
Hope this helps!

Resources