BTCPay Server intergration using Greenfield API / php - php

So I am trying to integrate btcpayserver into my site. I am fairly new to php so bare with me but I have everything working until after the invoice is created. Whenever user clicks to pay with bitcoin, it successfully creates new invoice but doesn't redirect to the checkout link afterwards.
I should mention i am using the following to help with integration process https://github.com/btcpayserver/btcpayserver-greenfield-php
Here is my create_invoice.php
session_start();
// Include autoload file.
require __DIR__ . '/../vendor/autoload.php';
// Import Invoice client class.
use BTCPayServer\Client\Invoice;
use BTCPayServer\Client\InvoiceCheckoutOptions;
use BTCPayServer\Util\PreciseNumber;
// Fill in with your BTCPay Server data.
$apiKey = 'aaaaaaaaaa';
$host = 'https://aa.demo.btcpayserver.org/';
$storeId = 'aaaaaa';
$amount = $_POST['amount'];
$currency = 'USD';
$orderId = $_SESSION['name']."#" . mt_rand(0, 1000);
$buyerEmail = $_SESSION['name'];
try {
$client = new Invoice($host, $apiKey);
var_dump(
$client->createInvoice(
$storeId,
$currency,
PreciseNumber::parseString($amount),
$orderId,
$buyerEmail
)
);
} catch (\Throwable $e) {
echo "Error: " . $e->getMessage();
}
Whenever the form is submitted the following is shown (i replaced the sensitive information)
object(BTCPayServer\Result\Invoice)#6 (1)
{
["data":"BTCPayServer\Result\AbstractResult":private] => array(16)
{
["id"]=> string(22) "aaaaaaaaaaa"
["storeId"]=> string(44) "ssssssssssssssssssssssssssss"
["amount"]=> string(4) "18.0"
["checkoutLink"]=> string(62) "https://demo.aa.btcpayserver.org/i/aaaaaaaaaaaaaa"
["status"]=> string(3) "New"
["additionalStatus"]=> string(4) "None"
["monitoringExpiration"]=> int(1669087659)
["expirationTime"]=> int(1669080459)
["createdTime"]=> int(1669078659)
["availableStatusesForManualMarking"]=> array(2)
{
[0]=> string(7) "Settled"
[1]=> string(7) "Invalid"
}
["archived"]=> bool(false)
["type"]=> string(8) "Standard"
["currency"]=> string(3) "USD"
["metadata"]=> array(1)
{
["orderId"]=> string(4) "#501"
}
["checkout"]=> array(10) {
["speedPolicy"]=> string(9) "HighSpeed"
["paymentMethods"]=> array(1)
{
[0]=> string(3) "BTC"
}
["defaultPaymentMethod"]=> NULL
["expirationMinutes"]=> int(30)
["monitoringMinutes"]=> int(120)
["paymentTolerance"]=> float(0)
["requiresRefundEmail"]=> NULL
["defaultLanguage"]=> NULL
}
["receipt"]=> array(3)
{
["enabled"]=> NULL
["showQR"]=> NULL
["showPayments"]=> NULL
}
}
}
Now my issue is I need to redirect to "checkoutLink" after invoice is created.
UPDATE*
Following code displays error "Error: Cannot access offset of type string on string"
if ($response->getStatus() === 200) {
$data1 = $response->getBody();
$link1 = $data1["checkoutLink"];
echo $link1;
} else {
throw $this->getExceptionByStatusCode($method, $url, $response);
}

Related

How to access XML response

