wordpress site integration with rest API - wordpress

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.

Related

How to translate order status on API response

Is there any way how to translate order status on API response
“https://test.com/wp-json/wc/v3/orders “.
{
“status”: “processing”,
}
Thank you
In order to use this in PHP, we need to translate it to a format that PHP understands. To do this, we can use the json_decode() function.
$json = '{"key":"value"}';
// Translate into an object
$obj = json_decode( $json );
// Translate into an array
$array = json_decode( $json, true );

How to add meta fields to media using Wordpress REST API v2 by using Postman?

I want to be able to add meta to a media post type by using WP REST API.
I want to use Postman because, for now, I just want to test how the API is working. The docs seems to be somewhat confusing. I would be grateful if you have any working examples.
Basically, I want to add copyright meta field to the media using this API.
for creating API you need to add route first. you can add route using below code:
function custom_meta_api() {
register_rest_route('wp/v1', '/update_meta/(?P<id>[\d]+)', array(
array(
'methods' => 'POST',
'callback' => 'saveMeta',
),
));
}|
add_action('rest_api_init', 'custom_meta_api');
you can pass your image id in (?P<id>[\d]+)
now in postman write url
http://your-url/wp-json/wp/v1/update_meta/5 with POST request
in body you can write below code
{"data":
{
"copyright":"xyz"
}
}
and to save in postmeta table create function saveMeta(which you have written in callback). Code for the function is below:
function saveMeta(WP_REST_Request $data) {
$bookingID = $data['id'];
$request = $data->get_json_params();
extract($request['data']);
update_post_meta($bookingID, 'copyright', $copyright);
$response = array();
$response["code"] = "success";
$response["message"] = "";
$response["data"] = array();
$response["data"][] = 'meta added';
return $response;
}

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.

Google API PHP Client - retrieve calendar list and events

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.

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