Reputation: 1
I would like to post array for api via PHP. I have used oAuth 1.0 for this, but how can I POST JSON body array using oAuth.
<? php
//code start
try
{
$postData = array(
'ProductID' => $productID,
'InventoryType' => $InventoryType,
'ProductCostPrice' => $productCost
);
$postData = json_encode($postData);
$oauth = new OAuth($this->consumer_key, $this->consumer_secret);
$oauth->enableDebug(); // simple debug flag for checking error messages
$oauth->disableSSLChecks(); // avoids an SSL issue when testing
$oauth->setToken($this->access_token, $this->token_secret);
## POST JSON body array ##
$oauth->setBody('body',$postData);
##
$url = $this->product_update_url.$productID;
$oauth->fetch($url, OAUTH_AUTH_TYPE_FORM);
$response_info = $oauth->getLastResponseInfo();
header("Content-Type: {$response_info["content_type"]}");
$dataList = (array) json_decode($oauth->getLastResponse());
echo "<pre>";
print_r($dataList);
echo "</pre>";
exit;
} catch(OAuthException $E) {
Mage::log('error', null, 'error.log');
}
==================
URL: http://php.net/manual/en/class.oauth.php
Please can you help, that how can I POST json body array using oAuth.
Upvotes: 0
Views: 911
Reputation: 921
The way request parameters are normalized in the OAuth1 spec means you should only sign the body if it's in a form url-encoded format (ie param1=value1¶m2=value2
or arr[]=val1&arr[]=val2
)
This is due to the way OAuth1 calculates a request signature which includes sorting the parameters by name alphabetically.
In your example above- if possible- you should try and form url-encode the array of data instead.
$postData = array(
'ProductID' => $productID,
'InventoryType' => $InventoryType,
'ProductCostPrice' => $productCost
);
// "ProductID=1&InventoryType=widget&ProductCostPrice=3.5"
$body = http_build_query($postData);
...
$oauth->setBody('body', $body);
If for whatever reason that's not possible you'll need to ensure the request body isn't used in your signature calculation when decoding the request.
If you're using HTTPS for your API (which you should) you should be alright with a request body that isn't verifiable in the signature. If you allow HTTP requests to your API you should have some mechanism for confirming the request body was not altered.
A method I've seen is to hash the JSON body string and then include that hash as a query parameter in the request (so it is included in the signature calculation). Then as part of the API's decoding process you'd confirm the JSON body hashes to the signed query value.
This question is a bit old, but I found it via a google search so I thought it best to leave an answer for future searchers.
Upvotes: 1