What kind of API response does this script produce? - php

I am experimenting with differnt API's of websites right now because I am building my own API for site, On bebo.com through there API they have a php cient which passes a key and secret that the owner of the app has. you then have a client library with a bunch of methods/functions you can call, all of the methods work like this:
public function score_getHigh($uid='', $name='') {
return $this->execute('score.getHigh', array('member_id' => $uid, 'name' => $name));
}
You can see they all just pass in a name of a function and put the params into an array and pass it through the execute(METHOD-NAME, METHOD PARAMS) function. This function then runs code like this
//execute function
//flatten array
foreach ($params as $k => $v) {
if (is_array($v)) {
$params[$k] = implode(',', $v);
}
}
To make a list of all the functions and params to run, it then POST or GET this to the API page with CURL and this is the result that comes back below in my browser if I visit the page myself in a browser instead of letting curl post it then I view the page source of the web browser it shows this array just how I posted it in the browser,
Array
(
[error_code] => 102
[error_msg] => Session key invalid or no longer valid
[request_args] => Array
(
[0] => Array
(
[key] => v
[value] => 1.0
)
[1] => Array
(
[key] => api_key
[value] => Qnw1Moc22Y9m3XY5zUZohbxiwfkURaPJpN3m
)
[2] => Array
(
[key] => method
[value] => friends.get
)
[3] => Array
(
[key] => call_id
[value] => 1262417906.33
)
[4] => Array
(
[key] => sig
[value] => 18b8592f383a5f0abc332745284a0e99
)
)
)
So finally the question here, What kind of response is this, it's not JSON and I don't think it is XML, what would this be called and the script that is trying to get this result with CURL, how can it process this back into something to work with?

From your PHP script, you should be able to do something like this:
$foo = $bebo->score_getHigh(...);
echo $foo['error_code']; // Should output 102 in this case
The response that you posted looks like the output of PHP's serialize function. That would make sense if you use Bebo's PHP client to make a request and then printed the resulting object. Bebo's service is actually returning XML to you when you make your request, as demonstrated by the example below.
$ curl http://apps.bebo.com/restserver.php?\
v=1.0&api_key=Qnw1Moc22Y9m3XY5zUZohbxiwfkURaPJpN3m\
&method=friends.get&call_id=1262417906.33&\
sig=18b8592f383a5f0abc332745284a0e99
<error_response>
<error_code>102</error_code>
<error_msg>Session key invalid or no longer valid</error_msg>
<request_args list="true">
<arg>
<key>v</key>
<value>1.0</value>
</arg>
<arg>
<key>api_key</key>
<value>Qnw1Moc22Y9m3XY5zUZohbxiwfkURaPJpN3m</value>
</arg>
<arg>
<key>method</key>
<value>friends.get</value>
</arg>
<arg>
<key>call_id</key>
<value>1262417906.33</value>
</arg>
<arg>
<key>sig</key>
<value>18b8592f383a5f0abc332745284a0e99</value>
</arg>
</request_args>
</error_response>

Related

How to interpret results of FedEx API tracking request

