PHP Curl - eBay CSV FileExchange - php

I've tried to send a CSV File to eBay FileExchange Service.
I'm writing an application to update a lot of products on eBay at the same time.
When I upload the test.csv by using the eBay CSV-Manager the update will be success, but with the script nothing will happens after post the data.
I've treid the following steps:
Create a separate token for FileExchange.
https://signin.ebay.de/ws/eBayISAPI.dll?SignIn&runame=F-FILEEXL51P1EHH6L899Q9B969GE134DK-FileUpload
Then I use the following script:
$token = 'AgAAAA**AQAAAA**aAAAAA************';
$ebay_url = 'https://bulksell.ebay.com/ws/eBayISAPI.dll?FileExchangeUpload';
$sendheaders = array(
'User-Agent: My Client App v1.0'
);
$fields = array(
'token' => $token,
'file' => '#test.csv'
);
$ch = curl_init($ebay_url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HEADER, 1); // set to 0 to eliminate header info from response
curl_setopt($ch, CURLOPT_NOBODY, 0); // set to 1 to eliminate body info from response
curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0); // use HTTP/1.0 instead of 1.1
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // Returns response data instead of TRUE(1)
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); // uncomment this line if you get no gateway response. ###
curl_setopt($ch, CURLOPT_HTTPHEADER, $sendheaders);
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields); // use HTTP POST to send form data
$resp = curl_exec($ch); //execute post and get results
if(!curl_exec($ch)) {
die('Error: ' . curl_error($ch) . ' - Code: ' . curl_errno($ch));
}
curl_close ($ch);
I've used this csv File-format (test.csv)
Action;ItemID;DispatchTimeMax
Revise;28*********916;30
The results after post:
print_r($resp);
HTTP/1.1 200 OK
Server: Apache-Coyote/1.1
Set-Cookie: dp1=bu1p/QEBfX0BAX19AQA**617d3da3^bl/DE617d3da3^; Domain=.ebay.com; Expires=Sat, 30-Oct-2021 12:42:11 GMT; Path=/
Set-Cookie: s=CgAD4ACBdvCgjMjFkNjZkMDcxNmUwYTBmMTc1MTA0ZmEwZmZmYjEyZWFY39RE; Domain=.ebay.com; Path=/
Set-Cookie: nonsession=CgADKACBhfT2jMjFkNjZkMDcxNmUwYTBmMTc1MTA0ZmEwZmZmYjEyZWIAywABXbrdqzHTwXKU; Domain=.ebay.com; Expires=Sat, 30-Oct-2021 12:42:11 GMT; Path=/
Cache-Control: private
Pragma: no-cache
Content-Type: text/html;charset=UTF-8
Content-Length: 731
Date: Thu, 31 Oct 2019 12:42:11 GMT
Connection: keep-alive
File upload successful. Your ref # is .
Close
Thanks for helping me.

I have found a solution:
Obviously at php 7.1 the # has no effect, and the file post ist empty to ebay.
I use the curl_file_create function and it's work.
if (!function_exists('curl_file_create'))
{
function curl_file_create($filename, $mimetype = '')
{
return "#$filename;filename="
. ($mimetype ? ";type=$mimetype" : '');
}
}
$fields = array(
"token" => $token,
"file" => curl_file_create ($_GET['filename'], 'text/csv')
);
Hope that help's anybody.

Related

PHP - curl post view request body (parameters)

