eBay api search item - php

I want to get items by keyword search.
<?php
error_reporting(E_ALL);
require_once("includes/config.php");
// Construct the HTTP GET call
$apicall = "https://api.ebay.com/buy/browse/v1/item_summary/search?"; //
URL to call
$apicall .= "q=GTR"; //search keyword
$apicall .= "limit=3";
// Create headers to send with CURL request.
$headers = array
(
'X-EBAY-API-APP-ID: ' . $sapp_id,
'X-EBAY-API-DEV-NAME: ' . $dev_id,
'X-EBAY-API-CERT-NAME: ' . $cert_id,
'X-EBAY-C-ENDUSERCTX: 5337984774'
);
// Send request to eBay and load response in $response
$connection = curl_init();
curl_setopt($connection, CURLOPT_URL,
"https://api.ebay.com/buy/browse/v1/item_summary/search?");
curl_setopt($connection, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($connection, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($connection, CURLOPT_HTTPHEADER, $headers);
curl_setopt($connection, CURLOPT_POST, 1);
curl_setopt($connection, CURLOPT_POSTFIELDS, $apicall);
curl_setopt($connection, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec($connection);
curl_close($connection);
// Load the call and capture the document returned by eBay API
$resp = $response;
// Output response
echo("<pre>");
print_r($resp);
//To retrieve specific values of the array in PHP, you will need to use
object operator
// $value = $resp->Item->ConvertedCurrentPrice;
// $value = $resp->Item->ConvertedCurrentPrice;
// print $xml->Product->Title;
echo("</pre>");
?>
i got this error when i run.
{
"errors": [
{
"errorId": 3001,
"domain": "ROUTING",
"category": "REQUEST",
"message": "Request Rejected",
"longMessage": "The Request has errors. For help, see the documentation for this API."
}
]
}
Since i am beginner i don't know what to do.
i tried xml request method and it's work fine but i want to do it with REST API method.
i follow this docs - Official eBay search api documentation
i like to know why i am getting this error and what's the correct way to achieve this search query ?

Not tested as I don't have an eBay developer account but perhaps the following might help. The code below will issue a GET request with the querystring as part of the url as the documentation suggests
<?php
error_reporting( E_ALL );
require_once("includes/config.php");
/*
you can download from https://curl.haxx.se/docs/caextract.html
*/
$cacert='c:/wwwroot/cacert.pem'; # edit as appropriate to point to valid `cacert.pem` file
$verbose=true;
$endpoint = "https://api.ebay.com/buy/browse/v1/item_summary/search?";
$args=array(
'q' => 'GTR',
'limit' => 3
);
$url=sprintf( '%s%s', $endpoint, http_build_query( $args ) );
/*
for advanced debug information we create a stream
and output to that during the request. At the end
of the request the stream is processed and we can
view that data.
*/
if( $verbose )$vbh = fopen('php://temp', 'w+');
$headers = array(
'X-EBAY-API-APP-ID: ' . $sapp_id,
'X-EBAY-API-DEV-NAME: ' . $dev_id,
'X-EBAY-API-CERT-NAME: ' . $cert_id,
'X-EBAY-C-ENDUSERCTX: 5337984774'
);
$curl = curl_init();
curl_setopt( $curl, CURLOPT_URL, $url );
curl_setopt( $curl, CURLOPT_SSL_VERIFYPEER, true );
curl_setopt( $curl, CURLOPT_CAINFO, $cacert );
curl_setopt( $curl, CURLOPT_SSL_VERIFYHOST, 2 );
curl_setopt( $curl, CURLOPT_HTTPHEADER, $headers );
curl_setopt( $curl, CURLOPT_RETURNTRANSFER, 1 );
curl_setopt( $curl, CURLOPT_USERAGENT, 'curl' );
if( $verbose ){
curl_setopt( $curl, CURLOPT_VERBOSE, true );
curl_setopt( $curl, CURLOPT_NOPROGRESS, true );
curl_setopt( $curl, CURLOPT_STDERR, $vbh ); # the stream object
}
/* make the request and get info */
$response = curl_exec( $curl );
$info=(object)curl_getinfo( $curl );
$errors=curl_error( $curl );
/* store the verbose debug info */
if( $verbose ){
rewind( $vbh );
$debug=stream_get_contents( $vbh );
fclose( $vbh );
}
curl_close( $curl );
if( $info->http_code==200 ){
printf( '<pre>%s</pre>', print_r( $response, 1 ) );
} else{
printf( '<pre>%s</pre>', print_r( $verbose ? $debug : $info ,1 ) );
printf( '<pre>%s</pre>', print_r( $errors, 1 ) );
}
?>

Related

fetch X-WP-Total and X-WP-TotalPages response headers using php curl request

I'm trying to read the X-WP-* headers using a curl response requested on the WordPress API for fetching posts (See reference:https://developer.wordpress.org/rest-api/using-the-rest-api/pagination/) e.g https://news.harvard.edu/wp-json/wp/v2/posts.
however I'm unable to read the http response headers returned.
$url = "https://news.harvard.edu/wp-json/wp/v2/posts";
$headers = [];
$data=[];
curl_setopt($curl, CURLOPT_CONNECTTIMEOUT ,0);
curl_setopt($curl, CURLOPT_TIMEOUT, 0);
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HEADER, true);
curl_setopt($curl, CURLOPT_HEADERFUNCTION,
function ($curl, $header) use (&$headers) {
$len = strlen($header);
$header = explode(':', $header, 2);
if (count($header) < 2) // ignore invalid headers
return $len;
$headers[strtolower(trim($header[0]))][] = trim($header[1]);
return $len;
}
);
$response = curl_exec($curl);
if ($response == false) {
if(curl_errno($curl)>=1){
$error = curl_errno($curl);
curl_close($curl);
$data = ["curl_error"=>$error];
}
}else{
$data = [
"headers"=>$headers
];
curl_close($curl);
}
var_dump($data);
// $data doesn't contain X-WP-Total and X-WP-TotalPages
You were nearly there with the above but it lacks any SSL support which is why I believe it was failing. If you set the CURLOPT_HEADER=true option (as above) this code will still work but you'll not be able to decode the JSON response - you do not need to actually print the headers so set this as false or omit completely.
$url = "https://news.harvard.edu/wp-json/wp/v2/posts";
$cacert='c:/wwwroot/cacert.pem';
/*
Download a copy of CACERT.pem from
https://curl.haxx.se/docs/caextract.html
save to webserver and modify the $cacert variable
to suit - ensuring that the path you choose is
readable.
*/
$headers = [];
$data=[];
# slightly modified version of original function
# only appends matching headers to output variable.
$callback=function( $ch, $header ){
global $headers;
$len = strlen( $header );
$header = explode(':', $header, 2 );
if( count( $header ) < 2 ) return $len;
$param = strtolower( trim( $header[0] ) );
$value = trim( $header[1] );
if( strstr( $param, 'x-wp' ) ) $headers[ $param ]=$value;
return $len;
};
$curl=curl_init();
# The request will fail without including options for dealing with SSL.
if( parse_url( $url, PHP_URL_SCHEME )=='https' ){
curl_setopt( $curl, CURLOPT_SSL_VERIFYPEER, true );
curl_setopt( $curl, CURLOPT_SSL_VERIFYHOST, 2 );
curl_setopt( $curl, CURLOPT_CAINFO, $cacert );
}
curl_setopt( $curl, CURLOPT_URL, trim( $url ) );
curl_setopt( $curl, CURLOPT_CONNECTTIMEOUT ,0 );
curl_setopt( $curl, CURLOPT_TIMEOUT, 0 );
curl_setopt( $curl, CURLOPT_RETURNTRANSFER, true );
# we do not need the header in the output
curl_setopt( $curl, CURLOPT_HEADER, false );
# but we do need to process request headers - find any X-WP* headers
curl_setopt( $curl, CURLOPT_HEADERFUNCTION, $callback );
$res = curl_exec($curl);
curl_close( $curl );
# process the required headers...
printf( '<pre>%s</pre>', print_r( $headers, true ) );
$json=json_decode( $res );
# do stuff with JSON data
This outputs the following:
Array
(
[x-wp-total] => 25118
[x-wp-totalpages] => 2512
)

Need help on Facebook API how to get data from array with multiple fields

$endpointFormat = ENDPOINT_BASE . '{page-id}?fields=about,bio,description,new_like_count,talking_about_count,category,fan_count,link,name,rating_count,website,whatsapp_number,followers_count,country_page_likes,were_here_count,location&access_token={access-token}';
$statsAccountEndpoint = ENDPOINT_BASE . $pageId;
$statParams = array(
array ('fields' => 'about','bio','description','new_like_count', 'talking_about_count','category', 'fan_count', 'link','name','rating_count','website','whatsapp_number','followers_count','country_page_likes','were_here_count','location'),
'access_token' => $singleRow['fbaccesstoken']
);
// add params to endpoint
$statsAccountEndpoint .= '?' . http_build_query( $statParams );
// setup curl
$ch = curl_init();
curl_setopt( $ch, CURLOPT_URL, $statsAccountEndpoint );
curl_setopt( $ch, CURLOPT_SSL_VERIFYHOST, false );
curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, false );
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
// make call and get response
$response = curl_exec( $ch );
curl_close( $ch );
$responseArray = json_decode( $response, true );
Printing out the statParams
Printing out responseArray which only shows the name and page id
Just wanting to get the stats of the page im linking, tried with only 1 field variable before and it showed fine. Thanks for your time!
$statParams = array(
'fields' => 'about,bio,description,new_like_count,talking_about_count,category,fan_count,link,name,rating_count,website,whatsapp_number,followers_count,country_page_likes,were_here_count,location',
);
just had to make it so that everything is in one big '' instead of separate.

Inline keyboard Telegram bot [PHP]

I want that my bot when I write /orario he answer me with a inline keyboard.
So.. I created an array for my keyboard in this way:
$tastierino_giorno = '[{"text":"Testo","callback_data":"StampaMessaggio"}]';
and in another function I write this:
function tastieraInline($chatid, $tastierino)
{
global $token;
$messaggio = "Scegli per che giorno inviare il messaggio:";
$tastiera = '&reply_markup={"inline_keyboard":
['.urlencode($tastierino).'],"resize_keyboard":true}';
$url = "https://api.telegram.org/$token/sendMessage?chat_id=$chatId&parse_mode=HTML&text=".urlencode($messaggio).$tastiera;
file_get_contents($url);
}
After this, with an if, I check if the users has write "/orario".
} elseif($message == "/orario"){
tastieraInline($chatid, $tastierino_giorno);
}
Now the problem is that it doesn't works... what's the problem?
Change
$tastiera = '&reply_markup={"inline_keyboard":
['.urlencode($tastierino).'],"resize_keyboard":true}';
to
$tastiera = '&reply_markup='.urlencode('{"inline_keyboard":
['.$tastierino.'],"resize_keyboard":true}');
you should URL encode the whole JSON data
You should pay attention to the result returned from your telegram calls. file_get_contents is great for getting something working quickly but doesn't return any error information.
You should use curl or a library like guzzle. An example for curl:
$ch = curl_init( $url );
if ( $ch == FALSE )
{
error_log( "Error initialising curl" );
return FALSE;
}
curl_setopt( $ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1 );
curl_setopt( $ch, CURLOPT_POST, 0 );
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1 );
curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, 1 );
curl_setopt( $ch, CURLOPT_SSL_VERIFYHOST, 2 );
curl_setopt( $ch, CURLOPT_FORBID_REUSE, 1 );
// Set TCP timeout to 30 seconds
curl_setopt( $ch, CURLOPT_CONNECTTIMEOUT, 30 );
curl_setopt( $ch, CURLOPT_HTTPHEADER, array( 'Connection: Close' ) );
$result = curl_exec( $ch );
$error = curl_errno( $ch );
$errorStr = curl_error( $ch );
curl_close( $ch );
if ( $error != 0 )
{
return array( $errorStr, $result );
}
return $result;
Guzzle is a lot simpler if you don't mind installing an additional library.
Hopefully this will get you the error string from your failed telegram calls.
Onto your actual issue. You should create json for the keyboard markup using json_encode rather than appending strings. http_build_query makes building URLs much easier.