I need to do some basic Fedex package tracking. I'm using Jeremy Dunn's php-fedex-api-wrapper. My FedEx developer credentials are setup and I am able to authenticate via the FedEx api.
The problem: when I run a basic track request using the api-wrapper code I get back a result that I am unsure how to interpret. It looks like a structure that I should have no trouble parsing but I cannot.
Here are the first few lines of the result code that I see when I var_dump($trackReply)
object(FedEx\TrackService\ComplexType\TrackReply)#66 (2) {
["name":protected]=>
string(10) "TrackReply"
["values":protected]=>
array(4) {
If I cast the result as an array and print_r it looks like this (truncated version):
Array
(
[0] => FedEx\TrackService\ComplexType\TrackReply Object
(
[name:protected] => TrackReply
[values:protected] => Array
(
[HighestSeverity] => SUCCESS
[Notifications] => Array
(
[0] => FedEx\TrackService\ComplexType\Notification Object
(
[name:protected] => Notification
[values:protected] => Array
(
[Severity] => SUCCESS
[Source] => trck
[Code] => 0
[Message] => Request was successfully processed.
[LocalizedMessage] => Request was successfully
processed.
)
)
)
The $trackResult is obviously an object, but I cannot figure out how to access its specific properties. When it is cast as an array, element zero is clearly an object, so I would think I could access the object properties with
I tried $test = $trackResult[0];// which should now be an object, right?
and then
I looked at this StackOverflow post and it seems to be relevant: Convert a PHP object to an associative array
So I tried one of the solutions from the link above:
$array = json_decode(json_encode($nested_object), true);
But, when I print_r($array) I get essentially an empty array like this:
Array
(
)

Parsing a timestamp based PHP std class obkect

I have a PHP standard class object converted from json_decode of a REST call on an API which looks like :
Array
(
[1437688713] => stdClass Object
(
[handle] => Keep it logically awesome.
[id] => 377748
[ping] => stdClass Object
(
[url] => https://api.me.com
[id] => 377748
[name] => web
[active] => 1
[events] => Array
(
[0] => data_new
[1] => data_old
)
So far i had no issues in parsing any of the PHP objects. However this one is failing because i can not access the nested object elements using a key since 1437688713 is not assigned to a key and accessing an object is failing if i try to do this:
$object->1437688713->handle
Is there a way to access these elements ?
Update: one more thing, i would never know this value (1437688713) in advance. Just like a key. All i get is a stdclass object which i have to parse.
The outer part of your data is an array, not an object. Try:
$array['1437688713']->handle;
or if you don't know the key, you can iterate over the array (handy if it may contain multiple objects too):
foreach ($array as $key => $object) {
echo $key; // outputs: 1437688713
echo $object->handle; // outputs: Keep it logically awesome.
}
Get the first item from $object array
$first_key = key($object);
Use it with your response array,
$object[$first_key]->handle;
Or, the first element of array
$first_pair = reset($object)->handle;

Calling another function in PHP with Array as Parameter passing only first element (JSON RPC)

this might be quite a dummy question. I've been searching the web and trying around alot but i just can't find a solution.
I am sending out Core Data Objects as Dictionarys within an Array to my PHP JSON RPC web service. I will not dig further into this at this point, because i know that my JSON RPC is well formed.
On PHP side i do have one RPC Server which will take the JSON data and pass it to the respective function.
$request = json_decode(file_get_contents('php://input'),true);
Using print_r i get the following result
print_r($request['params']);
(Sorry, i don't know how to include 'Array (' and the closing ')' in the box)
Array
(
[0] => Array
(
[dayId] => 7
[dayName] => Sonntag
)
[1] => Array
(
[dayId] => 6
[dayName] => Samstag
)
[2] => Array
(
[dayId] => 4
[dayName] => Donnerstag
)
[3] => Array
(
[dayId] => 2
[dayName] => Dienstag
)
[4] => Array
(
[dayId] => 1
[dayName] => Montag
)
)
As mentioned before, this array is now passed to the respective function using
$result = #call_user_func_array(array($object,$request['method']),$request['params']))
This will call method updateDaysFromClient in my implementation class.
At this point, i would like to repeat, that my JSON RPC is well formed (method, id, params).
public function updateDaysFromClient($clientDaysArray) {
print_r($clientDaysArray);
return "Update test";
}
Now comes my problem: Within my implementation, when calling the print_r on the array passed as parameter, i will only receive the first element of that array.
Array
(
[dayId] => 7
[dayName] => Sonntag
)
Can anyone explain to me why not the whole Array but only the first element is passed?
Please try to pass like this,
$result = #call_user_func_array(array($object,$request['method']),array($request['params'])))
pass $request['params'] inside another array.

Podio Auth. "Array ( [error_parameters] => Array ( ) [error_detail] => [error_propagate] =>.."

Starting out with podio API going no where fast..
<?php
define("CLIENTID", "###");
define("CLIENTSECRET", "####");
define("APPID", "###");
define("APPTOKEN", "#####");
require_once 'podio/PodioAPI.php';
Podio::setup($clientid, $clientsecret);
if (!Podio::isauthenticated())
{
try {
Podio::authenticatewithapp($appid, $apptoken);
}
catch(PodioError $e) {
die(printr($e->body));
}
}
?>
Output:
Array ( [errorparameters] => Array ( ) [errordetail] => [errorpropagate] => [request] => Array ( [url] => http://api.podio.com/oauth/token [querystring] => [method] => POST ) [errordescription] => Invalid value "" (string): must be integer [error] => invalidvalue ) 1
The issue is with
Podio::authenticatewithapp($appid, $apptoken);
Its not passing the data even though it was defined. I'm rusty coding and this is my first go with APIs.
I'm pretty sure your $appid and $apptoken are not defined, and that is why you are getting the "" string, non integer error. You could set those with the approriate values. However, since you did define the constants APPID and APPTOKEN already, you could use those as shown here:
Podio::authenticate_with_app(APPID, APPTOKEN);
(also I am not sure why you are referring to the podio methods and even print_r() without the underlines, so it should be is_authenticated(), I assume your actual code is not that way or it wouldn't work)

PayPal PHP SDK REST API Response not JSON

I get an object with nested arrays of nested objects when I make an API call. In the SDK I have the header set to accept: application/json. I am wondering why I am getting objects and arrays back?
Here is a partial part of the response:
PayPal\Api\CreditCard Object
(
[_propMap:PayPal\Common\PPModel:private] => Array
(
[type] => amex
[number] => xxxxxxxxxxx0005
[expire_month] => 5
[expire_year] => 2015
[cvv2] => 1234
[first_name] =>
[last_name] =>
[payer_id] => 3zIVtTFQ7UdKjP5mssjtzoUo6NvrsExl466oPC4Mm8nwOjI6BS
[id] => CARD-35X96613EN689504VKKCA4RA
[state] => ok
[valid_until] => 2015-06-01T00:00:00Z
[create_time] => 2013-11-13T23:41:56Z
[update_time] => 2013-11-13T23:41:56Z
[links] => Array
(
[0] => PayPal\Api\Links Object
(
[_propMap:PayPal\Common\PPModel:private] => Array
(
[href] => https://api.sandbox.paypal.com/v1/vault/credit-card/CARD-35X96613EN689504VKKCA4RA
[rel] => self
[method] => GET
)
)
[1] => PayPal\Api\Links Object
... and so on
Code that creates this
public static function get($creditCardId, $apiContext = null) {
if (($creditCardId == null) || (strlen($creditCardId) <= 0)) {
throw new \InvalidArgumentException("creditCardId cannot be null or empty");
}
$payLoad = "";
if ($apiContext == null) {
$apiContext = new ApiContext(self::$credential);
}
$call = new PPRestCall($apiContext);
print_r($call);
die;
$json = $call->execute(array('PayPal\Rest\RestHandler'), "/v1/vault/credit-card/$creditCardId", "GET", $payLoad);
$ret = new CreditCard();
$ret->fromJson($json);
return $ret;
}
Ok, so thank you Machavity for the help. The issue was that in the function that I posted above, it takes the JSON response and converts it to some wierd object thing with:
$ret->fromJson($json);
I removed that line and I now get JSON. I still wonder why having that object I intitially posted would be helpful and where it could be used. I also wonder why the SDK documentation doesn't explicitly state that the SDK does not return JSON as the final format. I feel it would save a lot of time if PayPal informed a developer that the response gets converted to an object, so we wouldn't have to search through thousands of lines of code to figure it out.
It's likely the SDK is accepting JSON on the communications layer and then running json_decode to pass you back an object you can work with. My own API system converts the response back into a PHP array.
json_decode( $call->execute(array('PayPal\Rest\RestHandler'), "/v1/vault/credit-card/$creditCardId", "GET", $payLoad) );

Categories