PHP Curl Paypal 沙箱

Posted

技术标签:

【中文标题】PHP Curl Paypal 沙箱【英文标题】:PHP Curl Paypal Sandbox 【发布时间】:2010-12-19 02:37:06 【问题描述】:

是否可以使用 CURL 和 Paypal 的开发者沙箱?当我尝试这段代码时,它在 print_r($lines);我需要登录沙盒,我怎样才能让它发送我的浏览器cookie?

此代码来自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("\r", "", $result);
    $lines = split("\n", $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##\n".
    "PayPal Transaction Information...\n".
    "Txn Id: ".$ppInfo["txn_id"]."\n".
    "Txn Type: ".$ppInfo["txn_type"]."\n".
    "Item Number: ".$ppInfo["item_number"]."\n".
    "Payment Date: ".$ppInfo["payment_date"]."\n".
    "Payment Type: ".$ppInfo["payment_type"]."\n".
    "Payment Status: ".$ppInfo["payment_status"]."\n".
    "Currency: ".$ppInfo["mc_currency"]."\n".
    "Payment Gross: ".$ppInfo["payment_gross"]."\n".
    "Payment Fee: ".$ppInfo["payment_fee"]."\n".
    "Payer Email: ".$ppInfo["payer_email"]."\n".
    "Payer Id: ".$ppInfo["payer_id"]."\n".
    "Payer Name: ".$ppInfo["first_name"]." ".$ppInfo["last_name"]."\n".
    "Payer Status: ".$ppInfo["payer_status"]."\n".
    "Country: ".$ppInfo["residence_country"]."\n".
    "Business: ".$ppInfo["business"]."\n".
    "Receiver Email: ".$ppInfo["receiver_email"]."\n".
    "Receiver Id: ".$ppInfo["receiver_id"]."\n";

    //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
     

【问题讨论】:

【参考方案1】:

这应该有效:

$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("\n", $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


另外 $_GET['tx'] 查找在约 5 分钟后停止工作

【讨论】:

【参考方案2】:

也许不是您想要的答案,但如果您想使用 PHP 中的 PayPal,我只是不断推荐此脚本:

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

非常简洁的脚本,便于理解交易的各个部分和编辑内容。

它还提供了有关如何将脚本与 PayPal 的沙箱一起使用的示例。如果我没记错的话,您只需更改一个变量(显然您需要一个沙箱帐户)。

【讨论】:

感谢分享。为我节省了很多时间。【参考方案3】:

如果有人使用 java 和 paypal PDT.. 这里使用 apache commons httpclient 4.1..

// 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 + "\n");
                
                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("----------------------------------------------------");    
                

【讨论】:

问题使用 PHP 脚本而不是 Java。

以上是关于PHP Curl Paypal 沙箱的主要内容,如果未能解决你的问题,请参考以下文章

Paypal 沙箱 CURL 执行 - “SSL 连接错误”

Paypal API 订阅 curl 沙箱目录产品 权限不足授权失败

对paypal沙箱的HTTPS请求失败

PayPal Rest API for Payments 在沙箱中返回 NULL

如何使用 PHP Wordpress 将沙箱 Paypal 返回值插入 MySQL 表?

在 PHP 中使用 IPN 的 Paypal 无法在新的 Beta 开发人员沙箱中运行