Evernote Sandbox Oauth not working suddenly - evernote

I'm using https://github.com/evernote/evernote-cloud-sdk-php for my app. The Oauth process on my sandbox server was working perfectly fine, until today. The weird thing is, on the live server, its currently working perfectly fine.
Any ideas appreciated. Heres the code
$sandbox = env('EVERNOTE_SANDBOX');
$china = env('EVERNOTE_CHINA');
$callbackurl = env('APP_URL');
$oauth_handler = new \Evernote\Auth\OauthHandler($sandbox, false, $china);
$key = 'my key';
$secret = 'my secret ';
$callback = $callbackurl.'/api/connect';
try {
$oauth_data = $oauth_handler->authorize($key, $secret, $callback);
error_log(print_r($oauth_data,true));
}
Changing $sandbox = true doesn't change anything.
the error log at the end shows this.
[08-Mar-2019 08:38:00 UTC] Evernote\Auth\OauthHandler Object
(
[sandbox:protected] => 1
[china:protected] =>
[consumer_secret:protected] => [censored]
[token_secret:protected] =>
[supportLinkedSandbox:protected] =>
[params:protected] => Array
(
[oauth_callback] => http://server_ip_address/api/connect
[oauth_consumer_key] => [censored]
[oauth_nonce] => [censored]
[oauth_signature] =>
[oauth_signature_method] => HMAC-SHA1
[oauth_timestamp] => 1552034280
[oauth_version] => 1.0
)
)

Fixed it with a exit(); after
$oauth_data =.......
exit();

Related

How to connect WordPress / WooCommerce to a REST API with PHP?

I am trying to write my first REST API with PHP. We want to send shipping data to the shipping company and get labels for printing in return. The shipping company has given me test api credentials.
So I started to write a plugin with this code inside:
$url = "https://mywebsite/endpoint/";
$username = "myusername";
$password = "mypassword";
$data = array(
'key1' => 'value1',
'key2' => 'value2'
);
$response = wp_remote_post( $url, array(
'body' => $data,
'headers' => array(
'Authorization' => 'Basic ' . base64_encode( $username . ':' . $password ),
),
)
);
var_dump($response); // not being called
When I run this code, I get a white screen with no error message, the last line with var_dump($response) is not being called. I am a bit stuck here because I se no success and no error...what could it be? Why this behaviour of the remote server? Does it mean "sorry, wrong credentials" or "data has the wrong format"? I have the feeling that the server doesn't even notice that I'm trying to contact him...
I tried a number of other variatons of the above code that I found somwehere online, and also outside of WordPress, but no success.
The shipping company gave me a documentation. It says:
HTTP Method: POST
Authentication Header: Basic Authentication (user name/ password)
so I thought I could do no wrong when trying that. Hm.
I found a solution, so I can share it here with you.
I installed the free Software Postman and created a simple POST query there. After entering $url, $username and $password I ran a query and it worked well. the good thing abort Postman is that it creates code snippets for you. "very_long_cryptic_string" is obviously created from $username and $password. The PHP for my case goes like this, and it works:
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => '',
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => 'POST',
CURLOPT_HTTPHEADER => array(
'Authorization: Basic very_long_cryptic_string'
),
));
$response = curl_exec($curl);
curl_close($curl);
echo $response;

Google Calendar API in production