Good day, I want to access the XML response and echo it to display its value but I don't know how to do it. I already tried some few answers in StackOverflow but I fail.
This is my code.
<?php
error_reporting(E_ALL);
require_once 'ruFunctions.php';
$rentalsUnited = new rentalsUnited();
$ru= $rentalsUnited->getOwners();
if($ru != null){
$data= simplexml_load_string($ru);
var_dump($data); // it will return boof(false)
var_dump($ru);
echo $data->Pull_ListAllOwners_RS->Status['ID']; //Trying to get property of non-object
}
?>
Results for var_dump($ru);
object(SimpleXMLElement)#2 (3) {
["Status"]=>
string(7) "Success"
["ResponseID"]=>
string(32) "44065d9888304e8cba912bce4d131ab1"
["Owners"]=>
object(SimpleXMLElement)#3 (1) {
["Owner"]=>
object(SimpleXMLElement)#4 (7) {
["#attributes"]=>
array(1) {
["OwnerID"]=>
string(6) "429335"
}
["FirstName"]=>
string(5) "Test"
["SurName"]=>
string(7) "Tester"
["CompanyName"]=>
string(15) "Test Helpers"
["Email"]=>
string(23) "info#Test.com"
["Phone"]=>
string(12) "+13474707707"
["UserAccountId"]=>
string(3) "602"
}
}
}
It looks like $ru is already a SimpleXMLElement, so trying to call simplexml_load_string will fail on this.
You can see some of the details by
if($ru != null){
echo $ru->Status;
}
You can (probably) list the owners by...
if($ru != null){
foreach ($ru->Owners->Owner as $owner ) {
echo "ownerId=".$owner['OwnerID'].PHP_EOL;
echo "FirstName=".$owner->FirstName.PHP_EOL;
}
}