I get an error response for missing parameter when posting cURL POST method,
I'm adding an array of parameters to CURLOPT_POSTFIELDS the following way:
$service = "AutoInsuranceFormPostService";
$method = "autoInsurancePublisherFormPost";
$userAgent = "Mozilla%2F5.0+%28Linux%3B+Android+4.4.4%3B+Z752C+Build%2FKTU84P%29+AppleWebKit%2F537.36+%28KHTML%2C+like+Gecko%29+Chrome%2F36.0.1985.135+Mobile+Safari%2F537.36";
$payload = $encodedPayLoad;
$parameters = array (
'service' => $service,
'method' => $method,
'UserAgent' => $userAgent,
'payload' => $payload
);
With:
curl_setopt($ch,CURLOPT_POSTFIELDS,$parameters);
Since the response is saying missing parameter "service", I figured I need to debug the request body.
I managed to get the headers with:
curl_getinfo($ch)
I also attempted to use:
curl_setopt($ch, CURLOPT_VERBOSE, true);
But unfortunately in both cases I only got the headers and not the body (the parameters values).
Full curl execution function:
function openurl($url, $postvars) {
$ch=curl_init();
curl_setopt($ch, CURLOPT_VERBOSE, true);
$verbose = fopen('php://temp', 'w+');
curl_setopt($ch, CURLOPT_STDERR, $verbose);
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch,CURLOPT_POSTFIELDS,$postvars);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch,CURLOPT_TIMEOUT, '3');
$result = curl_exec($ch);
rewind($verbose);
$verboseLog = stream_get_contents($verbose);
echo "Verbose information:\n<pre>", htmlspecialchars($verboseLog), "</pre>\n";
return $result;
}
Verbos information:
Content-Length: 6659
Expect: 100-continue
Content-Type: application/x-www-form-urlencoded; boundary=------------------------45b2d9f6776306b0
< HTTP/1.1 100 Continue
< HTTP/1.1 200 OK
< Date: Thu, 12 Jul 2018 16:32:52 GMT
< Server: Apache
< Cache-Control: public
< ORIGIN: S_CACHE
< Vary: User-Agent,Accept-Encoding
< Set-Cookie: _qs_origin=s-cache; path=/;
< Set-Cookie: _qs_deviceType=; path=/;
< Content-Length: 141
< Content-Type: application/json;charset=ISO-8859-1
<
This output is useless for me since I cannot see how the parameters were sent and those cannot fix their format.
The response I get is:
{"Status":"Fail","StatusCode":"400","ResponseMessage":"\"service\" parameter empty! || \"method\" parameter empty! ","SkipMatchingFlag":"No"}
I have been searching for a solution all day long, I've seen a ton of answers on "How to see the RESPONSE body", and "How to see the request HEADERS".
But none for "How to see the request body", so any help would be much appreciated,
Best regards.

Subscribe using Superfeedr PubSubHubbub generating error hub.topic not found

I want to integrate Superfeedr API using PubSubHubbub in PHP. I am following this and my code is:
<?php
require_once('Superfeedr.class.php')
$superfeedr = new Superfeedr('http://push-pub.appspot.com/feed',
'http://mycallback.tld/push?feed=http%3A%2F%2Fpush-pub.appspot.com%2Ffeed',
'http://wallabee.superfeedr.com');
$superfeedr->verbose = true;
$superfeedr->subscribe();
?>
And my subscribe() function is
public function subscribe()
{
$this->request('subscribe');
}
private function request($mode)
{
$data = array();
$data['topic'] = $this->topic;
$data['callback'] = $this->callback;
$post_data = array (
"hub.mode" => 'subscribe',
"hub.verify" => "sync",
"hub.callback" => urlencode($this->callback),
"hub.topic" => urlencode($this->topic),
"hub.verify_token" => "26550615cbbed86df28847cec06d3769",
);
//echo "<pre>"; print_r($post_data); exit;
// url-ify the data for the POST
foreach ($post_data as $key=>$value) {
$post_data_string .= $key.'='. $value.'&';
}
rtrim($fields_string,'&');
// curl request
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $this->hub);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Accept: application/json'));
curl_setopt($ch, CURLOPT_USERPWD, 'USERNAME:PASSWORD');
$output = curl_exec($ch);
if ($this->verbose) {
print('<pre>');
print_r($output);
print('</pre>');
}
}
But after execution I am getting this error
HTTP/1.1 422 Unprocessable Entity
X-Powered-By: The force, Luke
Vary: X-HTTP-Method-Override, Accept-Encoding
Content-Type: text/plain; charset=utf-8
X-Superfeedr-Host: supernoder16.superfeedr.com
Access-Control-Allow-Origin: *
Access-Control-Allow-Credentials: true
Access-Control-Allow-Methods: GET, POST, PUT, DELETE
Access-Control-Allow-Headers: Authorization
Content-Length: 97
ETag: W/"61-db6269b5"
Date: Wed, 24 Aug 2016 14:01:47 GMT
Connection: close
Please provide a valid hub.topic (feed) URL that is accepted on this hub. The hub does not match.
Same data (topic and callback etc..) requesting from https://superfeedr.com/users/testdata/push_console
is working fine. But I don't know why I am getting this error on my local. If anyone has any experienced with same problom then please help me. Thanks.
You are using a strange hub URL. You should use HTTPS://push.superfeedr.com in the last param of your class constructor.

How to perform a PUT operation using CURL in PHP?