I am getting data from api using curl as a json object it is giving a Array I want to bind that into drop down

Now I want to bind that into drop down how to do that? I don't have any idea to create drio down using api data as a array.
<?php
// specify the REST web service to interact with
$baseurl = 'http://host/api/v1/specializations';
/**
* Authenicate and get back token
*/
$curl = curl_init($baseurl);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: application/json',"Authorization: Bearer $atoken"));
// Set the POST arguments to pass to the Sugar server
$rawPOSTdata = array(
"type" => "private",
);
curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($rawPOSTdata));
// Make the REST call, returning the result
$response = curl_exec($curl);
if (!$response) {
die("Connection Failure.\n");
}
// Convert the result from JSON format to a PHP array
//echo "Success! response result is $response\n";
//print_r($response);
//var_dump(json_decode($response));
curl_close($curl);
if ( isset($result->error) )
{
die($result->error_message."\n");
}
var_dump(json_decode($response, true));
?>
I think this is what you were meaning - along these lines anyway. I'm not 100% sure that I have used the correct keys
<?php
$baseurl = 'http://host/api/v1/specializations';
$headers=array(
"Content-Type: application/json",
"Authorization: Bearer $atoken"
);
$data = array( "type" => "private" );
$curl = curl_init( $baseurl );
curl_setopt( $curl, CURLOPT_POST, true );
curl_setopt( $curl, CURLOPT_HEADER, false );
curl_setopt( $curl, CURLOPT_RETURNTRANSFER, true );
curl_setopt( $curl, CURLOPT_HTTPHEADER, $headers );
curl_setopt( $curl, CURLOPT_POSTFIELDS, json_encode( $data ) );
$result = curl_exec( $curl );
curl_close( $curl );
if( $result ) {
if ( isset($result->error) )die( $result->error_message );
/* Convert json data to array */
$arr=json_decode( $result, true );
/* Items of interest for menu are here? */
$json=$arr['data']['specialityMap'];
/* empty array to populate with html content */
$html=array();
/* add to the array */
$html[]="<select name=''>";
foreach($json as $i => $v )$html[]="<option value='$i'>$v";
$html[]="</select>";
/* echo or return html menu */
echo implode( PHP_EOL, $html );
}
?>
Please have a look if it helps.
$arr = json_decode($response);
foreach($arr['items'] as $val)
{
echo $val['fieldname'].'<br>';
}

