I'm trying to get the yammer ID of a user based on an email address, I wrote this
$emailx="email#email.com";
function get_yammer_id($email){
$url = 'https://www.yammer.com/api/v1/users/by_email.json';
$response = wp_remote_get( $url, array(
'timeout' => 45,
'redirection' => 5,
'httpversion' => '1.0',
'blocking' => true,
'headers' => array( 'Host' => 'www.yammer.com', 'Authorization' => 'Bearer ********-**********************' ),
'body' => array( 'email' => $email),
'cookies' => array()
)
);
$return = $response;
return $return;
}
$result = get_yammer_id($emailx);
echo $result;
The last echo greets me with "Array" though.
If I try to swap it for
echo $result[0];
I'll get nothing. Any ideas?
It may not be the best solution but I found one
$emailx="email#email.com";
function get_yammer_id($email){
$url = 'https://www.yammer.com/api/v1/users/by_email.json';
$response = wp_remote_get( $url, array(
'timeout' => 45,
'redirection' => 5,
'httpversion' => '1.0',
'blocking' => true,
'headers' => array( 'Host' => 'www.yammer.com', 'Authorization' => 'Bearer *******-*********************' ),
'body' => array( 'email' => $email),
'cookies' => array()
)
);
$return = (explode(",",$response['body']));
return (int)str_replace('"id":', '', $return[1]);
}
$result = get_yammer_id($emailx);
echo $result;
Does anyone have a better one?
Related
i have a code.
$url = 'sample.com/endpoint';
$response = wp_remote_post( $url, array(
'method' => 'POST',
'timeout' => 45,
'redirection' => 5,
'httpversion' => '1.0',
'blocking' => true,
'headers' => array(),
'body' => array(
'gonderi_olustur' => 1,
'customer_id' => 1,
'product' => 3715,
'count' => 1,
'payment_type' =>'N',
'post_check_price' => 170
),
'cookies' => array('PHPSESSID'=>'0td1s9mj7osdk528sb347sn878')
));
I am saving data to a remote website through my wordpress site. while doing this I type the session id manually.
as in code: 'cookies' => array('PHPSESSID'=>'0td1s9mj7osdk528sb347sn878') .
I manually set the session id each time.
I want to automate this process. first i want to login to remote website and get session id and save other data.
I am logging in with the following code. returns successfully. but the session is not valid for subsequent post requests.
$url = 'https://sample.com/endpoint';
$body = [
'uye_eposta' => 'email',
'uye_sifre' => 'password',
'uye_giris '=> '1'
];
$body = wp_json_encode( $body );
$options = [
'body' => $body,
'headers' => [
'Content-Type' => 'application/json',
],
'timeout' => 60,
'redirection' => 5,
'blocking' => true,
'httpversion' => '1.0',
'sslverify' => false,
'data_format' => 'body',
];
$response = wp_remote_post( $url, $options );
$cookies = wp_remote_retrieve_cookies( $response );
$arr = (array)$cookies[0];
$session_id = $arr['value'];
My first post, related to the following post
How do I set a basic filter in php using google sheets api?
I have implemented code below but get this message and I'm not sure what's the cause:
Invalid JSON payload received. Unknown name "requests" at 'requests[0]': Cannot find field.
$criteria = new \stdClass();
$criteria->{'2'} = array(
'condition' => array(
'type' => 'NUMBER_EQ',
'values' => array(
'userEnteredValue' => '5'
)
)
);
$requests = [
new Google_Service_Sheets_Request( array(
'requests' => array(
'setBasicFilter' => array(
'filter' => array(
'range' => [
'sheetId' => 0,
'startRowIndex' => 4,
'endRowIndex' => 20,
'startColumnIndex' => 0,
'endColumnIndex' => 11
],
'criteria' => $criteria
),
),
'includeSpreadsheetInResponse' => true,
'responseIncludeGridData' => true
)
)
)
];
$requestBody = new Google_Service_Sheets_BatchUpdateSpreadsheetRequest(array('requests' => $requests));
$response = $sheets->spreadsheets->batchUpdate($spreadsheetId, $requestBody);
Modification points:
Please include 'userEnteredValue' => '5' to an array.
'requests' => array(,,,) is not required in new Google_Service_Sheets_Request(). Because array('requests' => $requests) is used.
Please put 'includeSpreadsheetInResponse' => true, and 'responseIncludeGridData' => true outside of $requests.
When above points are reflected to your script, it becomes as follows.
Modified script:
$criteria = new \stdClass();
$criteria->{'2'} = array(
'condition' => array(
'type' => 'NUMBER_EQ',
'values' => [array('userEnteredValue' => '5')]
)
);
$requests = [
new Google_Service_Sheets_Request( array(
'setBasicFilter' => array(
'filter' => array(
'range' => [
'sheetId' => 0,
'startRowIndex' => 4,
'endRowIndex' => 20,
'startColumnIndex' => 0,
'endColumnIndex' => 11
],
'criteria' => $criteria
)
)
)
)
];
$requestBody = new Google_Service_Sheets_BatchUpdateSpreadsheetRequest(array(
'requests' => $requests,
'includeSpreadsheetInResponse' => true,
'responseIncludeGridData' => true
));
$response = $sheets->spreadsheets->batchUpdate($spreadsheetId, $requestBody);
In this case, $criteria->{'2'} can be used, and also, $criteria->{'1'} instead of $criteria->{'2'} can be used.
References:
Method: spreadsheets.batchUpdate
SetBasicFilterRequest
I am trying to post into a WordPress site using the WP API. I have the code below but it does not seem to be working, am not getting any post in my site.
<?php
$options = array (
'http' =>
array (
'ignore_errors' => true,
'method' => 'POST',
'header' =>
array (
'Authorization' => 'Basic ' . base64_encode( 'user' . ':' . 'pass' ),
),
'content' =>
http_build_query( array (
'title' => 'Hello World',
'content' => 'Hello. I am a test post. I was created by the API',
'tags' => 'tests',
'categories' => 'API',
)),
),
);
$context = stream_context_create( $options );
$response = file_get_contents(
'http://freeglobaljob.com/wp-json/posts/',
false,
$context
);
$response = json_decode( $response );
?>
I would like to convert these into wp_remote_post()
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, "https://clients6.google.com/rpc");
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_POSTFIELDS, '[{"method":"pos.plusones.get","id":"p","params":{"nolog":true,"id":"'.rawurldecode($this->url).'","source":"widget","userId":"#viewer","groupId":"#self"},"jsonrpc":"2.0","key":"p","apiVersion":"v1"}]');
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-type: application/json'));
$curl_results = curl_exec ($curl);
curl_close ($curl);
$json = json_decode($curl_results, true);
I almost tried with this
$params = array(
'method' => 'POST',
'timeout' => 45,
'blocking' => true,
'headers' => array(
'Content-Type' => 'application/json'
),
'body' => array(
'method' => 'pos.plusones.get',
'id' => 'p',
'params'=> array (
'nolog' => true,
'id' => rawurldecode($url),
'source' => 'widget',
'userId' => '#viewer',
'groupId' => '#self',
),
'jsonrpc' => '2.0',
'key' => 'p',
'apiVersion' => 'v1',
),
);
$connection = wp_remote_post('https://clients6.google.com/rpc', $params);
But there is a error message like this - "Unable to parse json"
Please help
Thank You
This works
$params = array(
'method' => 'POST',
'timeout' => 45,
'blocking' => true,
'headers' => array(
'Content-Type' => 'application/json'
),
'body' => '['.json_encode( array(
'method' => 'pos.plusones.get',
'id' => 'p',
'params' => array(
'nolog' => true,
'id' => rawurldecode( $url ),
'source' => 'widget',
'userId' => '#viewer',
'groupId' => '#self',
),
'jsonrpc' => '2.0',
'key' => 'p',
'apiVersion' => 'v1',
) ).']'
);
$connection = wp_remote_post( 'https://clients6.google.com/rpc', $params );
Noticed a few inconsistencies. not sure if the syntax is throwing the errors but might fix the parsing....
$params = array(
'method' => 'POST',
'timeout' => 45,
'blocking' => true,
'headers' => array(
'Content-Type' => 'application/json'
),
'body' => array(
'method' => 'pos.plusones.get',
'id' => 'p',
'params'=> array(
'nolog' => true,
'id' => rawurldecode($url),
'source' => 'widget',
'userId' => '#viewer',
'groupId' => '#self'
),
'jsonrpc' => '2.0',
'key' => 'p',
'apiVersion' => 'v1'
)
);
I'm testing my API and there's a login method for OAuth that I can't seem to properly test due to how it will not read $_GET values of a variable when POSTing.
The login method. Basically $OAuthParams doesn't get set when using POST because getAuthorizeParams() uses $_GET. So I want to fill/mock either $_GET or $OAuthParams.
public function login () {
$OAuthParams = $this->OAuth->getAuthorizeParams();
if ($this->request->is('post')) {
$this->validateRequest();
$loginData = array('User' => array(
'username' => $this->request->data['User']['username'],
'passwd' => $this->request->data['User']['passwd']
));
//Attempted login
if ($this->Auth->login($loginData['User'])) {
unset($loginData);
$userData = $this->User->find('first',array(
'conditions' => array(
'User.username' => $this->request->data['User']['username']
),
'fields' => array('username','name','id','banned','active','role','private'),
'recursive' => -1
));
$this->Session->write('Auth.User',$userData['User']); //Update the session
//Write this to session so we can log them out after authenticating
$this->Session->write('OAuth.logout', true);
//Write the auth params to the session for later
$this->Session->write('OAuth.params', $OAuthParams);
//Off we go
return $this->redirect(array('action' => 'authorize'));
} else {
$this->Session->setFlash(__('Username or password is incorrect'), 'default', array(), 'auth');
}
}
$appName = $this->applicationDetails['name'];
$this->set(compact('OAuthParams','appName'));
}
The current test method.
/**
* testAccessToken method
* 1. Get the authorization code (/oauth/authorize?response_type=code&client_id=CLIENT_ID&client_secret=CLIENT_SECRET)
* 2. Retrieve the token (/oauth/token?grant_type=authorization_code&code=CODE_RETURNED&client_id=CLIENT_ID&client_secret=CLIENT_SECRET)
* 3. Parse the token from the returned data
* #return void
*/
public function testAccessToken(){
//#link http://stackoverflow.com/questions/8183396/dealing-with-security-component-in-a-cakephp-2-test-case
$this->OAuth = $this->generate('OAuth', array(
'components' => array(
'Security' => array('_validatePost'),
)
));
$this->OAuth->Security->expects($this->any())
->method('_validatePost')
->will($this->returnValue(true));
$get_data = array(
'response_type' => 'code',
'client_id' => getenv('THREE_SCALE_APP_ID'),
'client_secret' => getenv('THREE_SCALE_APP_KEY'),
);
$post_data = array(
'User' => array(
'username' => 'test_user_1',
'passwd' => 'tester'
)
);
$resultPost = $this->testAction(
'/oauth/login',
array(
'method' => 'post',
'data' => $post_data
)
);
debug($resultPost);
$data_for_code = array(
'accept' => 'Yep',
'Authorize' => array(
'client_id' => getenv('THREE_SCALE_APP_ID'),
'client_secret' => getenv('THREE_SCALE_APP_KEY'),
'response_type' => 'code',
'state' => '',
'scope' => ''
)
);
$code = $this->testAction(
'/oauth/authorize',
array(
'data' => $data_for_code,
'method' => 'post'
)
);
debug($code);
/*$data_for_token = array(
'grant_type' => 'authorization_code',
'code' => $code,
'client_id' => getenv('THREE_SCALE_APP_ID'),
'client_secret' => getenv('THREE_SCALE_APP_KEY')
);
$token = $this->testAction(
'/oauth/token',
array(
'data' => $data_for_token,
'method' => 'post'
)
);*/
//debug($token);
}
Tried the following with no luck.
$this->OAuth = $this->generate(
'OAuth',
array(
'components' => array(
'Security' => array( '_validatePost' ),
'Auth' => array('loggedIn','user')
),
'methods' => array(
'getAuthorizeParams'
)
)
);
$data = array(
'response_type' => 'code',
'client_id' => getenv('THREE_SCALE_APP_ID'),
'client_secret' => getenv('THREE_SCALE_APP_KEY')
);
$this->OAuth->expects($this->any())
->method('getAuthorizeParams')
->will($this->returnValue($data));
$loginData = array(
'User' => array(
'client_id' => getenv('THREE_SCALE_APP_ID'),
'client_secret' => getenv('THREE_SCALE_APP_KEY'),
'response_type' => 'code',
'state' => '',
'scope' => '',
'redirect_uri' => 'https://myurl.com/api/myCallbackMethod',
'username' => 'test_user_1',
'passwd' => 'tester'
)
);
//test login action
$resultPost = $this->testAction(
'/oauth/login?response_type=code&client_id=' . getenv('THREE_SCALE_APP_ID') . '&client_secret=' . getenv('THREE_SCALE_APP_KEY'),
array(
'method' => 'post',
'data' => $loginData
)
);
debug($resultPost);
$data = array(
'accept' => 'Yep',
'Authorize' => array(
'client_id' => getenv('THREE_SCALE_APP_ID'),
'client_secret' => getenv('THREE_SCALE_APP_KEY'),
'response_type' => 'code',
'state' => '',
'scope' => ''
)
);
$result = $this->testAction(
'/oauth/authorize',
array(
'data' => $data,
'method' => 'post'
)
);
debug($result);
Mock the getAuthorizeParams() function to return the values you want.
The functions inside OAuth that you want to mock are an array of strings with the 'methods' key, ie:
$this->generate(
'OAuth',
array(
'methods' => array(
'getAuthorizeParams'
),
'components' => array(
...
)
)
);
Then before you call your testAction() method:
$this->OAuth->expects($this->once())
->method('getAuthorizeParams')
->will($this->returnValue($YOUR_EXPECTED_VALUE));