400{"name":"MALFORMED_REQUEST_ERROR","message":"Json request malformed

This is my connection to the database plus $apiContext
// Bootstrap and Configure
define('DB_HOST', '*');
define('DB_USERNAME', '*');
define('DB_PASSWORD', '');
define('DB_NAME', '*');
//get connection
$mysqli = new mysqli(DB_HOST, DB_USERNAME, DB_PASSWORD, DB_NAME);
include __DIR__ . '/autoload.php';
error_reporting(E_ALL);
ini_set('display_errors', '1');
use PayPal\Rest\ApiContext;
use PayPal\Auth\OAuthTokenCredential;
// Replace these values by entering your own ClientId and Secret by visiting https://developer.paypal.com/webapps/developer/applications/myapps
$clientId = '*';
$clientSecret = '*';
$apiContext = new ApiContext(
new OAuthTokenCredential(
$clientId,
$clientSecret
)
);
$apiContext->setConfig(
array(
'mode' => 'sandbox',
'log.LogEnabled' == true,
'log.FileName' == 'PayPal.log',
'log.LogLevel' == 'DEBUG', // PLEASE USE `INFO` LEVEL FOR LOGGING IN LIVE ENVIRONMENTS
'cache.enabled' == true,
)
);
This is how am creating batch payouts and testing from the sandbox.
if(!$mysqli){
die("Connection failed: " . $mysqli->error);
}
$query = "SELECT * FROM payments WHERE Channel ='paypal' AND status='2' ORDER BY created_at desc LIMIT 500";
//execute query
$result = $mysqli->query($query);
// # Create Bulk Payout
use PayPal\Api\Payout;
use PayPal\Api\Currency;
use PayPal\Api\PayoutItem;
use PayPal\Api\PayoutSenderBatchHeader;
// Create a new instance of Payout object
$payouts = new \PayPal\Api\Payout();
$senderBatchHeader = new \PayPal\Api\PayoutSenderBatchHeader();
$senderBatchHeader->setSenderBatchId(uniqid())
->setEmailSubject("You Have a new Payment");
$payouts->setSenderBatchHeader($senderBatchHeader);
// #### Sender Item
$i = 0;
while($row = mysqli_fetch_assoc($result)){
$senderItem[$i] = new \PayPal\Api\PayoutItem();
$senderItem[$i]->setRecipientType('Email')
->setReceiver($row['them_email'])
->setAmount(new \PayPal\Api\Currency("{ \"value\":\"{$row['tasker_amount']}\", \"currency\":\"USD\" }"))
->setSenderItemId($row['created_at'])
->setNote($row['pay_type']);
$i++;
$payouts->addItem($senderItem);
};
var_dump($senderItem);
// ### Create Payout
try {
$payouts->create(null, $apiContext);
} catch (PayPal\Exception\PayPalConnectionException $ex) {
echo $ex->getCode(); // Prints the Error Code
echo $ex->getData(); // Prints the detailed error message
die($ex);
} catch (Exception $ex) {
die($ex);
}
This is the error code plus the exceptions
400{"name":"MALFORMED_REQUEST_ERROR","message":"Json request malformed.","debug_id":"15e4b40545d51","information_link":"https://developer.paypal.com/docs/api/payments.payouts-batch/#errors"}
PayPal\Exception\PayPalConnectionException: Got Http response code 400 when accessing https://api.sandbox.paypal.com/v1/payments/payouts?. in /Applications/XAMPP/xamppfiles/htdocs/Paypal-PHP-SDK/paypal/rest-api-sdk-php/lib/PayPal/Core/PayPalHttpConnection.php:202 Stack trace:
#0 /Applications/XAMPP/xamppfiles/htdocs/Paypal-PHP-SDK/paypal/rest-api-sdk-php/lib/PayPal/Transport/PayPalRestCall.php(73): PayPal\Core\PayPalHttpConnection->execute('{"sender_batch_...')
#1 /Applications/XAMPP/xamppfiles/htdocs/Paypal-PHP-SDK/paypal/rest-api-sdk-php/lib/PayPal/Common/PayPalResourceModel.php(104): PayPal\Transport\PayPalRestCall->execute(Array, '/v1/payments/pa...', 'POST', '{"sender_batch_...', Array) #2 /Applications/XAMPP/xamppfiles/htdocs/Paypal-PHP-SDK/paypal/rest-api-sdk-php/lib/PayPal/Api/Payout.php(121): PayPal\Common\PayPalResourceModel::executeCall('/v1/payments/pa...', 'POST', '{"sender_batch_...', NULL, Object(PayPal\Rest\ApiContext), Object(PayPal\Transport\PayPalRestCall))
#3 /Applications/XAMPP/xamppfiles/htdocs/Paypal-PHP-SDK/wunipayout.php(45): PayPal\Api\Payout->create(Array, Object(PayPal\Rest\ApiContext)) #4 {main}
This is the output from var_dump($senderItem)
array(43)
{
[0]=> object(PayPal\Api\PayoutItem)#10 (1)
{
["_propMap":"PayPal\Common\PayPalModel":private]=> array(5)
{
["recipient_type"]=> string(5) "Email"
["receiver"]=> string(14) "jill#gmail.com"
["amount"]=> object(PayPal\Api\Currency)#11 (1)
{
["_propMap":"PayPal\Common\PayPalModel":private]=> array(2)
{
["value"]=> string(5) "12580"
["currency"]=> string(3) "USD"
}
}
["sender_item_id"]=> string(19) "2017-03-11 20:02:40"
["note"]=> string(7) "TASK_ME"
}
}
[1]=> object(PayPal\Api\PayoutItem)#12 (1)
{
["_propMap":"PayPal\Common\PayPalModel":private]=> array(5)
{
["recipient_type"]=> string(5) "Email"
["receiver"]=> string(12) "me#gmail.com"
["amount"]=> object(PayPal\Api\Currency)#13 (1)
{
["_propMap":"PayPal\Common\PayPalModel":private]=> array(2)
{
["value"]=> string(4) "1000"
["currency"]=> string(3) "USD"
}
}
["sender_item_id"]=> string(19) "2017-03-09 21:41:49"
["note"]=> string(4) "TASK"
}
}
[2]=> object(PayPal\Api\PayoutItem)#14 (1)
{
["_propMap":"PayPal\Common\PayPalModel":private]=> array(5)
{
["recipient_type"]=> string(5) "Email"
["receiver"]=> string(12) "me#gmail.com"
["amount"]=> object(PayPal\Api\Currency)#15 (1)
{
["_propMap":"PayPal\Common\PayPalModel":private]=> array(2)
{
["value"]=> string(4) "1288"
["currency"]=> string(3) "USD"
}
}
["sender_item_id"]=> string(19) "2017-03-06 18:04:47"
["note"]=> string(4) "TASK"
}
}
[3]=> object(PayPal\Api\PayoutItem)#16 (1)
{
["_propMap":"PayPal\Common\PayPalModel":private]=> array(5)
{
["recipient_type"]=> string(5) "Email"
["receiver"]=> string(13) "tex#gmail.com"
["amount"]=> object(PayPal\Api\Currency)#17 (1)
{
["_propMap":"PayPal\Common\PayPalModel":private]=> array(2)
{
["value"]=> string(1) "3"
["currency"]=> string(3) "USD"
}
}
["sender_item_id"]=> string(19) "2017-03-05 22:41:56"
["note"]=> string(7) "PROJECT"
}
}
}
Help me figure out why am getting this error am new to the PayPal Payouts API.
You should not be forming your own JSON string and passing it.
Instead, create an object using stdClass and assign properties and values to it. Then, use json_encode to pass to PayPal.
For example (excerpt, untested):
// Create empty object
$payAmount = new stdClass;
// Assign object attributes
$payAmount->value = $row['tasker_amount'];
$payAmount->currency = "USD";
// Create currency object
$currency = new \PayPal\Api\Currency(
json_encode($payAmount)
);
$senderItem[$i]->setRecipientType('Email')
->setReceiver($row['email'])
->setAmount($currency)
->setSenderItemId($row['created_at'])
->setNote($row['pay_type']);
I believe the issue comes from when you're calling the addItem method. This may solve your problem (use this entire loop). This also uses the modifications above:
while($row = mysqli_fetch_assoc($result)) {
// Create empty object
$payAmount = new stdClass;
// Assign object attributes
$payAmount->value = $row['tasker_amount'];
$payAmount->currency = "USD";
// Create currency object
$currency = new \PayPal\Api\Currency(
json_encode($payAmount)
);
$senderItem = new \PayPal\Api\PayoutItem();
$senderItem->setRecipientType('Email')
->setReceiver($row['them_email'])
->setAmount($currency)
->setSenderItemId($row['created_at'])
->setNote($row['pay_type']);
$payouts->addItem($senderItem);
};
Notice that I dropped $i, as it's useless in this case. You are appending the item in each iteration, so counting the item doesn't matter.
One last edit I could throw in here... Instead of creating a stdClass and json_encodeing it, you could use the methods that the Currency class has in the Paypal SDK:
while($row = mysqli_fetch_assoc($result)) {
$amount = new \PayPal\Api\Currency();
$amount->setCurrency("USD");
$amount->setValue((float)$row['tasker_amount']); // float values only
$senderItem = new \PayPal\Api\PayoutItem();
$senderItem->setRecipientType('Email')
->setReceiver($row['them_email'])
->setAmount($amount)
->setSenderItemId($row['created_at'])
->setNote($row['pay_type']);
$payouts->addItem($senderItem);
};

simplexml_load_string() giving errors because SOAP response is being passed as < instead of <

Hey guys I'm trying to create a simple web service whereby the user enters the price in a text box then the database is queried and returns the names of dresses which corresponds to the price but I'm getting an error when I'm trying to pass the soap response in the simplexml_load_string();. This is the snapshot of the errors I'm getting:
Here's my codes for the client.php:
<?php
if(isset($_POST['search_input']))
{
try
{
$input = $_POST['search_input'];
$wsdl = "http://localhost/WebService/UDDI/90210Store.wsdl";
//$options = array('cache_wsdl'=>WSDL_CACHE_NONE, 'features'=>SOAP_SINGLE_ELEMENT_ARRAYS);
//$client = new SoapClient($wsdl, $options);
$debugOption = array('trace'=>true, 'cache_wsdl'=>WSDL_CACHE_NONE, 'features'=>SOAP_SINGLE_ELEMENT_ARRAYS);
$client = new SoapClient($wsdl, $debugOption);
$response = $client->viewDressPerPrice($input);
$soaprequest = "<strong>REQUEST:</strong><br/>" . htmlspecialchars($client->__getLastRequest()) . "<br/>";
$soapresponse = htmlspecialchars($client->__getLastResponse());
echo $soapresponse;
if(isset($response->DressPerPrice))
{
$XMLDocument = simplexml_load_string($soapresponse); //this part giving errors
$XSLDocument = new DOMDocument();
$XSLDocument->load("WSEx1.xsl");
$XSLProcessor = new XSLTProcessor();//PHP5
$XSLProcessor->importStylesheet($XSLDocument);
echo $XSLProcessor->transformToXML($XMLDocument);
}
else
{
echo "This field is not found in database";
}
}
catch(Exception $e)
{
echo 'Exception: '.$e->getMessage();
}
catch(SOAPFault $exception)
{
echo 'SOAP Exception: '.$exception->getMessage();
}
}
else
{
header("Location: http://localhost/WebService/Client/Category.html");
}
?>
var_dump($response); result:
object(stdClass)#2 (1) { ["DressPerPrice"]=> array(5) { [0]=>
object(stdClass)#3 (3) { ["Name"]=> string(7) "Dress 2" ["Price"]=>
int(20) ["Image"]=> string(24) "" } 1=> object(stdClass)#4 (3) {
["Name"]=> string(7) "Dress 9" ["Price"]=> int(20) ["Image"]=>
string(6) "3.jpeg" } [2]=> object(stdClass)#5 (3) { ["Name"]=>
string(8) "Dress 10" ["Price"]=> int(20) ["Image"]=> string(19)
"0905C58A0179_1.jpeg" } [3]=> object(stdClass)#6 (3) { ["Name"]=>
string(8) "Dress 11" ["Price"]=> int(20) ["Image"]=> string(19)
"0905C58A0179_1.jpeg" } [4]=> object(stdClass)#7 (3) { ["Name"]=>
string(8) "Dress 12" ["Price"]=> int(20) ["Image"]=> string(19)
"0905C58A0179_1.jpeg" } } }
Dress
220<img
src="2.jpeg"></img>Dress
9203.jpegDress
10200905C58A0179_1.jpegDress
11200905C58A0179_1.jpegDress
12200905C58A0179_1.jpeg
Any way that I can fix this?
Your help will be much appreciated. Thanks.

