401 Unauthorized on Adyen API - php

I'm trying to do a payment in my test environment in Adyen with curl but for some reason I keep getting a 401 Unauthorized response back. I have checked the credentials of the Web Service User a dozen times but I'm sure they are correct. When I try the official Adyen PHP Api library (https://github.com/Adyen/adyen-php-api-library) I get the same results. I have also tried creating a new Web Service User but without results. Has anyone an idea what I'm doing wrong?
The request code:
<?php
$request = array(
"merchantAccount" => "MyWebsite",
"amount" => array(
"currency" => "EUR",
"value" => "199"
),
"reference" => "TEST-PAYMENT-" . date("Y-m-d-H:i:s"),
"shopperIP" => "2.207.255.255",
"shopperReference" => "YourReference",
"billingAddress" => array(
"street" => "Simon Carmiggeltstraat",
"postalCode" => "1011DJ",
"city" => "Amsterdam",
"houseNumberOrName" => "6-60",
"stateOrProvince" => "NH",
"country" => "NL"
),
"card" => array(
"expiryMonth" => "08",
"expiryYear" => "2018",
"holderName" => "Test Card Holder",
"number" => "4111111111111111",
"cvc" => "737"
),
);
$json = json_encode($request);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://pal-test.adyen.com/pal/servlet/Payment/v25/authorise");
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC );
curl_setopt($ch, CURLOPT_USERPWD, "xxxx:xxxx");
curl_setopt($ch, CURLOPT_POST, count($request));
curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER,array("Content-type: application/json"));
// things I tried
curl_setopt($ch, CURLOPT_USERAGENT,'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.17 (KHTML, like Gecko) Chrome/24.0.1312.52 Safari/537.17');
curl_setopt($ch, CURLOPT_AUTOREFERER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
$result = curl_exec($ch);
?>
The $result variable returns an empty string.
Response:
* Trying 91.212.42.153...
* Connected to pal-test.adyen.com (91.212.42.153) port 443 (#0)
* ALPN, offering http/1.1
* Cipher selection: ALL:!EXPORT:!EXPORT40:!EXPORT56:!aNULL:!LOW:!RC4:#STRENGTH
* successfully set certificate verify locations:
* CAfile: /etc/ssl/certs/ca-certificates.crt
CApath: /etc/ssl/certs
* SSL connection using TLSv1.2 / ECDHE-RSA-AES128-GCM-SHA256
* ALPN, server did not agree to a protocol
* Server certificate:
* subject: C=NL; ST=Noord-Holland; L=Amsterdam; O=Adyen B.V.; CN=*.adyen.com
* start date: Jun 14 00:00:00 2016 GMT
* expire date: Aug 13 23:59:59 2018 GMT
* issuer: C=US; O=thawte, Inc.; CN=thawte SSL CA - G2
* SSL certificate verify ok.
* Server auth using Basic with user 'xxxxx'
> POST /pal/servlet/Payment/v25/authorise HTTP/1.1
Host: pal-test.adyen.com
Authorization: Basic xxxxxx
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.17 (KHTML, like Gecko) Chrome/24.0.1312.52 Safari/537.17
Accept: */*
Content-type: application/json
Content-Length: 465
* upload completely sent off: 465 out of 465 bytes
< HTTP/1.1 401 Unauthorized
< Date: Mon, 02 Apr 2018 19:58:11 GMT
< Server: Apache
< Set-Cookie: JSESSIONID=47E667BF9B585DC3BDF40F8D58493E23.test103e; Path=/pal; Secure; HttpOnly
* Authentication problem. Ignoring this.
< WWW-Authenticate: BASIC realm="Adyen PAL Service Authentication"
< Content-Length: 0
< Content-Type: text/plain; charset=UTF-8
<
* Connection #0 to host pal-test.adyen.com left intact

401 is failed authentication. You are not using the correct combination of user + password.
You have the option to generate a password for general API usage or for POS Payments. Make sure that if are intending to use this API user for the general API, use the "Generate Password" and not "Generate POS Password".

Status: 401 with errorCode: 000 is a classic error for when the following maybe incorrect:
Use correct merchantAccount Name NOT companyAccount Name
API Key - Preferably regenerate the API Key and use the copy button in the customer area to copy it
Environment set to LIVE/TEST

Oke it works now. The strange thing is that I didn't change anything. My guess is that Adyen was having trouble on their side. I'll give them a call next time when something similar happens.

Related

PHP Guzzle request to get access_token not working. Works fine with CURL

I'm getting started trying to understand Guzzle but one of my requests keeps returning an error, even though the exact same request when done using CURL works just fine.
I have a refresh_token and want to get an access_token from WEB API.
The Guzzle request that results in an error:
$refresh_token = '<token>';
$client = new GuzzleHttp\Client(['headers' => ['Content-Type' => 'application/x-www-form-urlencoded']]);
$response = $client->request('POST', 'https://foo.bar/secure/token', [
'query' => ['grant_type' => 'refresh_token','refresh_token' => $refresh_token]
]);
echo $response->getStatusCode();
echo $response->getBody();
Fatal error: Uncaught exception 'GuzzleHttp\Exception\ClientException' with message 'Client error: resulted in a 400 Bad Request response' in vendor/guzzlehttp/guzzle/src/Exception/RequestException.php:113
This CURL request works just fine:
$refresh_token = '<token>';
$params=['grant_type'=>'refresh_token',
'refresh_token'=>$refresh_token
];
$headers = [
'POST /secure/token HTTP/1.1',
'Content-Type: application/x-www-form-urlencoded'
];
$curlURL='https://foo.bar/secure/token';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$curlURL);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS,http_build_query($params));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_VERBOSE, true);
$curl_res = curl_exec($ch);
if($curl_res) {
$server_output = json_decode($curl_res);
}
var_dump($curl_res);
I hope for your help.
Here's the Guzzle debug that was printed out in the browser.
Request Method: GET
Status Code: 200 OK
Remote Address: 87.236.19.237:80
Referrer Policy: no-referrer-when-downgrade
Connection: keep-alive
Content-Encoding: gzip
Content-Type: text/html
Date: Wed, 21 Aug 2019 15:46:25 GMT
Keep-Alive: timeout=30
Server: nginx-reuseport/1.13.4
Transfer-Encoding: chunked
Vary: Accept-Encoding
X-Powered-By: PHP/5.6.38
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3
Accept-Encoding: gzip, deflate
Accept-Language: ru-RU,ru;q=0.9,en-US;q=0.8,en;q=0.7
Cache-Control: max-age=0
Connection: keep-alive
DNT: 1
Upgrade-Insecure-Requests: 1
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.100 Safari/537.36
Your request becomes GET probably because of the "query" parameter.
Use form_params instead of query.
See the documentation.
http://docs.guzzlephp.org/en/stable/request-options.html#form-params
This is correct! Tnx Jonnix!
$response = $client->request('POST', 'https://sso.tinkoff.ru/secure/token', [
'form_params' => [
'grant_type' => 'refresh_token',
'refresh_token' => $refresh_token
]
]);

How to simulate a real request from browser using CURL?

I'm trying to simulate a real browser request using CURL with proxy rotate, I searched about it, But none of the answers worked.
Here is the code:
$url= 'https://www.stubhub.com/';
$proxy = '1.10.185.133:30207';
$userAgent = 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36';
$curl = curl_init();
curl_setopt( $curl, CURLOPT_URL, trim($url) );
curl_setopt($curl, CURLOPT_REFERER, trim($url));
curl_setopt( $curl, CURLOPT_RETURNTRANSFER, TRUE );
curl_setopt( $curl, CURLOPT_FOLLOWLOCATION, TRUE );
curl_setopt( $curl, CURLOPT_CONNECTTIMEOUT, 0 );
curl_setopt( $curl, CURLOPT_TIMEOUT, 0 );
curl_setopt( $curl, CURLOPT_AUTOREFERER, TRUE );
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
$cacert='C:/xampp/htdocs/cacert.pem';
curl_setopt( $curl, CURLOPT_CAINFO, $cacert );
curl_setopt($curl, CURLOPT_COOKIEFILE,__DIR__."/cookies.txt");
curl_setopt ($curl, CURLOPT_COOKIEJAR, dirname(__FILE__) . '/cookies.txt');
curl_setopt($curl, CURLOPT_MAXREDIRS, 5);
curl_setopt( $curl, CURLOPT_USERAGENT, $userAgent );
//Headers
$header = array();
$header[] = "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
$header[] = "Accept-Language: cs,en-US;q=0.7,en;q=0.3";
$header[] = "Accept-Encoding: utf-8";
$header[] = "Connection: keep-alive";
$header[] = "Host: www.gumtree.com";
$header[] = "Origin: https://www.stubhub.com";
$header[] = "Referer: https://www.stubhub.com";
curl_setopt( $curl, CURLOPT_HEADER, $header );
curl_setopt($curl, CURLOPT_PROXYTYPE, CURLPROXY_HTTP);
curl_setopt($curl, CURLOPT_HTTPPROXYTUNNEL, TRUE);
curl_setopt($curl, CURLOPT_PROXY, $proxy);
curl_setopt($curl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
$data = curl_exec( $curl );
$info = curl_getinfo( $curl );
$error = curl_error( $curl );
echo '<pre>';
print_r($all);
echo '</pre>';
Here is what I get when I run the script:
Array
(
[data] => HTTP/1.1 200 OK
HTTP/1.0 405 Method Not Allowed
Server: nginx
Content-Type: text/html; charset=UTF-8
Accept-Ranges: bytes
Expires: Thu, 01 Jan 1970 00:00:01 GMT
Cache-Control: private, no-cache, no-store, must-revalidate
Surrogate-Control: no-store, bypass-cache
Content-Length: 9411
X-EdgeConnect-MidMile-RTT: 203
X-EdgeConnect-Origin-MEX-Latency: 24
Date: Sat, 03 Nov 2018 17:15:56 GMT
Connection: close
Strict-Transport-Security: max-age=31536000; includeSubDomains
[info] => Array
(
[url] => https://www.stubhub.com/
[content_type] => text/html; charset=UTF-8
[http_code] => 405
[header_size] => 487
[request_size] => 608
[filetime] => -1
[ssl_verify_result] => 0
[redirect_count] => 0
[total_time] => 38.484
[namelookup_time] => 0
[connect_time] => 2.219
[pretransfer_time] => 17.062
[size_upload] => 0
[size_download] => 9411
[speed_download] => 244
[speed_upload] => 0
[download_content_length] => 9411
[upload_content_length] => -1
[starttransfer_time] => 23.859
[redirect_time] => 0
[redirect_url] =>
[primary_ip] => 1.10.186.132
[certinfo] => Array
(
)
[primary_port] => 42150
[local_ip] => 192.168.1.25
[local_port] => 59320
)
[error] =>
)
As well as a Recaptcha, As it says:
Due to high volume of activity from your computer, our anti-robot software has blocked your access to stubhub.com. Please solve the puzzle below and you will immediately regain access.
When I visit the website using any browser, The website is displayed.
But with the above script, It's not.
So what am I missing to make the curl request like a real browser request and not be detected as a bot?
Or if there is an API/library that could do it, Please mention it.
Would Guzzle or similar fix this issue?
"So what am I missing to make the curl request like a real browser request"
My guess is they are using a simple cookie check. There are more sophisticated methods that allow recognizing automation such as cURL with a high degree of reliability, especially if coupled with lists of proxy IP addresses or IPs of known bangers.
Your first step is to intercept the outgoing browser request using pcap or something similar, then try and replicate it using cURL.
One other simple thing to check is whether your cookie jar has been seeded with some telltale. I routinely do that too, since most scripts on the Internet are just copy-pastes and don't pay much attention to these details.
The thing that would for sure make you bounce from any of my systems is that you're sending a referer, but you don't seem to actually have connected to the first page. You're practically saying "Well met again" to a server that is seeing you for the first time. You might have saved a cookie from that first encounter, and the cookie has now been invalidated (actually been marked "evil") by some other action. At least in the beginning, always replicate the visiting sequence from a clean slate.
You might try and adapt this answer, also cURL-based. Always verify actual traffic using a MitM SSL-decoding proxy.
Now, the real answer - what do you need that information for? Can you get it somewhere else? Can you ask for it explicitly, maybe reach an agreement with the source site?

curl_setopt 504 Gateway Time-out

I write code for send hit request to proxy server's ip addresses. But this code is giving error of
504 Gateway Time-out
I also try to increase the timeout in php.ini. But that is also not working. Here is the code I am trying to use
<?php
$curl = curl_init();
$timeout = 300;
$proxies = file("proxy.txt");
$r="https://www.youtube.com/watch?v=iglQXfPXJHE";
//$r ="https://www.youtube.com/watch?v=rcWMxmKbj7c";
// Not more than 2 at a time
for($x=0;$x<2000; $x++){
//setting time limit to zero will ensure the script doesn't get timed out
set_time_limit(300);
//now we will separate proxy address from the port
//$PROXY_URL=$proxies[$getrand[$x]];
echo $proxies[$x];
curl_setopt($curl, CURLOPT_URL,$r);
curl_setopt($curl , CURLOPT_PROXY , preg_replace('/\s+/', '',$proxies[$x]));
curl_setopt($curl, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.9.0.5) Gecko/2008120122 Firefox/3.0.5");
curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, $timeout);
curl_setopt($curl, CURLOPT_REFERER, "http://google.com/");
$text = curl_exec($curl);
echo "Hit Generated:";
echo htmlentities($x);
}
?>
Any help is appreciated. Thank you
Given a text file, call proxy.txt, with the following content
198.110.57.6 8080 US United States anonymous no yes 1 minute ago
35.193.215.131 8080 US United States anonymous no yes 1 minute ago
198.50.219.239 80 CA Canada anonymous no yes 1 minute ago
217.61.124.144 80 IT Italy anonymous no yes 1 minute ago
171.255.199.5 80 VN Vietnam anonymous no no 1 minute ago
And the following PHP code
define('ROOT','c:/wwwroot');
function curlproxy( $url, $ip, $port, $https ){
$cacert=ROOT . '/cacert.pem';
$curl=curl_init();
if( $https==true ){
curl_setopt( $curl, CURLOPT_SSL_VERIFYPEER, 0 );
curl_setopt( $curl, CURLOPT_SSL_VERIFYHOST, 2 );
curl_setopt( $curl, CURLOPT_CAINFO, realpath( $cacert ) );
$proxy='https://'.$ip .':' . $port;
} else {
$proxy='http://'.$ip .':' . $port;
}
$vbh = fopen('php://temp', 'w+');
curl_setopt( $curl, CURLOPT_URL, $url );
curl_setopt( $curl, CURLOPT_AUTOREFERER, TRUE );
curl_setopt( $curl, CURLOPT_FOLLOWLOCATION, TRUE );
curl_setopt( $curl, CURLOPT_FRESH_CONNECT, TRUE );
curl_setopt( $curl, CURLOPT_FORBID_REUSE, TRUE );
curl_setopt( $curl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1 );
curl_setopt( $curl, CURLOPT_CLOSEPOLICY, CURLCLOSEPOLICY_OLDEST );
curl_setopt( $curl, CURLOPT_MAXCONNECTS, 1 );
curl_setopt( $curl, CURLOPT_FAILONERROR, TRUE );
curl_setopt( $curl, CURLOPT_RETURNTRANSFER, TRUE );
curl_setopt( $curl, CURLOPT_CONNECTTIMEOUT, 20 );
curl_setopt( $curl, CURLOPT_TIMEOUT, 20 );
curl_setopt( $curl, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36' );
curl_setopt( $curl, CURLINFO_HEADER_OUT, FALSE );
curl_setopt( $curl, CURLOPT_NOBODY, TRUE );
curl_setopt( $curl, CURLOPT_PROXY, $proxy );
curl_setopt( $curl, CURLOPT_HTTPPROXYTUNNEL, TRUE );
curl_setopt( $curl, CURLOPT_PROXYTYPE, CURLPROXY_HTTP );
curl_setopt( $curl, CURLOPT_VERBOSE, TRUE );
curl_setopt( $curl, CURLOPT_NOPROGRESS, TRUE );
curl_setopt( $curl, CURLOPT_STDERR, $vbh );
$payload=(object)array_filter( array(
'response' => curl_exec( $curl ),
'info' => (object)curl_getinfo( $curl ),
'errors' => curl_error( $curl ),
'request' => array(
'url' => $url,
'ip' => $ip,
'port' => $port,
'https' => $https,
'proxy' => $proxy
)
)
);
curl_close( $curl );
rewind( $vbh );
$payload->verbose=stream_get_contents( $vbh );
fclose( $vbh );
return $payload;
}
$data=array();
$url='https://www.youtube.com/watch?v=iglQXfPXJHE';
$list = file('c:/temp/proxy.txt');
foreach( $list as $i => $line ){
list($ip,$port,$code,$country,$anomynous,$google,$https,$up)=explode(chr(9),$line);
$data[]=curlproxy( $url, $ip, $port, $https );
}
echo '<pre>',print_r($data,true),'</pre>';
Gave reasonable results for certain proxies chosen randomly from free-proxy-list.net ~ of which a small snippet is shown here
Array
(
[0] => stdClass Object
(
[info] => stdClass Object
(
[url] => https://lightspeed.ravennaschools.org/access?YT91X4Q5J1HNFABCRE8BZ5FZ22WS4KQ2
[content_type] => text/html
[http_code] => 200
[header_size] => 721
[request_size] => 970
[filetime] => -1
[ssl_verify_result] => 19
[redirect_count] => 1
[total_time] => 1.763
[namelookup_time] => 0
[connect_time] => 0.14
[pretransfer_time] => 0.624
[size_upload] => 0
[size_download] => 0
[speed_download] => 0
[speed_upload] => 0
[download_content_length] => 0
[upload_content_length] => 0
[starttransfer_time] => 0.764
[redirect_time] => 0.999
[certinfo] => Array
(
)
)
[request] => Array
(
[url] => https://www.youtube.com/watch?v=iglQXfPXJHE
[ip] => 198.110.57.6
[port] => 8080
[https] => yes
[proxy] => https://198.110.57.6:8080
)
[verbose] => * About to connect() to proxy 198.110.57.6 port 8080 (#0)
* Trying 198.110.57.6... * connected
* Connected to 198.110.57.6 (198.110.57.6) port 8080 (#0)
* Establish HTTP proxy tunnel to www.youtube.com:443
> CONNECT www.youtube.com:443 HTTP/1.1
Host: www.youtube.com:443
User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36
Proxy-Connection: Keep-Alive
< HTTP/1.1 200 Connection established
<
* Proxy replied OK to CONNECT request
* successfully set certificate verify locations:
* CAfile: C:\wwwroot\cacert.pem
CApath: none
* SSL connection using AES256-SHA
* Server certificate:
* subject: C=US; ST=California; L=Mountain View; O=Google Inc; CN=*.google.com
* start date: 2017-07-25 08:46:44 GMT
* expire date: 2017-10-17 08:28:00 GMT
* subjectAltName: www.youtube.com matched
* issuer: C=US; ST=California; L=Bakersfield; O=Lightspeed Systems; OU=Support; CN=Lightspeed Rocket; emailAddress=support#lightspeedsystems.com
* SSL certificate verify result: self signed certificate in certificate chain (19), continuing anyway.
> HEAD /watch?v=iglQXfPXJHE HTTP/1.1
User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36
Host: www.youtube.com
Accept: */*
< HTTP/1.1 302 Moved Temporarily
< Server: squid/3.3.13
< Date: Thu, 10 Aug 2017 06:52:52 GMT
< Content-Length: 0
< Location: https://lightspeed.ravennaschools.org/access?YT91X4Q5J1HNFABCRE8BZ5FZ22WS4KQ2
< X-Cache: MISS from lightspeed.ravennaschools.org
< Via: 1.1 lightspeed.ravennaschools.org (squid/3.3.13)
< Connection: close
<
* Closing connection #0
* Issue another request to this URL: 'https://lightspeed.ravennaschools.org/access?YT91X4Q5J1HNFABCRE8BZ5FZ22WS4KQ2'
* About to connect() to proxy 198.110.57.6 port 8080 (#0)
* Trying 198.110.57.6... * connected
* Connected to 198.110.57.6 (198.110.57.6) port 8080 (#0)
* Establish HTTP proxy tunnel to lightspeed.ravennaschools.org:443
> CONNECT lightspeed.ravennaschools.org:443 HTTP/1.1
Host: lightspeed.ravennaschools.org:443
User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36
Proxy-Connection: Keep-Alive
< HTTP/1.1 200 Connection established
<
* Proxy replied OK to CONNECT request
* successfully set certificate verify locations:
* CAfile: C:\wwwroot\cacert.pem
CApath: none
* SSL connection using AES256-SHA
* Server certificate:
* subject: OU=Domain Control Validated; CN=lightspeed.ravennaschools.org
* start date: 2017-08-01 16:01:01 GMT
* expire date: 2020-08-01 16:01:01 GMT
* subjectAltName: lightspeed.ravennaschools.org matched
* issuer: C=US; ST=California; L=Bakersfield; O=Lightspeed Systems; OU=Support; CN=Lightspeed Rocket; emailAddress=support#lightspeedsystems.com
* SSL certificate verify result: self signed certificate in certificate chain (19), continuing anyway.
> HEAD /access?YT91X4Q5J1HNFABCRE8BZ5FZ22WS4KQ2 HTTP/1.1
User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36
Host: lightspeed.ravennaschools.org
Accept: */*
Referer: https://www.youtube.com/watch?v=iglQXfPXJHE
< HTTP/1.1 200 OK
< Server: nginx/1.10.0
< Date: Thu, 10 Aug 2017 06:52:53 GMT
< Content-Type: text/html
< Expires: Thu, 10 Aug 2017 06:52:52 GMT
< Cache-Control: no-cache
< Cache-Control: no-cache
< Pragma: no-cache
< X-UA-Compatible: IE=Edge,chrome=1
< X-Lightspeed: suite
< X-Cache: MISS from lightspeed.ravennaschools.org
< Via: 1.1 lightspeed.ravennaschools.org (squid/3.3.13)
< Connection: keep-alive
* no chunk, no close, no size. Assume close to signal end
<
* Closing connection #0
)
If however the sole aim of this script is to increase the hit counter then you may need to rethink as that does not seem to be affected but perhaps the above will be of use.

sending Curl POSTFIELDS array

I am trying to use CURL to post the following fields to PANDADOCS, but for some reason I am getting an error that the values are not being received on their side.
This is the error I am getting:
"type": "validation_error", "detail": {"url": ["This field is required."], "name": ["This field is required."]}}
I am posting with the following:
$docurl = "myurl.com/document.pdf";
$headr = array();
$headr[] = 'Content-length: 0';
$headr[] = 'Content-Type: application/json;charset=UTF-8';
$headr[] = "Authorization: Bearer $ACCESS_TOKEN";
$url = 'https://api.pandadoc.com/public/v1/documents';
$ch = curl_init();
curl_setopt($ch, CURLOPT_HTTPHEADER,$headr);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, FALSE);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_USERAGENT, $useragent);
$postfields = array();
$postfields['name'] = 'PSA';
$postfields['url'] = $docurl;
$postfields['recipients'] = array ([0]=>array(
['email'] => ['dondon#gmail.com'],
['first_name'] => ['don'],
['last_name'] => ['jones'],
['role']=>['u1'] ));
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query( $postfields) );
$ret = curl_exec($ch); //
when I print_r($postfields)
I get
Array ( [name] => PSA [url] => https://api.pandadoc.com/public/v1/documents [recipients] => Array ( ) )
so all the fields arent getting posted.
but whats wierd is that the URL and NAME are in the array but not the other fields yet the error is complaining about not receiving NAME and URL..
dazed and confused...
* Hostname was found in DNS cache
* Trying 54.190.72.92...
* Connected to api.pandadoc.com (54.190.72.92) port 443 (#28)
* SSL connection using TLSv1.2 / ECDHE-RSA-AES256-GCM-SHA384
* Server certificate:
* subject: OU=GT83522468; OU=See www.rapidssl.com/resources/cps (c)14; OU=Domain Control Validated - RapidSSL(R); CN=*.pandadoc.com
* start date: 2014-11-09 00:32:24 GMT
* expire date: 2016-10-11 09:34:58 GMT
* subjectAltName: api.pandadoc.com matched
* issuer: C=US; O=GeoTrust Inc.; CN=RapidSSL SHA256 CA - G3
* SSL certificate verify result: unable to get local issuer certificate (20), continuing anyway.
> POST /public/v1/documents HTTP/1.1
User-Agent: Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US) AppleWebKit/533.2 (KHTML, like Gecko) Chrome/5.0.342.3 Safari/533.2
Host: api.pandadoc.com
Accept: */*
Content-length: 0
Content-Type: application/json;charset=UTF-8
Authorization: Bearer [ACCESS TOKEN]
* upload completely sent off: 37 out of 37 bytes
< HTTP/1.1 400 BAD REQUEST
* Server nginx/1.4.6 (Ubuntu) is not blacklisted
< Server: nginx/1.4.6 (Ubuntu)
< Date: Fri, 06 Mar 2015 19:52:53 GMT
< Content-Type: application/json
< Transfer-Encoding: chunked
< Connection: keep-alive
< Vary: Accept
< Allow: GET, POST, DELETE, HEAD, OPTIONS
<
* Connection #28 to host api.pandadoc.com left intact
$string is not defined.
Add
$string = http_build_query( $postfields );
after
$postfields = array();
$postfields['name'] = 'PSA';
$postfields['url'] = $docurl;
// This is invalid array
$postfields['recipients'] = array ([0]=>array(
['email'] => ['dondon#gmail.com'],
['first_name'] => ['don'],
['last_name'] => ['jones'],
['role']=>['u1'] ));
http://php.net/manual/en/function.http-build-query.php
UPDATE
I just read Pandadoc API. They accept json data and your data was invalid. Also content type.
This should work:
<?php
$url = 'https://api.pandadoc.com/public/v1/documents';
$docurl = "myurl.com/document.pdf";
$postfields = array();
$postfields['name'] = 'PSA';
$postfields['url'] = $docurl;
$postfields['recipients'] = array(
array(
'email' => 'dondon#gmail.com',
'first_name' => 'don',
'last_name' => 'jones',
'role' => 'u1'
)
);
$data_string = json_encode( $postfields );
$headr = array();
$headr[] = 'Content-length: '.strlen( $data_string );
$headr[] = 'Content-type: application/json';
$headr[] = "Authorization: Bearer $ACCESS_TOKEN";
$ch = curl_init( $url );
curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, true );
curl_setopt( $ch, CURLOPT_VERBOSE, 1 );
curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, false );
curl_setopt( $ch, CURLOPT_CUSTOMREQUEST, "POST" );
curl_setopt( $ch, CURLOPT_POSTFIELDS, $data_string );
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
curl_setopt( $ch, CURLOPT_HTTPHEADER, $headr );
$result = curl_exec( $ch );
?>

Error Sending XML file by CURL to WebServices

I'm trying to send by POST method a XML through of CURL to authenticated webServices, but for some reason the server is rejecting the XML file, me giving me an error 500, however another WebService than by GET method, not have problem. The following code is i'm trying.
<?php
$request_xml = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>
<FiltroLicitaciones xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">
<CantidadRegistro>10</CantidadRegistro>
<Texto>memo</Texto>
<CodigoRegion xsi:nil=\"true\" />
<CodigoEstado>1</CodigoEstado>
<TipoFecha>FechaPublicacion</TipoFecha>
<FechaDesde>2011-06-01T00:00:00</FechaDesde>
<FechaHasta>2011-08-01T00:00:00</FechaHasta>
</FiltroLicitaciones>";
//Initialize handle and set options
$username = 'user';
$password = 'pass';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://www.mercadopublico.cl/movil/licitaciones/porFecha');
//curl_setopt($ch, CURLOPT_URL, "http://localhost/server.php");
curl_setopt($ch, CURLOPT_USERPWD, $username.':'.$password);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 4);
curl_setopt($ch, CURLOPT_POSTFIELDS, $request_xml);
$result = curl_exec($ch);
curl_close($ch);
print_r($result);
?>
I don't know if will be a error for XML malformed, but server return me a random 500 error with the following header:
HTTP/1.1 500 The server encountered an error processing the request. Please see the server logs for more details.
Cache-Control: private
Content-Length: 1047
Content-Type: text/html
Server: Microsoft-IIS/7.5
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
Date: Mon, 30 Jul 2012 23:53:05 GMT
I did a test in the local server, for see as the data came, the following the result this is:
HTTP/1.1 200 OK
Date: Mon, 30 Jul 2012 23:41:50 GMT
Server: Apache/2.2.22 (Fedora)
X-Powered-By: PHP/5.3.14
Content-Length: 2450
Connection: close
Content-Type: text/html; charset=UTF-8
Array
(
[GLOBALS] => Array
*RECURSION*
[_POST] => Array
(
[<?xml version] => "1.0" encoding="utf-8" ?>
<FiltroLicitaciones xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<CantidadRegistro>10</CantidadRegistro>
<Texto>memo</Texto>
<CodigoRegion xsi:nil="true" />
<CodigoEstado>1</CodigoEstado>
<TipoFecha>FechaPublicacion</TipoFecha>
<FechaDesde>2011-06-01T00:00:00</FechaDesde>
<FechaHasta>2011-08-01T00:00:00</FechaHasta>
</FiltroLicitaciones>
)
[_GET] => Array
(
)
[_COOKIE] => Array
(
)
[_FILES] => Array
(
)
[_ENV] => Array
(
)
[_REQUEST] => Array
(
[<?xml version] => "1.0" encoding="utf-8" ?>
<FiltroLicitaciones xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<CantidadRegistro>10</CantidadRegistro>
<Texto>memo</Texto>
<CodigoRegion xsi:nil="true" />
<CodigoEstado>1</CodigoEstado>
<TipoFecha>FechaPublicacion</TipoFecha>
<FechaDesde>2011-06-01T00:00:00</FechaDesde>
<FechaHasta>2011-08-01T00:00:00</FechaHasta>
</FiltroLicitaciones>
)
[_SERVER] => Array
(
[HTTP_HOST] => localhost
[HTTP_ACCEPT] => */*
[CONTENT_LENGTH] => 469
[CONTENT_TYPE] => application/x-www-form-urlencoded
[PATH] => /usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
[SERVER_SIGNATURE] => <address>Apache/2.2.22 (Fedora) Server at localhost Port 80</address>
[SERVER_SOFTWARE] => Apache/2.2.22 (Fedora)
[SERVER_NAME] => localhost
[SERVER_ADDR] => ::1
[SERVER_PORT] => 80
[REMOTE_ADDR] => ::1
[DOCUMENT_ROOT] => /var/www/html
[SERVER_ADMIN] => root#localhost
[SCRIPT_FILENAME] => /var/www/html/server.php
[REMOTE_PORT] => 37712
[GATEWAY_INTERFACE] => CGI/1.1
[SERVER_PROTOCOL] => HTTP/1.1
[REQUEST_METHOD] => POST
[QUERY_STRING] =>
[REQUEST_URI] => /server.php
[SCRIPT_NAME] => /server.php
[PHP_SELF] => /server.php
[PHP_AUTH_USER] => user
[PHP_AUTH_PW] => pass
[REQUEST_TIME] => 1343691710
)
)
I hope can you help me.
Thanks.
Best Regards.
Well I'm not sure if the 500 error is from the xml but, as I see in your code the xml has no url variable :
myxml=<xml></xml>
Because as you can see from the response the url paramenter has become
[<?xml version] => "1.0" encoding="utf-8" ?>
and this is wrong.
If the api docs didn't specified any url parameters then you should probably set the right curl header :
curl_setopt($ch,CURLOPT_HTTPHEADER, Array("Content-Type: application/xml");
Like this the server knows what to expect
Note this part of your sample dump:
[_POST] => Array
(
[<?xml version]
Your XML data was interpreted as a form-type data upload, with a field name of <?xml version. This destroyed your XML's structure, leading to a parse error on the server you're submitting this to.
Read below url first i think this is very use full to you
Sending XML files to a Webservice (Using cURL)
http://softwaredevelopmentindia.wordpress.com/2007/07/09/sending-xml-files-to-a-webservice-using-curl/
or try this
Calling Web Services. Great fun!! … when it works. One of the biggest challenges is to send the XML document and get the response back, an XML document in particular. I have come up with a PHP function that hides all the necessary logic from theuser and handles the posting of the XML document and returns whatever the server responds. It relies on PHP’s cURL library (so you need it properly configured on your server in order to work). All you need to do is create the XML document, choose the URL (and port) to which you want to post the XML document and the function takes care of the rest. Below is the function code. As you can see, the function can handle SSL-enabled servers, something that provides a great advantage, since many Web services run on HTTPS.
// open a http channel, transmit data and return received buffer
function xml_post($post_xml, $url, $port)
{
$user_agent = $_SERVER[’HTTP_USER_AGENT’];
$ch = curl_init(); // initialize curl handle
curl_setopt($ch, CURLOPT_URL, $url); // set url to post to
curl_setopt($ch, CURLOPT_FAILONERROR, 1); // Fail on errors
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); // allow redirects
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1); // return into a variable
curl_setopt($ch, CURLOPT_PORT, $port); //Set the port number
curl_setopt($ch, CURLOPT_TIMEOUT, 15); // times out after 15s
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_xml); // add POST fields
curl_setopt($ch, CURLOPT_USERAGENT, $user_agent);
if($port==443)
{
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
}
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
The example below shows how the function works, by posting a XML document of the form
<?xml version=”1.0″ encoding=”iso-8859-1″?>
<Document>
<Message>
Your Name
</Message>
</Document>
to a “listener” script, which takes the XML document and returns a reply (another XML document). In this case, the listener is very simple. All it does is replace the “Message” tag with “Reply” and print the resulting XML. Of course, the listener can do all sorts of things in response to the POST.
<?php
if ( !isset( $HTTP_RAW_POST_DATA ) )
{
$HTTP_RAW_POST_DATA = file_get_contents( ‘php://input’ );
}
$xml = str_replace(”Message”,”Reply” , $HTTP_RAW_POST_DATA);
print((trim($xml)));
?>

Categories