I would like to perform a PUT operation on a webservice using CURL. Let's assume that:
webservice url: http://stageapi.myprepaid.co.za/api/ConsumerRegisterRequest/cac52674-1711-e311-b4a8-00155d4905d3
municipality= NMBM
sgc= 12345
I've written the code below, but it outputs this error message: "ExceptionMessage":"Object reference not set to an instance of an object.". Any help would be so much appreciated. Thanks!
<?php
function sendJSONRequest($url, $data)
{
$data_string = json_encode($data);
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Accept: application/json',
'X-MP-Version: 10072013')
);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
ob_start();
$result = curl_exec($ch);
$info = curl_getinfo($ch);
if ($result === false || $info['http_code'] == 400) {
return $result;
} else {
return $result;
}
ob_end_clean();
curl_close($ch);
}
$mun = $_GET['municipality'];
$sgc = $_GET['sgc'];
$req = $_GET['req']; //cac52674-1711-e311-b4a8-00155d4905d3
//myPrepaid PUT URL
echo $mpurl = "http://stageapi.myprepaid.co.za/api/ConsumerRegisterRequest/$req";
// Set Variables
$data = array("Municipality" => "$mun", "SGC" => "$sgc");
//Get Response
echo $response = sendJSONRequest($mpurl, $data);
?>
I copied your code, but changed it so it pointed at a very basic HTTP server on my localhost. Your code is working correctly, and making the following request:
PUT /api/ConsumerRegisterRequest/cac52674-1711-e311-b4a8-00155d4905d3 HTTP/1.1
Host: localhost:9420
Content-Type: application/json
Accept: application/json
X-MP-Version: 10072013
Content-Length: 37
{"Municipality":"NMBM","SGC":"12345"}
The error message you're receiving is coming from the stageapi.myprepaid.co.za server. This is the full response when I point it back to them:
HTTP/1.1 500 Internal Server Error
Cache-Control: no-cache
Pragma: no-cache
Content-Type: application/json; charset=utf-8
Expires: -1
Server: Microsoft-IIS/8.0
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
Date: Fri, 30 Aug 2013 04:30:41 GMT
Connection: close
Content-Length: 867
{"Message":"An error has occurred.","ExceptionMessage":"Object reference not set to an instance of an object.","ExceptionType":"System.NullReferenceException","StackTrace":" at MyPrepaidApi.Controllers.ConsumerRegisterRequestController.Put(CrmRegisterRequest value) in c:\\Workspace\\MyPrepaid\\Prepaid Vending System\\PrepaidCloud\\WebApi\\Controllers\\ConsumerRegisterRequestController.cs:line 190\r\n at lambda_method(Closure , Object , Object[] )\r\n at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.<>c__DisplayClass13.<GetExecutor>b__c(Object instance, Object[] methodParameters)\r\n at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.Execute(Object instance, Object[] arguments)\r\n at System.Threading.Tasks.TaskHelpers.RunSynchronously[TResult](Func`1 func, CancellationToken cancellationToken)"}
You may want to check out the API to make sure you're passing them the correct information. If you are, the problem could be on their end.
And while I realize this isn't part of your question and this is in development, please remember to sanitize any data from $_GET. :)
Try with:
curl_setopt($ch, CURLOPT_PUT, true);

What's wrong in the php code? Unknown output

PHP code file: sms1.php
Located at http://techmentry.com/sms1.php (please visit the link and see the outpur of the below code).
<?php
//Variables to POST
$user = "HIDDEN";
$password = "HIDDEN";
$mobiles = "919999999999";
$message = "test";
$sender = "HIDDEN";
//Initialize CURL data to send via POST
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://example.com/example.php");
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, "user=$user&
password=$password&
mobiles=$mobiles&
message=$message&
sender=$sender"
);
//Execute CURL command and return into variable $result
$result = curl_exec($ch);
//Do stuff
echo "$result"
?>
The output I expected is: The above code should have process this URL: URL HIDDEN
and then return a message ID or appropiate error code.
But the output I got is beyond my expection! There are even no error logs. Please help me :)
You get the code, but you also get the complete response from the server, including HTTP headers.
I get:
HTTP/1.1 200 OK
Date: Wed, 24 Jul 2013 12:24:01 GMT
Server: Apache
Expires: Thu, 19 Nov 1981 08:52:00 GMT
Cache-Control: max-age=60, private, proxy-revalidate
Pragma: no-cache
Vary: Accept-Encoding
Content-Length: 8
Content-Type: text/html
Set-Cookie: PHPSESSID=c9bfcf7ddd3fff9d0a05b34541fbf0a9; expires=Wed, 24-Jul-2013 16:24:01 GMT; path=/
code 105
Try to remove this line:
curl_setopt($ch, CURLOPT_HEADER, 1);

how to handle box.net download responce in php