Php script for push notfication returns nothing

I have this script for sending a push notification on my android app :
<?php
// Replace with real BROWSER API key from Google APIs
$apiKey = "AIzaSyAATjQOVDdOUiHra0H-EfxpobQcqOsdwqa";
// Replace with real client registration IDs. Put the correct registration id you are getting from app. If you are using eclipse check your logcat you will get it there.
$registrationIDs = array("APA91bEmxWS9bsXLsixaYQ6zuByM0SzFWe5DEKVLO68923hW3Mo2qB6bIH2LarP5WgzKasMtFAdVyy8YQuwv0YbrRNwdGFORh1wQvQ9uKBkC3jH6uXBYAQOv5xfzrsjYjqcQK8syikrQ6dq6oRrp9XUnimdj_4oBbw" );
// Message to be sent
$message = "Push working!";
// Set POST variables.
$url = 'https://android.googleapis.com/gcm/send';
$fields = array(
'registration_ids' => $registrationIDs,
'data' => array( "message" => $message ) /*Make sure that message is the key you are using in GCMIntentService.java onMessage() -> extras.getString("message");*/
);
$headers = array(
'Authorization: key=' . $apiKey,
'Content-Type: application/json'
);
// Open connection
$ch = curl_init();
// Set the url, number of POST vars, POST data
curl_setopt( $ch, CURLOPT_URL, $url );
curl_setopt( $ch, CURLOPT_POST, true );
curl_setopt( $ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
curl_setopt ($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt( $ch, CURLOPT_POSTFIELDS, json_encode( $fields ) );
// Execute post
$result = curl_exec($ch);
// Close connection
curl_close($ch);
// Echo success or failure
echo $result;
?>
I never get any push notification on my phone. The thing is that actually i never get any output from the script like the echo $result; returns nothing.
Is this even possible?
Any ideas?
Solution
<?php
// Replace with real BROWSER API key from Google APIs
$apiKey = "AIzaSyAATjQOVDdOUiHra0H-EfxpobQcqOsdwqa";
// Replace with real client registration IDs. Put the correct registration id you are getting from app. If you are using eclipse check your logcat you will get it there.
$registrationIDs = array("APA91bEmxWS9bsXLsixaYQ6zuByM0SzFWe5DEKVLO68923hW3Mo2qB6bIH2LarP5WgzKasMtFAdVyy8YQuwv0YbrRNwdGFORh1wQvQ9uKBkC3jH6uXBYAQOv5xfzrsjYjqcQK8syikrQ6dq6oRrp9XUnimdj_4oBbw" );
// Message to be sent
$message = "Push working!";
// Set POST variables.
$url = 'https://android.googleapis.com/gcm/send';
$fields = array(
'registration_ids' => $registrationIDs,
'data' => array( "message" => $message ) /*Make sure that message is the key you are using in GCMIntentService.java onMessage() -> extras.getString("message");*/
);
$headers = array(
'Authorization: key=' . $apiKey,
'Content-Type: application/json'
);
// Open connection
$ch = curl_init();
// Set the url, number of POST vars, POST data
curl_setopt( $ch, CURLOPT_URL, $url );
curl_setopt( $ch, CURLOPT_POST, true );
curl_setopt( $ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt( $ch, CURLOPT_POSTFIELDS, json_encode( $fields ) );
// Execute post
$result = curl_exec($ch);
// Close connection
curl_close($ch);
// Echo success or failure
echo $result;
?>
Now it works perfectly.
Found the error.
Replace line curl_setopt ($ch, CURLOPT_SSL_VERIFYHOST, 0);
with line curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, 0);
I corrected the code on the question so now it works.

Categories