Can I ask you if there is anybody who can answer me a question about Google Calendar API? I have generated credentials and on localhost it works pretty fine. I just want to return like 100 upcoming events ($service->events->listEvents($calendarId, $optParams) but this same code on production doesn`t works, it returns 500 Internal Server Error especially on this piece of code. Any advice how to continue?
this is the piece of code and it breaks on the first commented line
<?php
require './vendor/autoload.php';
$client = new Google_Client();
$gazza = new GuzzleHttp\Client([
'verify' => './cacert.pem'
]);
$client->setApplicationName('Google Calendar API PHP Quickstart');
$client->setScopes(Google_Service_Calendar::CALENDAR_READONLY);
$client->setAuthConfig('./credentials-calendar-old.json');
$client->setAccessType('offline');
$tokenPath = 'token.json';
if (file_exists($tokenPath)) {
$accessToken = json_decode(file_get_contents($tokenPath), true);
$client->setAccessToken($accessToken);
}
$service = new Google_Service_Calendar($client);
$calendarId = 'primary';
$optParams = array(
'maxResults' => 1000,
'orderBy' => 'startTime',
'singleEvents' => true,
'timeMin' => date('c'),
);
$results = $service->events->listEvents($calendarId, $optParams);
$events = $results->getItems();
// Print the next 10 events on the user's calendar.
$calendarId = 'primary';
$optParams = array(
'maxResults' => 1000,
'orderBy' => 'startTime',
'singleEvents' => true,
'timeMin' => date('c'),
);
Thanks a lot,
Alex
Try to remove the code below, as far as I know this code is just for localhost, to force https.
$gazza = new GuzzleHttp\Client([
'verify' => './cacert.pem'
]);

Closure Compiler RESTFul API output_info Parameter

I'm using the Google Closure Compiler RESTFul API with WordPress.
The request is created using wp_remote_post() and so far everything went okay.
What I want to know is how to get the API to not only return the compiled code, but also the warnings, errors and statistics.
Supplying 'output_info' => array( 'compiled_code', 'warnings', 'errors', 'statistics' ) in the body parameter seems not to work and the API returns errors. Any ideas?
Thank you very much!
Just looked around and found out that Closure Compiler accepts output_info parameter multiple times. This is not possible with the WP_Http API without some modifications.
So I looked at the source of WP_Http and did the following, now it's working :)
// Default request data
$request_data = array(
'output_info' => array( 'compiled_code', 'warnings', 'errors', 'statistics' ),
'output_format' => 'json'
);
$request_data = array_merge( $request_data, $args, compact( 'js_code' ) );
// Process the request body manually to make same named parameters possible
$body = http_build_query( $request_data, null, '&' );
$body = preg_replace( '/output_info%5B\d+%5D=/', 'output_info=', $body );
// Initiate request
$response = wp_remote_post( CLOSURE_COMPILER_URL, array(
'sslverify' => false,
'timeout' => 10,
'headers' => array(
'Content-Type' => 'application/x-www-form-urlencoded; charset=' . get_option( 'blog_charset' )
),
'body' => $body
));

PHP-SDK publish link not available for public

When publishing a new link, using php sdk, the link is only available for logged user, it's not publish as public.
$facebook = new Facebook(array(
'appId' => $appId,
'secret' => $secret,
'cookie' => true
));
$user = $facebook->getUser(); // Get the UID of the connected user, or 0 if the Facebook user is not connected.
if($user == 0) {
setcookie('cod_eventos', $_POST['cod_eventos']);
$login_url = $facebook->getLoginUrl($params = array('scope' => "publish_stream"));
setcookie('userlogin', 1);
echo ("<script>window.open('".$login_url."')</script>");
} else {
$page_id = $page_id;
try {
$access_token = $facebook->getAccessToken();
$attachment2 = array(
'access_token' => $access_token
);
$page = $facebook->api('/me/accounts', 'get', $attachment2);
} catch (FacebookApiException $e) {
echo 'Unable to get page access token';
}
$privacy = array(
'value' => 'EVERYONE',
);
$attachment = array(
'access_token' => $page['data'][0]['access_token'],
'name' => 'Test',
'link' => 'http://www.facebook.com/',
'description' =>'Facebook',
'privacy' => json_encode($privacy),
);
try {
$facebook->api('/' . $page_id . '/feed', 'POST', $attachment);
echo '<div class="gestor_ficheiros_tipo">Event publish Facebook</div>';
}
catch (FacebookApiException $e)
{
echo '<div class="gestor_ficheiros_tipo">'.$e->getMessage().'</div>';
}
After running this the content is publish, but not view-able by un-registered facebook users
Apparently, despite what the API documentation says, the privacy setting is 'privacy_type', not 'privacy'. I found that out here on SO I think, but closed the tab so I can't immediately share the link.
Check the settings on your app as well - I think it's the 'Visibility of app and posts' setting defaults to 'Friends' instead of 'Public'. Maybe that'll do it?
I found out what was the problem, I was using facebook app in sandbox mode... :(. Once I've changed it started working perfectly

drupal using node.save with XMLRPC call to another site. "Access Denied" message

I have a piece of code on 1 drupal site to create a node another drupal site in a multi-site setup.
It looks like I'm getting the sessionid and logging in just fine, but when trying to create a "page" node, I get "Access denied". Under Services -> Settings I have "Key Authentication", "Use keys" is unchecked, and "Use sessid" is checked. I agev permissions for the logged in user: "create page content", "administer services", etc...
Below is my code:
<p>Test Page 1</p>
<? $url = 'http://drupal2.dev/xmlrpc.php'; ?>
<?
$conn = xmlrpc($url, 'system.connect');
print_r($conn);
?>
<p>--</p>
<?
$login = xmlrpc($url, 'user.login', $conn['sessid'], 'superuser_name', 'superuser_password');
print_r($login);
?>
<p>--</p>
<?
$data=array('type'=>'page', 'title'=>'Test', 'body'=>'test');
$data_s=serialize($data);
$result = xmlrpc($url, 'node.save', $login['sessid'], $data_s);
echo $result;
//echo $data_s;
?>
<?
if($error = xmlrpc_error()){
if($error->code > 0){
$error->message = t('Outgoing HTTP request failed because the socket could not be opened.');
}
drupal_set_message(t('Operation failed because the remote site gave an error: %message (#code).',
array(
'%message' => $error->message,
'#code' => $error->code
)
)
);
}
?>
The ouput of this script is:
Array ( [sessid] => 9eebdde9bf0bfd9610cc2f03af131a9c [user] => Array ( [uid] => 0 [hostname] => ::1 [roles] => Array ( [1] => anonymous user ) [session] => [cache] => 0 ) )
--
Array ( [sessid] => c0ca4c599e41e97e7a7ceb43ee43249e [user] => Array ( [uid] => 1 [name] => eric [pass] => 13583b155536098b98df41bb69fcc53 [mail] => email#gmail.com [mode] => 0 [sort] => 0 [threshold] => 0 [theme] => [signature] => [signature_format] => 0 [created] => 1271813934 [access] => 1275867734 [login] => 1275868794 [status] => 1 [timezone] => [language] => [picture] => [init] => email#gmail.com [data] => a:0:{} [roles] => Array ( [2] => authenticated user ) ) )
--
Access denied
I discovered recently that PHP session ids are more complex than I had thought.
For them to work, your XMLRPC transport needs to fully support cookies, which are used for Drupal's authentication.
Without cookies, each request is treated as a new anonymous request and is given a new session ID. So the fact that you've logged in means nothing to the next xmlrpc call you make.
I'm doing some work in python, and made a custom transport object to support cookies, and now it all works for me. I found out how to do this in python here:
http://osdir.com/ml/python.cherrypy/2005-12/msg00142.html
(edit-add) I might also add that the services module is pretty bad with its error reporting. For example, if you send an argument as a string when it's expecting an array (with the string in the array) you can often get access denied errors which don't really reflect the fact that there is a parameter error.
Check that the service is working as you expect by testing it out under Admin > Site Building > Services > Browse and click the service you want to use.
site 1 code:
function exmple2_cron() {
homes_sync_get_node_list();
}
function homes_sync_get_node_list() {
$methods = xmlrpc('http://example.com/map/xmlrpc.php', array('system.listMethods' => array()));
$node_ids = xmlrpc('http://example.com/map/xmlrpc.php', array('node.getAllHomes'=>array()));
if (xmlrpc_error()) {
$error = xmlrpc_error();
watchdog('homes_sync', 'Error getting node list from parent server. Error: #error.', array('#error' => $error);
}
else {
foreach ($node_ids as $nid) {
$nodes[] = $nid;
}
variable_set('parent_home_nodes', $nodes);
watchdog('homes_sync', 'Successfully retrieved node list from parent server.', array(), WATCHDOG_NOTICE);
}
homes_sync_perform_update();
}
function homes_sync_perform_update() {
$node_ids = variable_get('parent_home_nodes', 0);
foreach ($node_ids as $nid) {
$data = xmlrpc('http://example.com/map/xmlrpc.php', array('node.get' => array($nid)));print_r($data);exit;
$result = db_fetch_array(db_query('SELECT n.nid, n.title, n.type FROM {node} n WHERE n.title = "%s" AND n.type = "%s"', $data['title'], 'page'));
if (xmlrpc_error()) {
$error = xmlrpc_error();
watchdog('homes_sync', 'Could not perform XMLRPC request. Error: #error.', array('#error' => $error), WATCHDOG_CRITICAL);
} else {
if (is_array($data)) {
$node = "";
if ($result && $result['nid']) {
$node->nid = $result['nid'];
}
$node->type = $data['type'];
$node->uid = 1;
$node->status = $data['status'];
$node->created = $data['created'];
$node->changed = $data['changed'];
$node->comment = $data['comment'];
$node->promote = $data['promote'];
$node->moderate = $data['moderate'];
$node->sticky = $data['sticky'];
$node->tnid = $data['tnid'];
$node->translate = $data['translate'];
$node->title = $data['title'];
$node->body = $data['body'];
$node->teaser = $data['teaser'];
$node->format = $data['format'];
$node->name = $data['name'];
$node->data = $data['data'];
$node->path = $data['path'];
node_save($node);
unset($node);
}
}
}
}
remote site code:
function example_xmlrpc() {
$methods = array();
$methods[] = array(
'node.getAllHomes',
'homes_service_node_get_all_homes',
array('int'),
);
return $methods;
}
function homes_service_node_get_all_homes() {
$query = db_query('SELECT n.* FROM {node} n');
foreach ($query as $record){
$nid[] = $record;
}
return $nid;
}

Resources