English 中文(简体)
PHP Curl Paypal Sandbox
原标题:

Is it possible to use CURL and Paypal s Developer Sandbox? When I try this code it says in print_r($lines); that I need to login to the Sandbox, how can I make it send my browser cookie?

This code is from http://leepeng.blogspot.com/2006/04/standard-paypal-php-integration.html

   $orderno = $_SESSION["ss_last_orderno"];
    $ppAcc = "[SELLER HERE]";
    $at = "[AT HERE]"; //PDT Identity Token
    $url = "https://www.sandbox.paypal.com/cgi-bin/webscr"; //Test
    //$url = "https://www.paypal.com/cgi-bin/webscr"; //Live
    $tx = $_REQUEST[ tx ]; //this value is return by PayPal
    $cmd = "_notify-synch";
    $post = "tx=$tx&at=$at&cmd=$cmd";

    //Send request to PayPal server using CURL
    $ch = curl_init ($url);
    curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt ($ch, CURLOPT_HEADER, 0);
    curl_setopt ($ch, CURLOPT_TIMEOUT, 30);
    curl_setopt ($ch, CURLOPT_POST, 1);
    curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,FALSE);
    curl_setopt ($ch, CURLOPT_POSTFIELDS, $post);

    $result = curl_exec ($ch); //returned result is key-value pair string
    $error = curl_error($ch);

    if (curl_errno($ch) != 0) //CURL error
    exit("ERROR: Failed updating order. PayPal PDT service failed.");

    $longstr = str_replace("
", "", $result);
    $lines = split("
", $longstr);
    print_r($lines);
    //parse the result string and store information to array
    if ($lines[0] == "SUCCESS") {
    //successful payment
    $ppInfo = array();
    for ($i=1; $i<count($lines); $i++) {
    $parts = split("=", $lines[$i]);
    if (count($parts)==2) {
    $ppInfo[$parts[0]] = urldecode($parts[1]);
    }
    }

    $curtime = gmdate("d/m/Y H:i:s");
    //capture the PayPal returned information as order remarks
    $oremarks =
    "##$curtime##
".
    "PayPal Transaction Information...
".
    "Txn Id: ".$ppInfo["txn_id"]."
".
    "Txn Type: ".$ppInfo["txn_type"]."
".
    "Item Number: ".$ppInfo["item_number"]."
".
    "Payment Date: ".$ppInfo["payment_date"]."
".
    "Payment Type: ".$ppInfo["payment_type"]."
".
    "Payment Status: ".$ppInfo["payment_status"]."
".
    "Currency: ".$ppInfo["mc_currency"]."
".
    "Payment Gross: ".$ppInfo["payment_gross"]."
".
    "Payment Fee: ".$ppInfo["payment_fee"]."
".
    "Payer Email: ".$ppInfo["payer_email"]."
".
    "Payer Id: ".$ppInfo["payer_id"]."
".
    "Payer Name: ".$ppInfo["first_name"]." ".$ppInfo["last_name"]."
".
    "Payer Status: ".$ppInfo["payer_status"]."
".
    "Country: ".$ppInfo["residence_country"]."
".
    "Business: ".$ppInfo["business"]."
".
    "Receiver Email: ".$ppInfo["receiver_email"]."
".
    "Receiver Id: ".$ppInfo["receiver_id"]."
";

    //Update database using $orderno, set status to Paid
    //Send confirmation email to buyer and notification email to merchant
    //Redirect to thankyou page
    }

    //Payment failed
    else {

    print "Please try again...";
    //Delete order information
    //Redirect to failed page
    } 
最佳回答

This should work:

$tid = $_GET[ tx ];
$auth_token = "zzzzzzzzzzzzzzzzzzzz";
$paypal_url = "www.sandbox.paypal.com";

$url = "https://" . $paypal_url . "/cgi-bin/webscr";

$post_vars = "cmd=_notify-synch&tx=" . $tid . "&at=" . $auth_token;

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_vars);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 15);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_USERAGENT,  cURL/PHP );

$fetched = curl_exec($ch);