Unable to read or post to friends wall (news feed)

I have been trying to read a friends news feed to check if my message is there (does not matter if the message is visible, hidden or deleted) and if the message is there, not to post a new message. If it is not there than post a message. The code is below with a lot of unnecessary code to trace where the problem was coming from. I have my permission set for 'publish_stream, read_stream'.
I tried all the code in the other blogs but non seemed to work I do not know whether it is because I am using PHP SDK 3.0 - latest version. My App is iframe app. Even bought an expensive book (too expensive) on Facebook Applications but found out, after buying, that it was out of date!
The code works well if I am using /me or my user id but not my friend's id.
require 'config.php';
require 'facebook.php';
//Create facebook application instance.
$facebook = new Facebook(array(
'appId' => $fb_app_id,
'secret' => $fb_secret
));
$sent = false;
$userData = null;
$PPnotposted = true;
$me = null;
$test_friends =1;
$user = $facebook->getUser();
// Login or logout url will be needed depending on current user state.
if ($user) {
$logoutUrl = $facebook->getLogoutUrl(array("next"=> "<? echo $fb_app_url ?>" ));
} else {
$loginUrl = $facebook->getLoginUrl( array( 'scope'=> 'publish_stream, read_stream', 'redirect_uri' => $fb_app_url));
}
$get_someone_else = 100000xxxxxxxxx; // I used a real user id but covered it up here so
my friend's id hidden for this stackexchange help
if ($user) {
try {
// Proceed knowing you have a logged in user who's authenticated.
if ( $get_someone_else ){
$user_profile = $facebook->api("/".$get_someone_else);
echo "<br/> ********************user is ".$get_someone_else." ******************<br/>";
var_dump( $user_profile );
echo "<br/> ********************** end of user info ******************<br/>";
} else {
$user_profile = $facebook->api('/me');
}
} catch (FacebookApiException $e) {
}
// print_r( $user_profile );
$PPaccesstoken = $facebook->getAccessToken();
$attachment[access_token]= $PPaccesstoken ;
//post message to wall if it is sent through form
if(isset($_POST['PPmessage'])){
try {
if( $get_someone_else ){
$ppmy_news = $facebook->api("/.$get_someone_else./feed?limit=300"); //Get 300 messages to examine
echo "<br/> *********************** news feed is ".$ppmy_news." ******************<br/>";
var_dump( $ppmy_news );
echo "<br/> ******************** end of user info ********************<br/>";
} else {
$ppmy_news = $facebook->api('/me/feed?limit=300'); //Get 300 messages
//to examine. Initially I set it to
// 10 messages for testing purposes.
}
// var_dump( $ppmy_news);
// $sent = $facebook->api("/".$user."/feed", 'POST', $attachment );
$ppmy_view_lp=0;
if( $test_friends ) { //Debugging flag to activate or deactivate parts of code
echo "sent is :<br />";
// var_dump( $sent );
echo "<br />";
$friends = $facebook->api('/me/friends');
echo "friends is :<br />";
// var_dump( $friends );
echo "<br />";
$friendsLists = $facebook->api('/me/friends');
$total_friends = 0;
foreach ($friendsLists as $friends) {
foreach ($friends as $friend) {
$id = $friend['id'];
$name = $friend['name'];
$total_friends++; //Get total number of friends
echo "friend : ".$name." id is: ".$id." Total friends is : ".$total_friends." <br/> ";
}
}
}
} catch (FacebookApiException $e) {
echo "<br/> !!!!!!!!!!!! Error Dump Line 85 !!!!!!!!!!!!! <br/>";
var_dump( $e );
echo "<br/> !!!!!!!!!!!! End of Error Dump !!!!!!!!!!!!! <br/>";
//do something about it
}
}
}
But I find I am denied permission and the catch dump is:
!!!!!!!!!!!! Error Dump Line 85 !!!!!!!!!!!!!
object(FacebookApiException)#2 (7) { ["result:protected"]=> array(1) { ["error"]=> array(3) { ["message"]=> string(72) "(#803) Some of the aliases you requested do not exist: .100000xxxxxxxxx." ["type"]=> string(14) "OAuthException" ["code"]=> int(803) } } ["message:protected"]=> string(72) "(#803) Some of the aliases you requested do not exist: .100000xxxxxxxxx." ["string:private"]=> string(0) "" ["code:protected"]=> int(0) ["file:protected"]=> string(48) "/home/www/drpetersnews.com/vmt/base_facebook.php" ["line:protected"]=> int(1106) ["trace:private"]=> array(4) { [0]=> array(6) { ["file"]=> string(48) "/home/www/drpetersnews.com/vmt/base_facebook.php" ["line"]=> int(810) ["function"]=> string(17) "throwAPIException" ["class"]=> string(12) "BaseFacebook" ["type"]=> string(2) "->" ["args"]=> array(1) { [0]=> array(1) { ["error"]=> array(3) { ["message"]=> string(72) "(#803) Some of the aliases you requested do not exist: .100000xxxxxxxxx." ["type"]=> string(14) "OAuthException" ["code"]=> int(803) } } } } [1]=> array(4) { ["function"]=> string(6) "_graph" ["class"]=> string(12) "BaseFacebook" ["type"]=> string(2) "->" ["args"]=> array(1) { [0]=> string(32) "/.100000xxxxxxxxx./feed?limit=10" } } [2]=> array(4) { ["file"]=> string(48) "/home/www/drpetersnews.com/vmt/base_facebook.php" ["line"]=> int(587) ["function"]=> string(20) "call_user_func_array" ["args"]=> array(2) { [0]=> array(2) { [0]=> &object(Facebook)#1 (7) { ["appId:protected"]=> string(15) "368XXXXXXXXXX09" ["appSecret:protected"]=> string(32) "eb4216aXXXXXXXXXXXXXXXXXXXXXfe21" ["user:protected"]=> string(15) "1000000yyyyyyyy" ["signedRequest:protected"]=> NULL ["state:protected"]=> NULL ["accessToken:protected"]=> string(119) "AAAFO5a2SKXkBAAXYgZBdPfTbJKQ3XpBgZBQmU2QcXOx7eo18hB5Hox41J7Of7SMZCj7ZCchJrM1ZCN2KLoAoqCmQWUrjwhDJlMQca005w5kgJIrMQ6ZCdM" ["fileUploadSupport:protected"]=> bool(false) } [1]=> string(6) "_graph" } [1]=> array(1) { [0]=> string(32) "/.100000xxxxxxxxx./feed?limit=10" } } } [3]=> array(6) { ["file"]=> string(40) "/home/www/drpetersnews.com/vmt/index.php" ["line"]=> int(54) ["function"]=> string(3) "api" ["class"]=> string(12) "BaseFacebook" ["type"]=> string(2) "->" ["args"]=> array(1) { [0]=> string(32) "/.100000xxxxxxxxx./feed?limit=10" } } } }
!!!!!!!!!!!! End of Error Dump !!!!!!!!!!!!!
Please do help me out and let me know if I have set the permissions wrongly and how to do it properly.
The code is correct, but the problem could lie with Facebook's Privacy Settings. If you can't see the posts on the user's wall, it means that the user has set privacy settings preventing you from seeing the posts.
Use the Graph API Explorer tool (https://developers.facebook.com/tools/explorer/) and see if you can see the user's feed using it. Check a number of friend IDs to see if any of them return data.

Amazon ItemSearch Request is "Valid" but No Results Returned using PHP SoapClient

I posted this in the Amazon Product Advertising forum but noone is responding, so maybe someone here can help me out.
I'm trying to get a few items to display based on a keyword, so far I have this code and when it runs it says that the request is valid but there are no items returned, I'm trying to use the PHP SoapClient. Can someone please point out what I'm doing wrong?
Here is my code:
<?php
define("ACCESS_KEY",'###');
define("SECRET_KEY",'###');
define("ASSOCIATE_TAG",'###');
$timeStamp = gmdate("Y-m-d\TH:i:s\Z");
$function = "ItemSearch";
$string = $function.$timeStamp;
$signature = base64_encode(hash_hmac("sha256", $string, SECRET_KEY, True));
$client = new SoapClient('http://webservices.amazon.com/AWSECommerceService/AWSECommerceService.wsdl');
//var_dump($client->__getFunctions());
$params = array(
"Operation"=>$function,
"AssociateTag"=>ASSOCIATE_TAG,
"Request"=>array("Keywords"=>"book","ResponseGroup"=>"Medium")
);
$header_arr = array();
$header_arr[] = new SoapHeader( 'http://security.amazonaws.com/doc/2007-01-01/', 'AWSAccessKeyId', ACCESS_KEY );
$header_arr[] = new SoapHeader( 'http://security.amazonaws.com/doc/2007-01-01/', 'Timestamp', $timeStamp );
$header_arr[] = new SoapHeader( 'http://security.amazonaws.com/doc/2007-01-01/', 'Signature', $signature );
$client->__setSoapHeaders($header_arr);
$result=$client->__soapCall($function, array($params));
var_dump($result);
?>
And here is the response I get for the keyword book:
object(stdClass)#5 (2) {
["OperationRequest"]=>
object(stdClass)#6 (4) {
["HTTPHeaders"]=>
object(stdClass)#7 (1) {
["Header"]=>
object(stdClass)#8 (2) {
["Name"]=>
string(9) "UserAgent"
["Value"]=>
string(26) "PHP-SOAP/5.3.6-13ubuntu3.3"
}
}
["RequestId"]=>
string(36) "###"
["Arguments"]=>
object(stdClass)#9 (1) {
["Argument"]=>
object(stdClass)#10 (2) {
["Name"]=>
string(7) "Service"
["Value"]=>
string(19) "AWSECommerceService"
}
}
["RequestProcessingTime"]=>
float(0.085933)
}
["Items"]=>
object(stdClass)#11 (1) {
["Request"]=>
object(stdClass)#12 (2) {
["IsValid"]=>
string(4) "True"
["ItemSearchRequest"]=>
object(stdClass)#13 (2) {
["Keywords"]=>
string(4) "book"
["ResponseGroup"]=>
string(6) "Medium"
}
}
}
}
As you can see there is no actual items in the response. From the documentation it seems there should be some sort of TotalResults attribute in the response so I'm absolutely confused why I'm getting something completely different.
So apparently the problem was that you must specify a SearchIndex it doesn't just default to All, or even tell you that it is required it simply doesn't return any results.
So above replace request with:
$params = array(
"Operation"=>$function,
"AssociateTag"=>ASSOCIATE_TAG,
"Request"=>array("SearchIndex"=>"All","Keywords"=>"book","ResponseGroup"=>"Small")
);

Categories