PayPal IPN listener response - php

After fully testing in PayPal's sandbox and getting the process to work perfectly. I've taken it live and it's not working.
I'm receiving the POST data from PayPal via the notify_url. I then send it back to PayPal with cmd=_notify-validate infront of the data.
Using PayPals documented code, I'm using this to send the message to PayPal.
$header .= "POST /cgi-bin/webscr HTTP/1.0\r\n";
$header .= "Content-Type: application/x-www-form-urlencoded\r\n";
$header .= "Content-Length: " . strlen($req) . "\r\n\r\n";
$fp = fsockopen ('ssl://www.paypal.com', 443, $errno, $errstr, 30);
(using this code to get the response)
$res = stream_get_contents($fp, 1024);
The response I'm getting back is:
HTTP/1.1 200 OK
Date: Fri, 11 May 2012 20:51:28 GMT
X-Frame-Options: SAMEORIGIN
Set-Cookie: cwrClyrK4LoCV1fydGbAxiNL6iG=SdeBuKBN39mjr3w791CHr_MlSkoBdDmbxpQOjT_WOicyD_Sg6BYZm8koiEv2-5XBUkCjpXQwFqIxIQgIyo3e7arO8015CVw96dpne2CNjbgc1CvpDlqXn72IBWq%7cW7uYn6Za7ljG4iLtLVcyFoPk8gZD7sr_S8WjwZrZWD8UXzE7KAH3bll9TVik3wbdCFlrZG%7csxrZZHSH5SWBGfrKsIU6Dz-K43j4h37efIkWFcVJVER0ncRxNJ0wANN1Dp3pZpV2PLxC1m%7c1336769488; domain=.paypal.com; path=/; Secure; HttpOnly
Set-Cookie: cookie_check=yes; expires=Mon, 09-May-2022 20:51:28 GMT; domain=.paypal.com; path=/; Secure; HttpOnly
Set-Cookie: navcmd=_notify-validate; domain=.paypal.com; path=/; Secure; HttpOnly
Set-Cookie: navlns=0.0; expires=Thu, 06-May-2032 20:51:28 GMT; domain=.paypal.com; path=/; Secure; HttpOnly
Set-Cookie: Apache=10.73.8.50.1336769488653443; path=/; expires=Sun, 04-May-42 20:51:28 GMT
Vary: Accept-Encoding
Strict-Transport-Security: max-age=14400
Connection: close
Content-Type: text/html; charset=UTF-8
Set-Cookie: TSe9a623=bb3c8ce40a7f3f6d1c018255c9
What I'm not getting is the INVALID or VERIFIED response in this. This is the entire output from PayPal. In the sandbox, I was getting VERIFIED in the last line, and no Set-Cookie.
It seems weird that I'm not receiving an INVALID or VERIFIED response.
Any suggestions would be appreciated.

Did you write the request to the socket using fwrite/fputs? Also, judging by the length of that response, you may need to read more than 1024 bytes from the stream. That's getting awfully close.
You may want to read the response in a loop:
$resp = '';
while (!feof($fp)) {
$resp .= stream_get_contents($fp, 1024);
}
Then you can separate the headers from the body using:
list($headers, $response) = explode("\r\n\r\n", 2);

Related

php curl_setop url error

I have a
$result = curl_exec($ch)
the $ value is like that
HTTP/1.1 302 Found
Date: Wed, 18 Apr 2018 12:45:05 GMT
Set-Cookie: OAMAuthnHintCookie=0#1524055505; httponly; secure; path=/; domain=.test.com
Set-Cookie: OAMRequestContext_test.test.com:443_527635=Rv52rjM82f3htVYzT+Lp0g==;max-age=300; httponly; secure; path=/
Location: https://id.test.com/obrareq.cgi?encquery%3DE6zb4nAIzYfopY8L5SbbJJPLfvrkN7Y1RkKgv4%2FSzBKmT1cY%2BhRn0A3AhCDxGFIB10DLwLMp%2BcR40CHFKhdrh2aZcEck%2Bd2pzikJ3WzWCAo5LiVW8O3CGPVoeFXUBY2orJxN9zSZXNXkAzg%2F%2F2twT%2FS1ZIUlox8fyQrKf6mITSrqbgKhn5dcC5CR79rJDCO75VEIU472JptWmPlBlEkyFT1XRO%2BUzXQHUwui92%2FGCh34PbbDrPajiyU71ycb03ffcCt0Sl1tKVNw2S%2BsUe81VH1jgV8yLWXslvl2SzsqpQUcZVZdi80HEM2ppQTsvECX%2BiyWnZ49nVBxp3YqU4nlhkAIaNaEbTEpPVF%2FvCJSuHo%3D%20agentid%3DWgtest%20ver%3D1%20crmethod%3D2
Content-Length: 676
Cache-Control: max-age=0
Expires: Wed, 18 Apr 2018 12:45:05 GMT
I extract the location: url with:
preg_match('/(Location: https:\/\/id\.test\.com\/obrareq\.cgi\?encquery)(.*)/', $res, $location);
and put the result in $found:
$found=$location[2];
then I want to use this url in a new curl_setop
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,'https://id.test.com/obrareq.cgi?encquery'.$found);
......
but it doesn't give me any result.
If I do the same curl_setop with a manual copy of the url it works.
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,'https://id.test.com/obrareq.cgi?encquery%3DE6zb4nAIzYfopY8L5SbbJJPLfvrkN7Y1RkKgv4%2FSzBKmT1cY%2BhRn0A3AhCDxGFIB10DLwLMp%2BcR40CHFKhdrh2aZcEck%2Bd2pzikJ3WzWCAo5LiVW8O3CGPVoeFXUBY2orJxN9zSZXNXkAzg%2F%2F2twT%2FS1ZIUlox8fyQrKf6mITSrqbgKhn5dcC5CR79rJDCO75VEIU472JptWmPlBlEkyFT1XRO%2BUzXQHUwui92%2FGCh34PbbDrPajiyU71ycb03ffcCt0Sl1tKVNw2S%2BsUe81VH1jgV8yLWXslvl2SzsqpQUcZVZdi80HEM2ppQTsvECX%2BiyWnZ49nVBxp3YqU4nlhkAIaNaEbTEpPVF%2FvCJSuHo%3D%20agentid%3DWgtest%20ver%3D1%20crmethod%3D2y');
Any idea of what i did wrong?
......