$lines = explode("
", $fetched);
$keyarray = array();
if (strcmp ($lines[0], "SUCCESS") == 0) {
for ($i=1; $i<count($lines);$i++){
list($key,$val) = explode("=", $lines[$i]);
$keyarray[urldecode($key)] = urldecode($val);
}
// check the payment_status is Completed
// check that txn_id has not been previously processed
// check that receiver_email is your Primary PayPal email
// check that payment_amount/payment_currency are correct
// process payment
$firstname = $keyarray[ first_name ];
$lastname = $keyarray[ last_name ];
$itemname = $keyarray[ num_cart_items ];
$amount = $keyarray[ mc_gross ];

echo ("<h2>Thank you for your purchase!</h2>");

}
else if (strcmp ($lines[0], "FAIL") == 0) {
    echo ("<h2>Sorry, something went wrong</h2>");

// log for manual investigation

}

Also $_GET[ tx ] look up stops working after ~5 minutes

问题回答

Maybe not exactly what you want as an answer, but I just keep recommending this script if you want to use PayPal from PHP:

http://www.micahcarrick.com/04-19-2005/php-paypal-ipn-integration-class.html

Very clean script, which makes it easy to understand the parts of a transaction and edit things.

It also comes with examples provided on how to use the script with PayPal s sandbox. If I remember correctly, you just have to change one variable (and you obviously need an account for the sandbox).

If anyone using java with paypal PDT.. apache commons httpclient 4.1 is used here..

// Imports ----------------
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
// end of imports ---------------

            HttpClient httpclient = new DefaultHttpClient();  
            HttpParams myParams = httpclient.getParams();
            HttpConnectionParams.setConnectionTimeout(myParams,40000);
            HttpConnectionParams.setSoTimeout(myParams,40000);
            HttpPost httppost = new HttpPost("https://www.sandbox.paypal.com/cgi-bin/webscr");             
            httppost.setHeader("Content-Type", "application/x-www-form-urlencoded");

         try {  
                // Add your data  

                String txToken = "xxxxxxxxxxxx";
                String authToken = "xxxxxxxxxxxxxxxxxxxxxxxxx";                 

                List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2); 
                nameValuePairs.add(new BasicNameValuePair("cmd", "_notify-synch"));  
                nameValuePairs.add(new BasicNameValuePair("tx", txToken));  
                nameValuePairs.add(new BasicNameValuePair("at", authToken));
                httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

                HttpResponse response = httpclient.execute(httppost);  

                InputStream is = response.getEntity().getContent();
                BufferedReader reader = new BufferedReader(new InputStreamReader(is));
                StringBuilder str = new StringBuilder();
                String line = null;

                while((line = reader.readLine()) != null){
                     str.append(line + "
");
                }
                is.close();
                     String responseText = str.toString();
                     logger.info("----------------------------------------------------");
                     logger.info("RESPONSE : " + responseText);
                     logger.info("----------------------------------------------------");     
                     getContext().getResponse().getWriter().write(responseText);                


             }
             catch (Exception e) {  
                     logger.info("----------------------------------------------------");
                     logger.info("ERROR : " + e.getMessage());
                     logger.info("----------------------------------------------------");    
             }   




相关问题
Brute-force/DoS prevention in PHP [closed]

I am trying to write a script to prevent brute-force login attempts in a website I m building. The logic goes something like this: User sends login information. Check if username and password is ...

please can anyone check this while loop and if condition

<?php $con=mysql_connect("localhost","mts","mts"); if(!con) { die( unable to connect . mysql_error()); } mysql_select_db("mts",$con); /* date_default_timezone_set ("Asia/Calcutta"); $date = ...

定值美元

如何确认来自正确来源的数字。

Generating a drop down list of timezones with PHP

Most sites need some way to show the dates on the site in the users preferred timezone. Below are two lists that I found and then one method using the built in PHP DateTime class in PHP 5. I need ...

Text as watermarking in PHP

I want to create text as a watermark for an image. the water mark should have the following properties front: Impact color: white opacity: 31% Font style: regular, bold Bevel and Emboss size: 30 ...

How does php cast boolean variables?

How does php cast boolean variables? I was trying to save a boolean value to an array: $result["Users"]["is_login"] = true; but when I use debug the is_login value is blank. and when I do ...

热门标签