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.
Related
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;
}
I want to hide the definition of endpoints in a WordPress rest api... in the case of https://www.wpwhitesecurity.com/wp-json I want to return a 404 or an empty array, but not the list of endpoints of the site.
Some idea?
Thanks!
From version 4.4.0 exists the hook rest_index, the documentation in https://developer.wordpress.org/reference/hooks/rest_index/ describes :
This contains the data describing the API. This includes information
about supported authentication schemes, supported namespaces, routes
available on the API, and a small amount of data about the site.
The next code is working perfectly as I needed :
function my_site_rest_index( $response ){
return array();
}
add_filter('rest_index', 'my_site_rest_index');
function chuck_disable_rest_endpoints( $access ) {
if( ! is_user_logged_in() ) {
return new WP_Error( 'rest_cannot_access', __( 'Only logged users are able to call REST API.', 'disable-json-api' ), array( 'status' => rest_authorization_required_code() ) );
}return $access;
}
add_filter( 'rest_authentication_errors', 'chuck_disable_rest_endpoints' );
This will return that only logged users can access to API
I'm making an app mobile and I need to upload a photo from my camera via my API. But when doctrine try to INSERT INTO, he isn't happy because my name field is null. So the name generate by my entity is missing.
I don't understand where the code block. My web app uses already the same entity photo and everything works fine.
My Api controller:
<?php
/**
* #throws AccessDeniedException
* #return array
* #FOSRest\View()
*/
public function apiUploadAction()
{
$photo = new Photo;
$photo->setUser($this->getUser());
$photo->setFile = new UploadedFile(
$_FILES["file"]["tmp_name"],
$_FILES["file"]["name"],
$_FILES["file"]["type"],
$_FILES["file"]["size"],
$_FILES["file"]["error"],
$test = false
);
$em = $this->getDoctrine()->getManager();
$em->persist($photo);
$em->flush();
$apiResponse = array(
"code" => true,
"style" => "success",
/*********** SCREENSHOT COMES FROM HERE ***********/
"message" => $_FILES["file"]["tmp_name"]." ".$_FILES["file"]["name"]." ".$_FILES["file"]["type"]." ".$_FILES["file"]["size"]." ".$_FILES["file"]["error"],
);
$view = View::create();
$view->setFormat('json');
$view->setData($apiResponse);
return $this->get('fos_rest.view_handler')->handle($view);
}
The $apiResponse.message (screenshot):
As you can see symfony has the image so the problem don't come from my app mobile. new UploadedFile(); is the right way ? To upload without form.
Here is the solution :
Replace :
$photo->setFile = new UploadedFile(
$_FILES["file"]["tmp_name"],
$_FILES["file"]["name"],
$_FILES["file"]["type"],
$_FILES["file"]["size"],
$_FILES["file"]["error"],
$test = false
);
by
$photo->setFile($this->getRequest()->files->get('file'));
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.
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.