Paypal IPN sends invalid response after successful payment completion

First thing first,
Language: PHP
Framework: Code Igniter
This is the first time I'm implementing PayPal payment in my website so that users can pay from their PayPal accounts to the owner. Obviously.
Tutorial I followed for implementing PayPal payment is here.
And for implementing IPN listener, I used this code.
I wrote IPN listener in core php and it's a standalone file (no relation with codeigniter framework or website). A cron job makes this file run 24x7. I thought that's necessary but not quite sure. So IPN listener listens every time and whenever PayPal sends an IPN, it takes the data from POST and checks the verification. If it is verified, it write the POST data to database and log a file accordingly.
This whole things was already a mess and I think I made it worse.
My IPN listener is:
<?php
require_once 'Query.php';
define("DEBUG", 1);
define("USE_SANDBOX", 1);
define("LOG_FILE", "./ipn.log");
$raw_post_data = str_replace('=utf-8', '=UTF-8', file_get_contents('php://input'));
$raw_post_array = explode('&', $raw_post_data);
$myPost = array();
foreach ($raw_post_array as $keyval) {
$keyval = explode ('=', $keyval);
if (count($keyval) == 2)
$myPost[$keyval[0]] = urldecode($keyval[1]);
}
// read the post from PayPal system and add 'cmd'
$req = 'cmd=_notify-validate';
foreach ($myPost as $key => $value)
{
$value = urlencode(stripslashes($value));
$req .= "&$key=$value";
}
if(USE_SANDBOX == true) {
$paypal_url = "https://www.sandbox.paypal.com/cgi-bin/webscr";
} else {
$paypal_url = "https://www.paypal.com/cgi-bin/webscr";
}
$ch = curl_init($paypal_url);
if ($ch == FALSE) {
return FALSE;
}
curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $req);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($ch, CURLOPT_FORBID_REUSE, 1);
if(DEBUG == true) {
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLINFO_HEADER_OUT, 1);
}
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Connection: Close'));
$res = curl_exec($ch);
if (curl_errno($ch) != 0) // cURL error
{
if(DEBUG == true) {
error_log(date('[Y-m-d H:i e] '). "Can't connect to PayPal to validate IPN message: " . curl_error($ch) . PHP_EOL, 3, LOG_FILE);
}
curl_close($ch);
exit;
} else {
// Log the entire HTTP response if debug is switched on.
if(DEBUG == true) {
error_log(date('[Y-m-d H:i e] '). "HTTP request of validation request:". curl_getinfo($ch, CURLINFO_HEADER_OUT) ." for IPN payload: $req" . PHP_EOL, 3, LOG_FILE);
error_log(date('[Y-m-d H:i e] '). "HTTP response of validation request: $res" . PHP_EOL, 3, LOG_FILE);
}
curl_close($ch);
}
// Inspect IPN validation result and act accordingly
// Split response headers and payload, a better way for strcmp
$tokens = explode("\r\n\r\n", trim($res));
$res = trim(end($tokens));
if (strcmp ($res, "VERIFIED") == 0) {
$user_id = $_POST['custom'];
$product_id = $_POST["item_number"];
$txn_id = $_POST["txn_id"];
$payment_gross = $_POST["mc_gross"];
$currency_code = $_POST["mc_currency"];
$payer_email = $_POST["payer_email"];
$payment_status = $_POST["payment_status"];
$qry2="INSERT INTO payments(user_id,product_id,txn_id,payment_gross,currency_code,payer_email,payment_status) VALUES(".$user_id.",".$product_id.",'".$txn_id."',".$payment_gross.",'".$currency_code."','".$payer_email."','".$payment_status."')" ;
setData($qry2);
if(DEBUG == true) {
error_log(date('[Y-m-d H:i e] '). "Verified IPN: $req ". PHP_EOL, 3, LOG_FILE);
}
} else if (strcmp ($res, "INVALID") == 0) {
// log for manual investigation
// Add business logic here which deals with invalid IPN messages
if(DEBUG == true) {
error_log(date('[Y-m-d H:i e] '). "Invalid IPN: $req" . PHP_EOL, 3, LOG_FILE);
}
}
?>
What I'm trying to say here is , if the condition if (strcmp ($res, "VERIFIED") == 0) is true, then only database write operation occurs and then I write to a log file using this error_log(date('[Y-m-d H:i e] '). "Verified IPN: $req ". PHP_EOL, 3, LOG_FILE);
I checked my log file and try to do a search for Verified IPN but couldn't find anything. Here is my IPN log.
[2016-03-07 05:41 UTC] HTTP request of validation request:POST /cgi-bin/webscr HTTP/1.1
Host: www.sandbox.paypal.com
Accept: */*
Connection: Close
Content-Length: 20
Content-Type: application/x-www-form-urlencoded
for IPN payload: cmd=_notify-validate
[2016-03-07 05:41 UTC] HTTP response of validation request: HTTP/1.1 200 OK
Date: Mon, 07 Mar 2016 05:41:03 GMT
Server: Apache
X-Frame-Options: SAMEORIGIN
Set-Cookie: c9MWDuvPtT9GIMyPc3jwol1VSlO=WKlHKpJ3laas07Yu1WCXQPNlPGNpVTmx79in33FVjVu-1QcqQ1BKO2BLcO-ltHCgRNg4BYmHLqdIeaKPMYLdWqa1qP3eqTtCdlN-erDGl_NuifHufy7yejBynYZJS7W8xkoFUHBVW5eQocb6f3uGTwoVGpYBHeWXRejcU1o37sflJyynvgzkWMzHuvsG7pS9t19ZcqfrldHnv8pYpTXlBa4UeWbyuEVWiyuTVhBDE_UlA1L7E-Ho8J-rui0BFKqOHVsalakqcz9xP1XbyfIjb2hLrtpDDFmkqNqTs2ibxlGO-EjNhcJG1boI06ISlT4Dg0ZfGPlthPobrKZ0aS59OCOTaGOYReArBWqdDZXWq0tDwI8uIJwMaFT9w0fproQ5167v1nWS6QIZYnXmeZCO40Ss93NQW2OTeLRaKx-1e92aGSL3uxSq_YdE5Dm; domain=.paypal.com; path=/; Secure; HttpOnly
Set-Cookie: cookie_check=yes; expires=Thu, 05-Mar-2026 05:41:03 GMT; domain=.paypal.com; path=/; Secure; HttpOnly
Set-Cookie: navcmd=_notify-validate; domain=.paypal.com; path=/; Secure; HttpOnly
Set-Cookie: navlns=0.0; expires=Wed, 07-Mar-2018 05:41:03 GMT; domain=.paypal.com; path=/; Secure; HttpOnly
Set-Cookie: Apache=10.72.108.11.1457329263101875; path=/; expires=Wed, 28-Feb-46 05:41:03 GMT
Vary: Accept-Encoding,User-Agent
Connection: close
HTTP_X_PP_AZ_LOCATOR: sandbox.slc
Paypal-Debug-Id: d4da8be813fa0
Set-Cookie: X-PP-SILOVER=name%3DSANDBOX3.WEB.1%26silo_version%3D1880%26app%3Dappdispatcher%26TIME%3D1863638358; domain=.paypal.com; path=/; Secure; HttpOnly
Set-Cookie: X-PP-SILOVER=; Expires=Thu, 01 Jan 1970 00:00:01 GMT
Strict-Transport-Security: max-age=14400
Transfer-Encoding: chunked
Content-Type: text/html; charset=UTF-8
INVALID
[2016-03-07 05:41 UTC] Invalid IPN: cmd=_notify-validate
[2016-03-07 05:42 UTC] HTTP request of validation request:POST /cgi-bin/webscr HTTP/1.1
Host: www.sandbox.paypal.com
Accept: */*
Connection: Close
Content-Length: 20
Content-Type: application/x-www-form-urlencoded
for IPN payload: cmd=_notify-validate
[2016-03-07 05:42 UTC] HTTP response of validation request: HTTP/1.1 200 OK
Date: Mon, 07 Mar 2016 05:42:02 GMT
Server: Apache
X-Frame-Options: SAMEORIGIN
Set-Cookie: c9MWDuvPtT9GIMyPc3jwol1VSlO=f8rnnKoWpS27ajK43K_vGgiHMCbyL0kxcaLbl_qXj8X0JLk-LbcHgcR3owKzLqj_MJu_uo7CX7WOoie45aYro6IcO7wJJlXCvHm90MzDnGfwXjHYddOtovs9ZRpPcmiQ2o7Rxw6UhyVsaQ3stNXCFJ2RXouWssYRY8YTDST6VyVJWdtPzSIe24BebKqH2B1jbPOt_VJ1xhLRb_fmVpR6CB4ScN9fhgNdkyueDqEfp3o-xbT-VzHbfuTdSR3p2vvKKAVFBOs7ooDFmIylSOkxNkrBhvR2UwkGcpOo9HOBYWpqkfn2TlLBW6W1PpKSGnzY5M8TxaA-a1HtkKVMQ6TN4vyc46B7Ekps0ZLO3vtt9arFvvscgRMxOPGcQvwsGYrGHQv4Vyv_m47hrRRojf-yBdmebyhugsUKYSBjUSPiFDi5Ozg2inODpq0o0vC; domain=.paypal.com; path=/; Secure; HttpOnly
Set-Cookie: cookie_check=yes; expires=Thu, 05-Mar-2026 05:42:03 GMT; domain=.paypal.com; path=/; Secure; HttpOnly
Set-Cookie: navcmd=_notify-validate; domain=.paypal.com; path=/; Secure; HttpOnly
Set-Cookie: navlns=0.0; expires=Wed, 07-Mar-2018 05:42:03 GMT; domain=.paypal.com; path=/; Secure; HttpOnly
Set-Cookie: Apache=10.72.108.11.1457329322876295; path=/; expires=Wed, 28-Feb-46 05:42:02 GMT
Vary: Accept-Encoding,User-Agent
Connection: close
HTTP_X_PP_AZ_LOCATOR: sandbox.slc
Paypal-Debug-Id: ec94240d19c4
Set-Cookie: X-PP-SILOVER=name%3DSANDBOX3.WEB.1%26silo_version%3D1880%26app%3Dappdispatcher%26TIME%3D2853494102; domain=.paypal.com; path=/; Secure; HttpOnly
Set-Cookie: X-PP-SILOVER=; Expires=Thu, 01 Jan 1970 00:00:01 GMT
Strict-Transport-Security: max-age=14400
Transfer-Encoding: chunked
Content-Type: text/html; charset=UTF-8
INVALID
[2016-03-07 05:42 UTC] Invalid IPN: cmd=_notify-validate
[2016-03-07 05:43 UTC] HTTP request of validation request:POST /cgi-bin/webscr HTTP/1.1
Host: www.sandbox.paypal.com
Accept: */*
Connection: Close
Content-Length: 20
Content-Type: application/x-www-form-urlencoded
for IPN payload: cmd=_notify-validate
[2016-03-07 05:43 UTC] HTTP response of validation request: HTTP/1.1 200 OK
Date: Mon, 07 Mar 2016 05:43:02 GMT
Server: Apache
X-Frame-Options: SAMEORIGIN
Set-Cookie: c9MWDuvPtT9GIMyPc3jwol1VSlO=qFIftmj81M9XVbnGK-_ZFd_plIa-_hITqhkt7tHsSgU2hJnYg1P7b2xqdRFTOWeXIJnXWMBBwbAOFwF1azF07vQ_StCVY9SfONsm83OIv3S8WCTk9ekaXS6owbCFW4qVLtyDKxaKfNkLU576_BYmAFXULVJ3pAkLeGFUkzNC9kjY5ouHRKu3bzO7eSHrRpgQHnBQdoI6NcTHh697bQfeGAfFYpMIXDbYHEiSpaKm22v0j7hS4A_nntlaxbwrrRoZtZmTuoJdQNKF3wS26pJJkM4zYWpdY8xP21vISCk9sAAQjIOZCspps1tTjsXhDI4nYUZeJNjqG8xshBqB_lFweeqCQQC17MEivchn19F32ojFh--lfsp3cZA9YY34RBjxL1TnY-owkzw9n3qHpn-tnVP6--DgtJ-H3AqF0Q6QS3gCFam3tlNd5TEi9z0; domain=.paypal.com; path=/; Secure; HttpOnly
Set-Cookie: cookie_check=yes; expires=Thu, 05-Mar-2026 05:43:03 GMT; domain=.paypal.com; path=/; Secure; HttpOnly
Set-Cookie: navcmd=_notify-validate; domain=.paypal.com; path=/; Secure; HttpOnly
Set-Cookie: navlns=0.0; expires=Wed, 07-Mar-2018 05:43:03 GMT; domain=.paypal.com; path=/; Secure; HttpOnly
Set-Cookie: Apache=10.72.108.11.1457329382840458; path=/; expires=Wed, 28-Feb-46 05:43:02 GMT
Vary: Accept-Encoding,User-Agent
Connection: close
HTTP_X_PP_AZ_LOCATOR: sandbox.slc
Paypal-Debug-Id: 8ad4234c9398
Set-Cookie: X-PP-SILOVER=name%3DSANDBOX3.WEB.1%26silo_version%3D1880%26app%3Dappdispatcher%26TIME%3D3860127062; domain=.paypal.com; path=/; Secure; HttpOnly
Set-Cookie: X-PP-SILOVER=; Expires=Thu, 01 Jan 1970 00:00:01 GMT
Strict-Transport-Security: max-age=14400
Transfer-Encoding: chunked
Content-Type: text/html; charset=UTF-8
INVALID
[2016-03-07 05:43 UTC] Invalid IPN: cmd=_notify-validate
There's nothing like 'Verified' in it and log file has 'INVALID' in it that means
error_log(date('[Y-m-d H:i e] '). "Invalid IPN: $req" . PHP_EOL, 3, LOG_FILE);
this function gets executed. BUT DATA IS WRITTEN INTO DATABASE ALSO.
I don't what's wrong here. Can anyone point out the mistakes? Should I take any additional security measures? Thanks. Gracias.
public function success()
{
if(isset($_GET['tx']))
{
$tx = $_GET['tx'];
$result=$this->verifyWithPayPal($tx);
// $this->load->view('success',$result);
}
}
public function verifyWithPayPal($tx)
{
// $tx = $_REQUEST['tx'];
$token = $this->config->item('authtokan');
$paypal_url = $this->config->item('posturl').'?cmd=_notify-synch&tx='. $tx.'&at='.$token;
$curl= curl_init($paypal_url);
$data=array(
"cmd"=>"_notify-synch",
"tx"=>$tx,
"at"=>$token
);
$data_string=json_encode($data);
curl_setopt($curl,CURLOPT_HEADER, 0);
curl_setopt($curl,CURLOPT_POST, 1);
curl_setopt($curl,CURLOPT_POSTFIELDS,$data_string);
curl_setopt($curl,CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($curl,CURLOPT_RETURNTRANSFER,1);
$headers= array(
'Content-Type:application/x-www-form-urlencoded',
'Host: www.sandbox.paypal.com',
'Connection: close'
);
curl_setopt($curl,CURLOPT_HTTP_VERSION,CURL_HTTP_VERSION_1_1);
curl_setopt($curl,CURLOPT_HTTPHEADER, $headers);
$response= curl_exec($curl);
$lines= explode("\n", $response);
$keyarray = array();
if(strcmp($lines[0],"SUCCESS")==0){
for($i=1;$i<count($lines)-1; $i++){
list($key,$val)=explode("=",$lines[$i]);
$keyarray[urldecode($key)]=urldecode($val);
}
$this->getListProducts($keyarray);
}
}
public function getListProducts($result)
{
$i=1;
$data = array();
// echo "<pre>";
// print_r($result);
// echo "</pre>";
foreach($result as $key => $value)
{
if(0===strpos($key,'item_number')){
$product = array(
'first_name' => $result['first_name'],
'last_name' => $result['last_name'],
'receiver_email' => $result['receiver_email'],
'txn_type' => $result['txn_type'],
'txn_id' => $result['txn_id'],
'payment_date' => $result['payment_date'],
'payer_id' => $result['payer_id'],
'payer_email' => $result['payer_email'],
'address_street' => $result['address_street'],
'address_zip' => $result['address_zip'],
'address_status' => $result['address_status'],
'address_country_code' => $result['address_country_code'],
'address_name' => $result['address_name'],
'address_country' => $result['address_country'],
'address_city' => $result['address_city'],
'address_state' => $result['address_state'],
'receiver_id' => $result['receiver_id'],
'receiver_email' => $result['receiver_email'],
'item_number' => $result['item_number1'],
'item_name' => $result['item_name1'],
'quantity' => $result['quantity1'],
'mc_currency' => $result['mc_currency'],
'mc_fee' => $result['mc_fee'],
'mc_gross' => $result['mc_gross_1'],
'payment_gross' => $result['payment_gross']
);
$this->load->model('mdl_order');
$this->mdl_order->insert_record($product);
// echo "alert<script>successfully Transaction</script>";
if(isset($product)){
//echo 'hello';
$time=$this->session->userdata('last_time');
// echo $time;
//$data=array( $time=$this->session->userdata('last_time'));
$this->load->model('mdl_order');
$this->mdl_order->update($time);
echo "success update";
}
// redirect('manage_order');
$this->load->view('success',$product);
}
}
return $data;
}

curl: keep cookies while being redirected

I use this code (originally found login into webpage with php with cURL) to first grab the csrf token, create cookie, and than use that csrf token and cookie in a subsequent post request. It doesn't work(deduced from how the final webpage looks) and I think it's because the FOLLOWLOCATION is set to true. It must be set to true, because there are some redirections going on, but redirections also bring the consequence of "misplacing" cookies. The question is..how to keep cookies while being redirected as a response from server.
$cookie = 'cookies2.txt';
# Initialize a cURL session.
$ch = curl_init('https://example.com/login');
# Set the cURL options.
$options = [
CURLOPT_COOKIEJAR => $cookie,
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_USERAGENT => $useragent,
CURLOPT_COOKIESESSION => true,
CURLINFO_HEADER_OUT => true,
CURLOPT_HEADER=>1
];
# Set the options
curl_setopt_array($ch, $options);
# Execute
$html = curl_exec($ch);
$request = curl_getinfo($ch, CURLINFO_HEADER_OUT);
echo "1.Request sent: $request<br>";
$headerSizeFirst = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
$headersFirst = substr($html, 0, $headerSizeFirst);
echo "1.Request recieved: $headersFirst";
$dom = pQuery::parseStr($html);
$csrfToken = $dom->query('[name="csrf"]')->val();
$postData = [
'csrf' => $csrfToken,
'username' => $email,
'password' => $password
...........
];
# Convert the post data array to URL encoded string
$postDataStr = http_build_query($postData);
$options[CURLOPT_POST] = 1;
$options[CURLOPT_POSTFIELDS] = $postDataStr;
$options[CURLOPT_HEADER]=1;
$options[CURLOPT_COOKIEJAR]=$cookie;
$options[CURLOPT_FOLLOWLOCATION] = true;
$options[CURLOPT_RETURNTRANSFER] = true;
$options[CURLOPT_USERAGENT] = $useragent;
$options[CURLINFO_HEADER_OUT] => true,
curl_setopt_array($ch, $options);
# Execute
$response = curl_exec($ch);
$request = curl_getinfo($ch, CURLINFO_HEADER_OUT);
echo "2. Request sent: $request<br>";
$headerSize = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
$headers = substr($response, 0, $headerSize);
echo "2. Request recieved: $headers<br>";
echo $response;
/////// HEADER OUT AND IN DATA
1.Request sent: GET /login HTTP/1.1 Host: example.com User-Agent: Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.5; en-US; rv:1.9.2.3) Gecko/20100401 Firefox/3.6.3 Accept: */*
1.Request recieved: HTTP/1.1 200 OK Accept-Ranges: bytes Age: 0 Cache-Control: no-cache Content-Type: text/html; charset=UTF-8 Date: Tue, 09 Feb 2016 13:34:02 GMT Server: nginx Set-Cookie: ____ri=4485; expires=Thu, 17-Mar-16 01:34:01 GMT; path=/; domain=.example.com Set-Cookie: PHPSESSID=dk7n4kcrigi54q081tr1evd5a2; path=/; domain=.example.com Set-Cookie: ts1=11e2bb0a86bfb9669c361cc407e1e3b3decefcce; expires=Fri, 06-Feb-2026 13:34:01 GMT; path=/; domain=.example.com Set-Cookie: session=eyJpdiI6Im9cL1wvcWVUUEhDVWY5cnF2QnZzVDRIaElPWitIQmc4RVI3N1M2SGxsY3hUTT0iLCJ2YWx1ZSI6InZjVFBnelNlMmxuaXpVNlpGb2d0TzNoM21NXC85dG43cVpmbUZkQ1VuOHlnU1VOXC9XWDJaWTcxckZ2OWpZY093REd1WmZEd21FQURQNnQ3NDltMmU0NnZMWm9vSE40YmV0VG1WYkpndE9DNTdEUE4wSkp5Q1BWMXJGaFdmMHV5N0NWRmZoVHFnT0JtY1VnYjJ6N29UZkxvQThRWG9KWFV3Q0k4azdibEZvVGwrcFJRaXdaQVV4OXZLaWlDVVpmeVREc3k3cW1MOTdTdHEyY1FlZ2Vuc09WWHFOanNOTjlnK1c0SStuTWhoU0VBWGxsY1ZqRExTblBOWllpeDNqaHhZNSIsIm1hYyI6IjllMWNhMzU3NTVjYTA4NWIwZTQ0NTYxMzA3ZmIzMTAxMWE5NDg0NzZlMTNmZTc2NjhhNDI2M2ZmZDMwMzgwY2QifQ%3D%3D; expires=Fri, 19-Feb-2016 13:34:02 GMT; path=/; domain=.example.com; httponly Vary: Accept-Encoding Vary: Accept-Encoding, Accept-Encoding X-Cache: Miss X-Frame-Options: SAMEORIGIN Content-Length: 51381 Connection: keep-alive
2. Request sent: GET /inx/aeGDrYQ HTTP/1.1 Host: example.com User-Agent: Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.5; en-US; rv:1.9.2.3) Gecko/20100401 Firefox/3.6.3 Accept: */* Cookie: PHPSESSID=t762fd0nbi1bp3hrgb9sgc3k20; ____ri=4485; safemode=1; session=eyJpdiI6Im1HQzlNR1JhMTNDc0JRelYyRVwveUp6N0JxZG56Z2p5K094eSs3YU5HQ3dzPSIsInZhbHVlIjoiVXBPYzN4TVNReURhVnMxQlZ1TndLZ0dYUjltbUVEcW11bkJJMDdMRVZoZ0hHMjRXZ2p6azlcL1FWXC93NnZWN3oreDcxQms3aGlcL3l0MG1vTjd1V21FcmVCVzFnQjVuMUY5dHBWeUlTbU9NSjJcL1d5TlwvTW11ZWp1eHpNd3d4eFZTamV6aThsNldkdlN3aFo0XC9sTnVnU0tXVDRKbWVBU25VU0hJaDREQ1J5M2xDXC9zRUc5OXhWMWJWWG9jYndhczYyZW4xMkUxb3BoU3FmQmMrNVdzM3RqQmgzeHY1NVJ5RXRTNGZOdmQ4dTRCbmRtWVZBN210QVVEVk1BNTFPc1NQcFU3bnd4NEpKbnRaTFliRWNzbkZaXC9YWUF1Nld1ekZSbjVGRXBuZzNoRlBNND0iLCJtYWMiOiI4OWEwNmMyZGVkYjFiYTlmNDY0MDE5MTQwNzE1YzNhYWJjYTA5YjI3MWMyZjgwMTViN2MyYmI0OWUyNmMwNjM0In0%3D; toastMsg=2; ts1=11e2bb0a86bfb9669c361cc407e1e3b3decefcce
2. Request recieved: HTTP/1.1 302 Found Accept-Ranges: bytes Age: 0 Cache-Control: no-cache, private Content-Type: text/html; charset=UTF-8 Date: Tue, 09 Feb 2016 13:34:04 GMT location: http://example.com/inx/aeGDrYQ Server: nginx Set-Cookie: PHPSESSID=thrn81mu7584dvp2ek9tpde8f4; expires=Thu, 09-Feb-2017 13:34:03 GMT; path=/; domain=.example.com Set-Cookie: PHPSESSID=t762fd0nbi1bp3hrgb9sgc3k20; expires=Thu, 09-Feb-2017 13:34:03 GMT; path=/; domain=.example.com Set-Cookie: session=eyJpdiI6Im1HQzlNR1JhMTNDc0JRelYyRVwveUp6N0JxZG56Z2p5K094eSs3YU5HQ3dzPSIsInZhbHVlIjoiVXBPYzN4TVNReURhVnMxQlZ1TndLZ0dYUjltbUVEcW11bkJJMDdMRVZoZ0hHMjRXZ2p6azlcL1FWXC93NnZWN3oreDcxQms3aGlcL3l0MG1vTjd1V21FcmVCVzFnQjVuMUY5dHBWeUlTbU9NSjJcL1d5TlwvTW11ZWp1eHpNd3d4eFZTamV6aThsNldkdlN3aFo0XC9sTnVnU0tXVDRKbWVBU25VU0hJaDREQ1J5M2xDXC9zRUc5OXhWMWJWWG9jYndhczYyZW4xMkUxb3BoU3FmQmMrNVdzM3RqQmgzeHY1NVJ5RXRTNGZOdmQ4dTRCbmRtWVZBN210QVVEVk1BNTFPc1NQcFU3bnd4NEpKbnRaTFliRWNzbkZaXC9YWUF1Nld1ekZSbjVGRXBuZzNoRlBNND0iLCJtYWMiOiI4OWEwNmMyZGVkYjFiYTlmNDY0MDE5MTQwNzE1YzNhYWJjYTA5YjI3MWMyZjgwMTViN2MyYmI0OWUyNmMwNjM0In0%3D; expires=Fri, 19-Feb-2016 13:34:04 GMT; path=/; domain=.example.com; httponly Set-Cookie: toastMsg=2; expires=Fri, 08-Feb-2019 13:34:04 GMT; path=/; domain=.example.com Set-Cookie: unverified=deleted; expires=Thu, 01-Jan-1970 00:00:01 GMT; path=/; domain=.example.com; httponly Set-Cookie: safemode=1; expires=Fri, 19-Feb-2016 13:34:04 GMT; path=/; domain=.example.com Set-Cookie: cacheableGrace=deleted; expires=Thu, 01-Jan-1970 00:00:01 GMT; path=/; domain=.example.com; httponly X-Cache: Miss X-Frame-Options: SAMEORIGIN Content-Length: 0 Connection: keep-alive HTTP/1.1 200 OK Age: 0 Cache-Control: max-age=0, public, s-maxage=60 Content-Type: text/html; charset=UTF-8 Date: Tue, 09 Feb 2016 13:34:05 GMT Server: nginx Vary: Accept-Encoding Vary: Accept-Encoding X-Cache: Miss X-Cacheable: Yes X-Frame-Options: SAMEORIGIN transfer-encoding: chunked Connection: keep-alive
CURLOPT_COOKIESESSION set to true means you tell libcurl to treat this as a new (cookie) session and it will discard all session cookies at start of a request. You should probably not set that without being really sure that's what you need as it will flush all cookies without a specific expiry date/time.
Otherwise, when the cookie engine has been activated in libcurl it will keep the cookies associated with the handle and reuse them in subsequent requests done with that same handle.

Paypal IPN verified problems

I'm experiencing some problems with my paypal ipn script:
$req = 'cmd=_notify-validate';
foreach ($_POST as $key => $value) {
$value = urlencode(stripslashes($value));
$req .= "&$key=$value";
}
// post back to PayPal system to validate
$header = '';
$header = "POST /cgi-bin/webscr HTTP/1.1\r\n";
$header .= "Content-Type: application/x-www-form-urlencoded\r\n";
$header .= "Host: www.paypal.com\r\n";
$header .= "Connection: close\r\n";
$header .= "Content-Length: " . strlen($req) . "\r\n\r\n";
$fp = fsockopen('ssl://www.paypal.com', 443, $errno, $errstr, 30);
if (!$fp) {
// HTTP ERROR
}
else {
fputs ($fp, $header . $req);
$response = '';
while (!feof($fp)) {
$res = fgets ($fp, 1024);
$res = trim($res);
if (strpos($res,'VERIFIED') !== false) {
}
else {
// not verified
}
}
}
if (strpos($res,'VERIFIED') !== false) is always false.
This is what $res returns:
HTTP/1.1 200 OK
Server: Apache
X-Frame-Options: SAMEORIGIN
Strict-Transport-Security: max-age=14400
Strict-Transport-Security: max-age=14400
Content-Type: text/html; charset=UTF-8
DC: slc-a-origin-www-1.paypal.com
Date: Thu, 27 Feb 2014 20:50:47 GMT
Content-Length: 8
Connection: close
Set-Cookie: cwrClyrK4LoCV1fydGbAxiNL6iG=KVmAID_U9eq9TG0lkX119TL840BG6Xau98CeIZX3jTQTx9a4uGno9gxDJGS6VrX8CoBQnj9_n7cUnfeLjb8bD_pyJvE1_XJY5j-Sl5dVIROlu-Cn3_PmfiwL1S0RB-hCOCJzLNIzLsV7H4_xyZg7u4eCzBKTZdlfRru95teI1r2A2tFCtNcYgejjmUHfHzy4nSMco604T_4OJZX_6PvoheXYKqj8tOR_hNW_s3057XoT0wbqzwWA0YI00DZRoRocUuY77_hR6THpxJ6ZnekN3nrdsh74z4XvF39eaf2kdQLGKArjel4sFCAFtmO0NkVQs7VOM_upvhbruJQdm94oOue4UWUpx2NQMUE2JWYNgrgUaBliTrzbFgWOLFidJ1bNJoopcthU5nDUFDXDka7_JSRL44rPMWS0o0kLQIZDnfTiVqhdZsnWNT6wxH4; domain=.paypal.com; path=/; Secure; HttpOnly
Set-Cookie: cookie_check=yes; expires=Sun, 25-Feb-2024 20:50:47 GMT; domain=.paypal.com; path=/; Secure; HttpOnly
Set-Cookie: navcmd=_notify-validate; domain=.paypal.com; path=/; Secure; HttpOnly
Set-Cookie: navlns=0.0; expires=Sat, 27-Feb-2016 20:50:47 GMT; domain=.paypal.com; path=/; Secure; HttpOnly
Set-Cookie: Apache=10.73.8.134.1393534247185146; path=/; expires=Sat, 20-Feb-44 20:50:47 GMT
Set-Cookie: X-PP-SILOVER=name%3DLIVE5.WEB.1%26silo_version%3D880%26app%3Dslingshot%26TIME%3D665128787; domain=.paypal.com; path=/; Secure; HttpOnly
Set-Cookie: X-PP-SILOVER=; Expires=Thu, 01 Jan 1970 00:00:01 GMT
Set-Cookie: Apache=10.73.8.46.1393534247177026; path=/; expires=Sat, 20-Feb-44 20:50:47 GMT
Set-Cookie: AKDC=slc-a-origin-www-1.paypal.com; expires=Thu, 27-Feb-2014 21:20:47 GMT; path=/; secure
A few possible things, based off a working example I'm using...
You might be running into serialization issues.
You're posting back to ssl://www.paypal.com instead of https://www.paypal.com/cgi-bin/webscr
There may be a problem with the way you're checking for verification? My example uses strcmp() instead of strpos()
// read raw POST data to prevent serialization issues w/ $_POST
$raw_post_data = file_get_contents('php://input');
$raw_post_array = explode('&', $raw_post_data);
$myPost = array();
foreach ($raw_post_array as $keyval) {
$keyval = explode ('=', $keyval);
if (count($keyval) == 2)
$myPost[$keyval[0]] = urldecode($keyval[1]);
}
// read the post from PayPal system and add 'cmd'
$req = 'cmd=_notify-validate';
foreach ($myPost as $key => $value) {
if (get_magic_quotes_gpc()) {
$value = urlencode(stripslashes($value));
} else {
$value = urlencode($value);
}
$req .= "&$key=$value";
}
// Post IPN back to PayPal to validate the IPN data is genuine
$paypal_url = 'https://www.paypal.com/cgi-bin/webscr';
$ch = curl_init($paypal_url);
if ($ch == false) {
return false;
}
curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $req);
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'));
// CONFIG: Please download 'cacert.pem' from "http://curl.haxx.se/docs/caextract.html" and set the directory path
// of the certificate as shown below. Ensure the file is readable by the webserver.
// This is mandatory for some environments.
// $cert = __DIR__ . "./cacert.pem";
// curl_setopt($ch, CURLOPT_CAINFO, $cert);
$res = curl_exec($ch);
curl_close($ch);
// Inspect IPN validation result and act accordingly
if (strcmp($res, "VERIFIED") == 0) {
// good to go...
}
References:
https://developer.paypal.com/webapps/developer/docs/classic/products/instant-payment-notification/
http://paypal.github.io/sdk/sample-apps/

PHP/cURL: Unable to remote login

I am trying to login to a system (which happens to be using the SquirrelMail client) using cURL and I'm having trouble.
Here is my relevant PHP code:
$handle = curl_init();
curl_setopt($handle, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($handle, CURLOPT_URL, $url);
curl_setopt($handle, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($handle, CURLOPT_POST, true);
curl_setopt($handle, CURLOPT_POSTFIELDS, "login_username=myusername&secretkey=mypass&js_autodetect_results=0");
$output = curl_exec($handle);
curl_close($handle);
print $output;
And when I try running it, the page comes back with a message saying I must be logged in to access it. Digging into the this login file (redirect.php if you are familiar with SquirrelMail), I see this error comes up when the variable login_username is not defined.
Here is my curl verbose output:
* About to connect() to www.cwazy.net port 80 (#0)
* Trying 72.18.206.197... * connected
* Connected to www.cwazy.net (72.18.206.197) port 80 (#0)
> POST /wi/sm/src/redirect.php HTTP/1.1
Host: www.cwazy.net
Accept: */*
Content-Length: 64
Content-Type: application/x-www-form-urlencoded
< HTTP/1.1 302 Found
< Date: Sun, 10 Jan 2010 06:51:34 GMT
< Server: Apache/2.2.9 (Debian) PHP/5.2.6-1+lenny3 with Suhosin-Patch mod_ssl/2.2.9 OpenSSL/0.9.8g
< X-Powered-By: PHP/5.2.6-1+lenny3
< Set-Cookie: SQMSESSID=b39c5dcf6e96309ac98b08b8f4f42374; path=/wi/sm/
< Expires: Thu, 19 Nov 1981 08:52:00 GMT
< Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0
< Pragma: no-cache
< Set-Cookie: SQMSESSID=b39c5dcf6e96309ac98b08b8f4f42374; path=/wi/sm/; HttpOnly
< Set-Cookie: SQMSESSID=b39c5dcf6e96309ac98b08b8f4f42374; path=/wi/sm/; HttpOnly
< Set-Cookie: SQMSESSID=b39c5dcf6e96309ac98b08b8f4f42374; path=/wi/sm/; HttpOnly
< Set-Cookie: SQMSESSID=b39c5dcf6e96309ac98b08b8f4f42374; path=/wi/sm/; HttpOnly
< Set-Cookie: SQMSESSID=b39c5dcf6e96309ac98b08b8f4f42374; path=/wi/sm/; HttpOnly
< Set-Cookie: squirrelmail_language=en_US; expires=Tue, 09-Feb-2010 06:51:34 GMT; path=/wi/sm/; HttpOnly
< Set-Cookie: SQMSESSID=6d70837e874750f37df81f0aaaa48618; path=/wi/sm/
< Set-Cookie: SQMSESSID=6d70837e874750f37df81f0aaaa48618; path=/wi/sm/; HttpOnly
< Set-Cookie: SQMSESSID=6d70837e874750f37df81f0aaaa48618; path=/wi/sm/; HttpOnly
< Set-Cookie: SQMSESSID=6d70837e874750f37df81f0aaaa48618; path=/wi/sm/; HttpOnly
< Set-Cookie: SQMSESSID=6d70837e874750f37df81f0aaaa48618; path=/wi/sm/; HttpOnly
< Set-Cookie: SQMSESSID=6d70837e874750f37df81f0aaaa48618; path=/wi/sm/; HttpOnly
< Set-Cookie: key=S9ZRyTL%2B; path=/wi/sm/; HttpOnly
< Set-Cookie: SQMSESSID=6d70837e874750f37df81f0aaaa48618; path=/wi/sm/; HttpOnly
< Set-Cookie: SQMSESSID=6d70837e874750f37df81f0aaaa48618; path=/wi/sm/; HttpOnly
< Set-Cookie: SQMSESSID=6d70837e874750f37df81f0aaaa48618; path=/wi/sm/; HttpOnly
< Set-Cookie: SQMSESSID=6d70837e874750f37df81f0aaaa48618; path=/wi/sm/; HttpOnly
< Set-Cookie: SQMSESSID=6d70837e874750f37df81f0aaaa48618; path=/wi/sm/; HttpOnly
< Set-Cookie: SQMSESSID=6d70837e874750f37df81f0aaaa48618; path=/wi/sm/; HttpOnly
< Set-Cookie: SQMSESSID=6d70837e874750f37df81f0aaaa48618; path=/wi/sm/; HttpOnly
< Set-Cookie: SQMSESSID=6d70837e874750f37df81f0aaaa48618; path=/wi/sm/; HttpOnly
< Set-Cookie: SQMSESSID=6d70837e874750f37df81f0aaaa48618; path=/wi/sm/; HttpOnly
< Set-Cookie: SQMSESSID=6d70837e874750f37df81f0aaaa48618; path=/wi/sm/; HttpOnly
< Location: webmail.php
< Content-Length: 0
< Content-Type: text/html; charset=iso-8859-1
<
* Connection #0 to host www.cwazy.net left intact
* Issue another request to this URL: 'http://www.cwazy.net/wi/sm/src/webmail.php'
* Violate RFC 2616/10.3.3 and switch from POST to GET
* Re-using existing connection! (#0) with host www.cwazy.net
* Connected to www.cwazy.net (72.18.206.197) port 80 (#0)
> GET /wi/sm/src/webmail.php HTTP/1.1
Host: www.cwazy.net
Accept: */*
< HTTP/1.1 200 OK
< Date: Sun, 10 Jan 2010 06:51:40 GMT
< Server: Apache/2.2.9 (Debian) PHP/5.2.6-1+lenny3 with Suhosin-Patch mod_ssl/2.2.9 OpenSSL/0.9.8g
< X-Powered-By: PHP/5.2.6-1+lenny3
< Set-Cookie: SQMSESSID=a6e32d5f2bd7a2ccca51edd2aa4ea143; path=/wi/sm/
< Expires: Thu, 19 Nov 1981 08:52:00 GMT
< Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0
< Pragma: no-cache
< Set-Cookie: SQMSESSID=a6e32d5f2bd7a2ccca51edd2aa4ea143; path=/wi/sm/; HttpOnly
< Set-Cookie: SQMSESSID=a6e32d5f2bd7a2ccca51edd2aa4ea143; path=/wi/sm/; HttpOnly
< Set-Cookie: SQMSESSID=a6e32d5f2bd7a2ccca51edd2aa4ea143; path=/wi/sm/; HttpOnly
< Content-Length: 1154
< Content-Type: text/html; charset=iso-8859-1
<
* Connection #0 to host www.cwazy.net left intact
* Closing connection #0
Any ideas?
the initial POST returns the cookie:
Set-Cookie: SQMSESSID=6d70837e874750f37df81f0aaaa48618
but this cookie is not sent by the client on the next GET request. sm doesn't see any session and tries to create a new one with a new id:
Set-Cookie: SQMSESSID=a6e32d5f2bd7a2ccca51edd2aa4ea143
to fix this you can tell curl to store cookies:
curl_setopt($ch, CURLOPT_COOKIEJAR, 'cookies.txt');
and you may need to disable CURLOPT_FOLLOWLOCATION, and just request webmail.php in a second call to curl (using the same cookie jar with the authenticated session).
try add this to your code
$cookie="cookie.txt";
if(!file_exists($cookie)) {
$fh = fopen($cookie, "w");
fwrite($fh,"");
fclose($fh);
}
curl_setopt($curl_connection, CURL_COOKIEJAR, $cookie);
curl_setopt($curl_connection, CURL_COOKIEFILE, $cookie);
curl_setopt($curl_connection, CURL_VERBOSE, true);
Hope this helpfull..

Categories