I am using REST to call the Magento product list, but it is only showing 10 products instead of all of them.
Could anyone guide because of what this problem may occur?
This is the code I am using to call the rest api :-
$url = 'magentohost url';
$callbackUrl = $url . "oauth_admin.php";
$temporaryCredentialsRequestUrl = $url . "oauth/initiate?oauth_callback=" . urlencode($callbackUrl);
$adminAuthorizationUrl = $url . 'admin/oauth_authorize';
$accessTokenRequestUrl = $url . 'oauth/token';
$apiUrl = $url . 'api/rest';
$consumerKey = 'consumer_key';
$consumerSecret = 'consumer_secret';
$token = 'token';
$secret = 'token_secret';
try {
$oauthClient = new OAuth($consumerKey, $consumerSecret, OAUTH_SIG_METHOD_HMACSHA1, OAUTH_AUTH_TYPE_AUTHORIZATION);
$oauthClient->setToken($token, $secret);
$resourceUrl = "$apiUrl/products";
$oauthClient->fetch($resourceUrl, array(), 'GET', array('Content-Type' => 'application/json', 'Accept' => 'application/json'));
$productsList = json_decode($oauthClient->getLastResponse());
echo '<pre>';
print_r($productsList);
}
catch(Exception $e) {
echo '<pre>';
print_r($e);
}
It is giving me proper output, but never more than 10 products, when I want to output all of them.
By Default the limit is 10. You can pass the limit as follows:
You can define the limit of items returned in the response by passing the limit parameter. By default, 10 items are returned and the maximum number is 100 items. You can also define the page number by passing the page parameter. Example:
http://magentohost/api/rest/products?page=2&limit=20
I would like to add from the comment above. You should copy app/code/core/mage/Api2/Model/Resource.php to app/code/local/mage/Api2/Model/Resource.php and make your changes in he local file. You should NEVER edit the core Magento files, otherwise, if you upgrade your Magento system, you lose your changes.
We can set the default number of product response and maximum number of products.
Go to app/code/core/mage/Api2/Model/Resource.php
Change as per our need.
/**##+
* Collection page sizes
*/
const PAGE_SIZE_DEFAULT = 10;
const PAGE_SIZE_MAX = 200;
/**##-*/
Related
I'm trying to add new users to moodle 3.2 using a REST web service, and i want to customize thees fields (phone1, department, institution) in the student profile.
I used this code
$token = 'a38805c00f33023f7854d5adc720c7a7';
$domainname = 'http://localhost/moodle';
$functionname = 'core_user_create_users';
$restformat = 'json';
$user2 = new stdClass();
$user2->username = strtolower( $rsnew['Serial']);
$user2->password = $rsnew['pass'];
$user2->firstname = $rsnew['Fname'];
$user2->lastname = $rsnew['Lname'];
$user2->email = $rsnew['Email'];
$user2->lang = 'en';
$user2->auth = 'manual';
$user2->country = $rsnew['Country'];
$user2->timezone = '99';
$user2->phone1 = $rsnew['phone'];
$user2->department = $rsnew['dept'];
$user2->institution = $rsnew['branch'];
$user2->idnumber = $rsnew['grade'];
$users = array($user2);
$params = array('users' => $users);
$serverurl = $domainname . '/webservice/rest/server.php'. '?wstoken=' . $token . '&wsfunction='.$functionname;
require_once('./curl.php');
$curl = new curl;
$restformat = ($restformat == 'json')?'&moodlewsrestformat=' . $restformat:'';
$resp = $curl->post($serverurl . $restformat, $params);
But i get this error :
{
"exception": "invalid_parameter_exception",
"errorcode": "invalidparameter",
"message": "Invalid parameter value detected",
"debuginfo": "users => Invalid parameter value detected: Unexpected keys (phone1, department, institution) detected in parameter array."
}
What should I do to fix that?
Just as the error suggests, that web service does not support the fields you are giving it. You can refer to the function itself to find out what fields are supported and what data they must contain.
core_user_get_users
I am not aware of a workaround for your problem using existing web services. However, you can create your own which includes those additional fields.
Note that this sounds to me like this is a desirable feature and should be raised on the issue tracker.
I can get data from the Trello API using this:
private function get_card_info($card_id) {
$client = new \GuzzleHttp\Client();
$base = $this->endpoint . $card_id;
$params = "?key=" . $this->api_key . "&token=" . $this->token;
$cardURL = $base . $params;
$membersURL = $base . "/members" . $params;
$attachmentsURL = $base . "/attachments" . $params;
$response = $client->get($cardURL);
$this->card_info['card'] = json_decode($response->getBody()->getContents());
$response = $client->get($membersURL);
$this->card_info['members'] = json_decode($response->getBody()->getContents());
$response = $client->get($attachmentsURL);
$this->card_info['attachments'] = json_decode($response->getBody()->getContents());
}
However, this is broken into three calls. Is there a way to get card information, the member information, and the attachment information all in one call? The docs mention using &fields=name,id, but that only seems to limit what's returned from the base call to the cards endpoint.
It's absurd to have to hit the API 3 times every time I need card information, but I can't find any examples gathering all that's needed.
Try hitting the API with following parameters:
/cards/[id]?fields=name,idList&members=true&member_fields=all&& attachments=true&&attachment_fields=all
Trello replied to me, and stated that they would have answered much like Vladimir did. However, the only response I got from that was the initial card data, sans attachments and members. However, they also directed me to this blog post that covers batching requests. They apparently removed it from the docs because of the confusion it created.
To summarize the changes, you essentially make a call to /batch, and append a urls GET parameter with a comma separated list of endpoints to hit. The working final version ended up looking like this:
private function get_card_info($card_id) {
$client = new \GuzzleHttp\Client();
$params = "&key=" . $this->api_key . "&token=" . $this->token;
$cardURL = "/cards/" . $card_id;
$members = "/cards/" . $card_id . "/members";
$attachmentsURL = "/cards/" . $card_id . "/attachments";
$urls = $this->endpoint . implode(',', [$cardURL, $members, $attachmentsURL]) . $params;
$response = $client->get($urls);
$this->card = json_decode($response->getBody()->getContents(), true);
}
To generate/initiate a new vulnerability scan at SoftLayer, this works (for every server in an account):
require_once('SoapClient.class.php');
$apiUsername = "omitted";
$apiKey = "omitted";
$client = SoftLayer_SoapClient::getClient('SoftLayer_Account', null, $apiUsername, $apiKey);
$accountInfo = $client->getObject();
$hardware = $client->getHardware();
foreach ($hardware as $server){
$scanclient = SoftLayer_SoapClient::getClient('SoftLayer_Network_Security_Scanner_Request', '', $apiUsername, $apiKey);
$scantemplate = new stdClass();
$scantemplate->accountId = $accountInfo->id;
$scantemplate->hardwareId = $server->id;
$scantemplate->ipAddress = $server->primaryIpAddress;
try{
// Successfully creates new scan
$scan = $scanclient->createObject($scantemplate);
} catch (Exception $e){
echo $e->getMessage() . "\n\r";
}
}
When changing
$reportstatus = $scanclient->createObject($scantemplate);
to
$reportstatus = $scanclient->getReport($scantemplate);
The API responds with an error concerning "Object does not exist to execute method on.".
Would SoftLayer_Network_Security_Scanner_RequestInitParameters be required as per the docs? If so how do you define these "init parameters" and attach to the request for status or report?
http://sldn.softlayer.com/reference/services/SoftLayer_Network_Security_Scanner_Request/getReport
You need to set the init parameter using the Softlayer PHP client you can do that like this:
When you are creating the client:
$virtualGuestService = SoftLayer_SoapClient::getClient('SoftLayer_Virtual_Guest', $initParemter, $username, $key);
Or after creating the client:
$virtualGuestService = SoftLayer_SoapClient::getClient('SoftLayer_Virtual_Guest', null, $username, $key);
# Setting the init parameter
$virtualGuestService->setInitParameter($virtualGuestId);
The init parameter is basically the id of the object you wish to get edit or delete, in this case the init parameter is the id of the vulnerability scan you wish to get the report.
You can try this code:
$scanclient = SoftLayer_SoapClient::getClient('SoftLayer_Network_Security_Scanner_Request', '', $apiUsername, $apiKey);
$scanclient->setInitParameter(15326); # The id of the vulnerability scan
$reportstatus = $scanclient->getReport();
To get the list of your vulnerabilities scans in a VSI you can use this method:
http://sldn.softlayer.com/reference/services/SoftLayer_Virtual_Guest/getSecurityScanRequests
and for bare metal servers you can use this one:
http://sldn.softlayer.com/reference/services/SoftLayer_Hardware_Server/getSecurityScanRequests
Regards
I've followed the directions posted in this stackoverflow question, but I am stuck.
I am using tumblr/tumblr.php from Github (the official "PHP client for the tumblr API").
I am also following directions here (which are actually for twitter), but those directions aren't tailored for the git library I am using.
I have a valid consumer key and secret.
From those I make a request and get oauth_token and oauth_token_secret like so:
$client = new Tumblr\API\Client($consumerKey,$consumerSecret);
$client->getRequestHandler()->setBaseUrl('https://www.tumblr.com/');
$req = $client->getRequestHandler()->request('POST', 'oauth/request_token', [
'oauth_callback' => '...',
]);
// Get the result
$result = $req->body->__toString();
print_r( $result );
Which gives me:
oauth_token=2C6f...MqSF&oauth_token_secret=HaGh...IJLi&oauth_callback_confirmed=true
Then I send the user to the http://www.tumblr.com/oauth/authorize?oauth_token=2C6f...MqSF, so they can allow access for the app. This redirects to: ...?oauth_token=2C6f...MqSF&oauth_verifier=nvjl...GtEa#_=_
And now in the final step I believe I am supposed to convert my request token to an access token. Is that right? I am doing something wrong:
$client = new Tumblr\API\Client($consumerKey,$consumerSecret);
$client->getRequestHandler()->setBaseUrl('https://www.tumblr.com/');
$req = $client->getRequestHandler()->request('POST', 'oauth/access_token', [
'oauth_token' => '2C6f...MqSF',
'oauth_verifier' => 'nvjl...GtEa'
]);
// Get the result
$result = $req->body->__toString();
print_r( $result );
because I get responses like this one:
oauth_signature [AqbbYs0XSZ7plqB0V3UQ6O6SCVI=] does not match expected value [0XwhYMWswlRWgcr6WeA7/RrwrhA=]
What is wrong with my last step?
I am not sure if I should even be sending oauth_verifier with the request. Is #_=_ supposed to be part of oauth_verifier? I wouldn't think so. I get signature errors for all the variations Ive tried.
Without the token and tokenSecret I can't make certain calls to the API. I get unauthorized 403 responses. Same when I use the token and token_secret from the second step. I'm pretty sure I need a new token/secret pair.
You're pretty close, you just are passing the oauth_token incorrectly in the last step, and skipping out on oauth_token_secret altogeter.
I've compiled this working code (which you can also now find posted on the Wiki at https://github.com/tumblr/tumblr.php/wiki/Authentication):
<?php
require_once('vendor/autoload.php');
// some variables that will be pretttty useful
$consumerKey = '<your consumer key>';
$consumerSecret = 'your consumer secret>';
$client = new Tumblr\API\Client($consumerKey, $consumerSecret);
$requestHandler = $client->getRequestHandler();
$requestHandler->setBaseUrl('https://www.tumblr.com/');
// start the old gal up
$resp = $requestHandler->request('POST', 'oauth/request_token', array());
// get the oauth_token
$out = $result = $resp->body;
$data = array();
parse_str($out, $data);
// tell the user where to go
echo 'https://www.tumblr.com/oauth/authorize?oauth_token=' . $data['oauth_token'];
$client->setToken($data['oauth_token'], $data['oauth_token_secret']);
// get the verifier
echo "\noauth_verifier: ";
$handle = fopen('php://stdin', 'r');
$line = fgets($handle);
// exchange the verifier for the keys
$verifier = trim($line);
$resp = $requestHandler->request('POST', 'oauth/access_token', array('oauth_verifier' => $verifier));
$out = $result = $resp->body;
$data = array();
parse_str($out, $data);
// and print out our new keys
$token = $data['oauth_token'];
$secret = $data['oauth_token_secret'];
echo "\ntoken: " . $token . "\nsecret: " . $secret;
// and prove we're in the money
$client = new Tumblr\API\Client($consumerKey, $consumerSecret, $token, $secret);
$info = $client->getUserInfo();
echo "\ncongrats " . $info->user->name . "!\n";
I spent my last 5 hours in this issue and finally I came here for the solution.
I am doing log-in using twitter functionality in my site (Zend Framework + PHP) and everything is working fine. But I am facing the following issue in it:
If the user has no tweets (0 tweets) in his account then the
$tweets = json_decode($response->getBody());
echo "<pre>";
print_r($tweets);
exit;
Its showing me blank array. i.e. : Array(); :-(
And if I am adding some tweets there in twitter account then its showing me the complete array along with user information like display name, image, etc...like this:
Array
(
//other data
[0] => stdClass Object
(
[user] => stdClass Object
....
....
so on..
)
)
Following is my code :
public function twitterregisterAction() {
$path = realpath(APPLICATION_PATH . '/../library/');
set_include_path($path);
session_start();
require $path . "/Zend/Oauth/Consumer.php";
$config = array(
"callbackUrl" => "http://" . $_SERVER['HTTP_HOST'] . "/register/twittercallback",
"siteUrl" => "http://twitter.com/oauth",
"consumerKey" => "xxxxxxxxxxxxx",
"consumerSecret" => "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
);
$consumer = new Zend_Oauth_Consumer($config);
// fetch a request token
$token = $consumer->getRequestToken();
// persist the token to storage
$_SESSION["TWITTER_REQUEST_TOKEN"] = serialize($token);
// redirect the user
$consumer->redirect();
}
/*
* Ticket id #16
* twittercallbackAction method
*/
public function twittercallbackAction() {
$config = array(
"callbackUrl" => "http://" . $_SERVER['HTTP_HOST'] . "/register/twittercallback",
"siteUrl" => "http://twitter.com/oauth",
"consumerKey" => "xxxxxxxxxxxxxxxxxx",
"consumerSecret" => "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
);
$consumer = new Zend_Oauth_Consumer($config);
if (!$this->_getParam("denied")) {
if (!empty($_GET) && isset($_SESSION['TWITTER_REQUEST_TOKEN'])) {
$token = $consumer->getAccessToken($_GET, unserialize($_SESSION['TWITTER_REQUEST_TOKEN']));
} else {
// Mistaken request? Some malfeasant trying something?
exit('Invalid callback request. Oops. Sorry.');
}
// save token to file
// file_put_contents('token.txt', serialize($token));
$client = $token->getHttpClient($config);
$client->setUri('https://api.twitter.com/1/statuses/user_timeline.json?');
$client->setMethod(Zend_Http_Client::GET);
$client->setParameterGet('name');
$client->setParameterGet('profile_image_url');
$response = $client->request();
$tweets = json_decode($response->getBody());
$session = new Zend_Session_Namespace("userIdentity");
Zend_Session::rememberMe(63072000); //2years
$session->tw_id = $tweets[0]->user->id;
$session->tw_name = $tweets[0]->user->name;
$session->tw_image = $tweets[0]->user->profile_image_url;
if ($session->tw_id != "") {
$tw_id = $session->tw_id;
//Calling the function twitterAuthAction for email authentication
$twAuthArr = $this->twitterAuthAction($tw_id);
if ($twAuthArr['socialId'] == $tw_id) {
$session->userId = $twAuthArr['id'];
$session->email = $twAuthArr['emailId'];
$this->_redirect('/profile/showprofile');
} else {
$user = new UserRegistration();
$firstname = "";
$lastname = "";
$password = "";
$socialtype = "twitter";
$email = "";
$socialid = $session->tw_id;
$result = $user->registerUser($firstname, $lastname, $socialid, $socialtype, $email, $password);
$session->userId = $result;
$this->_redirect('/register');
}
}
$this->_redirect("/register");
} else {
$this->_redirect("/register");
}
}
My Questions are :
1) Why its not providing user array if there is no any tweet in my twitter account (or newly created twitter account)
2) I want user profile details from twitter account. How can I get it?
Need Help. Thanks
I think as per david's answer you need to use users/show url there instead of using statuses/user_timeline. You can use curl for requesting url so you'll get the response which contains the users information.
Try with following code:
$user_id = $client->getToken()->getParam('user_id');
$trends_url = "http://api.twitter.com/1/users/show.json?user_id=".$user_id;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $trends_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$curlout = curl_exec($ch);
curl_close($ch);
$response = json_decode($curlout, true);
$session = new Zend_Session_Namespace("userIdentity");
Zend_Session::rememberMe(63072000); //2years
$session->tw_id = $response['id'];
$session->tw_name = $response['name'];
$session->tw_image = $response['profile_image_url'];
Try this. Hope it will help you.
I think you are misreading the Twitter API docs for the statuses/user_timeline endpoint.
The field user that you identify is one of the fields within a returned tweet. If the user id to which you point has no tweets, then there will be no entries in the returned array, hence no user field.
If you need the user information even in the absence of any tweets, then you probably need to hit the users/show endpoint.