i am trying to download a file using box.net using API in php.
As per the documentation i wrote up the code.
but in response i am getting some strange texts.
here's my code:
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://api.box.com/2.0/files/3934139624/content ");
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_HTTPGET,true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Authorization: BoxAuth api_key={MyApikey}&auth_token={Mytoken}"));
$result = curl_exec($ch);
die('DIE');
I am getting response something like this:
PK!Ðòš-[Content_Types].xml ¢( ´UËNÃ0¼#ñ‘¯¨qË!Ô´G¨Dù×Þ´‰mÙÛ×ß³IšA›ˆ†^"EÑÎÌÎÎnÆÓ]žEðA[“°QH¯~ÉŸb üv8¼ãÒƒ,0ØdüF¼VÍ„ÇW‘ßZ¯xj-‹b‚cÑcUWP'L8—i)„óQ?H6Mµeå:'ª¸€sÞJZ˳¸¾) ùdü©Xg=ïH[e‡‡,üõÐfL•¥²°Ò.´0´·uPvÒž¦»v˜3Üis¡M­ÿ¤³ÎàÉ×ÿSÝ)"à>»DP*ÜNz0êBI­‘Û$мfÞºÀi+zŠ P ´0"f3°£\…ȾTºI S‘ÌõŒ«º¾ÇôWš™¦ÚY igï#µÇX6_Ö]7~ fïØˉÈaoÙ.b*lIÆrj)õ,l0Ï%‘b¬ 6ài¢ÕõDÿ_‹Ž…, ¡ ‰Ïó|uœZ^tÙ¢yǯ;!Y,}{ûCƒ³/h>ÿÿPK!¿hJä1>word/rels/document.xml.rels ¢( ¬”ËNÃ0E÷HüCä=qR q'æ>¾ƒ“‘ˆsµà©WÃ-ŽÌEî›nâ>ðÍqã¨Í§y±3ÆóüükeìE±ty’àÕ³üÍ黦ÏÖ¤KLÏhóÊŸi¾IàˆpzÒŽ¹ç?}xÛxx;ùgïÐ¥f7Yô KéMèwÄÆÇÐEïúÃF§³ß9ètÏ7ÌKWxÐ/žñ¡“ùéâ;W…—Ô•¯bú%B×óù§ìv îã㡈“ô£ 8ÜílìÐqq~x|!Ã4Á1Nâ ñaãVš+¾•ËÓr¤ØLe'õc"ójS“Œ(ñR'»>wbriê’6œ,•ôçPøH†.ÔO«<çµ¼G›[¯ ‹Ÿ~ëÈŒcñ)“ )ò<­4/nÌ—­ôEÛþßpÄÙ÷æ¬Û?xg«\ÖîЃSäÀ•Ç°tÒ(¾‹³ƒwïg˜³ÕKøŒ;ù¾.†ì, l©´ªµÐm¯]‰ŠTíßnÁ¿·ß¤/ë»–ª”짓6õ“^Qð-wô—Qð]6bé à²#ÆûÍ#¡™˜×Fa'™Â†êMî'ÂÛ¿U*XÆÞ/¾\ÁÜl X5HñKÕ˜sØ8EÌ/!вÃÐeq”µ±dº¨É…⛂R—7ЊU¹iØF:h±FÎç¢àõð¾ôÈ!˜&æ',ADSÈP¸L‘M.úìäpow½Ý(¥Ú·R ãpK0è7^;¿Lë4f¤P­3Ì…#M s´ï¡Ü:…(#à(1ß;9|÷S½°T4ϹF²ì%“$åÁf“tÖة⼪R&˜nn†)#éóÒfŽBC?‰ð€()ÄÝ(%LNËñ)V^«ÞÛ¶[5+Í>jÀ£WlŽ÷¡¿)ÁoôFBû›CÕ©ë­Ü™ÖI¦æÖQ×ƤHX-ijž^ÀDûs“ …Ø}
Can any one tell me how can i handle such kind of response?
thanks in advance.
As per box.net api documentation:
The response to this request will simply be the complete data of the
file itself.
So all you need to save file content locally.
In response header, you need to check content-type, right now it is XML
$result = curl_exec($ch);
$fp = fopen('test.xml','wb');
fwrite($fp, $result);
fclose($fp);
#GBD following comes in response header:
HTTP/1.1 302 Found
Server: nginx
Date: Wed, 14 Nov 2012 09:11:51 GMT
Content-Type: text/html; charset=utf-8
Connection: keep-alive
Cache-control: private
Location: https://dl.boxcloud.com/bc/1/85f471520cf611a05025a5f/JolueqOGpciD6dgYhecNBoVpYxkvmYe1ZLheZor6BF4DUBIelMQTkFwYIys3nIibNIIEHUp447tBZLaXDzIbNQ,,/a44510a2b21219463fade41d6b36dabf/
Content-Length: 0
HTTP/1.1 200 OK
Server: nginx
Date: Wed, 14 Nov 2012 09:11:52 GMT
Content-Type: application/vnd.openxmlformats-officedocument.wordprocessingml.document
Content-Length: 19944
Connection: keep-alive
Cache-control: private
Accept-Ranges: bytes
Content-Disposition: attachment;filename="cloud computing proposal.docx";filename*=UTF-8''cloud%20computing%20proposal.docx
X-Content-Type-Options: nosniff
Accept-Ranges: bytes
And saving file in xml also,couldn't b opened.

Categories