Page 1 of 1

Post Data and Receive Response from an external script

Posted: Wed Feb 24, 2010 5:32 pm
by gcreddy
Hello,

I am a novice coder trying to implement a payment processing portal. I have an account with a payment processing website.

I am gathering data (eg: card name, card number, expiration date etc.) and posting it to their CGI script with the test variables provided by them and I am getting a (parsed) response on their CGI script. However, I need to collect this reponse, come back to some page on my domain, write it into a databasse and generate some kind of a thank you message.

Can somebody please tell me how I can write a script (I mean...what functions / resources are used) to implement this type of functionality?

Thanks for reading my post.

Regards,
G.C.Reddy

Re: Post Data and Receive Response from an external script

Posted: Wed Feb 24, 2010 5:42 pm
by s.dot
Hi, You will need to post the variables like this...

Code: Select all

 
//generate the request you are POSTing to the payment processor
$req = '';
foreach ($_POST AS $k => $v)
{
    $req .= '&' . $k . '=' . urlencode($v);
}
 
header("POST /script.cgi HTTP/1.0");
header("Host: http://www.example.com");
header("Content-Type: application/x-www-form-urlencoded");
header("Content-Length: " . strlen($req));
 
//open a file stream
if ($fileStream = fsockopen('www.example.com', 80, $errno, $errstr, 30))
{
    //write the $_POST data to the file stream
    fwrite($fileStream, $headers . $req);
 
    //loop, attempting to read content sent back from payment processor
        $contents = '';
    while (!feof($fileStream))
    {
        //get the contents, 1kb at a time
        $contents .= fgets($fileStream, 1024);
     }
 
     //you now have what the payment processor sent back to you
     //so do something with it, like write it to the database
     echo $contents;
}
 
Edit: I did not check the code for errors but I do something similar for PayPal IPN requests.

Re: Post Data and Receive Response from an external script

Posted: Wed Feb 24, 2010 6:28 pm
by Darhazer
The headers, send by header(), are send to the client, and not to the CGI script. You have to include them in the beginning of the $req, with 2 end-of-line characters to separate them from the body.
Using curl however is the easiest way to accomplish this.