You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从URL获取PayPal交易详情?支付成功后页面展示交易详情方法

实现PayPal交易后页面展示交易详情(基于IPN)

Hey there! Let me break down exactly how to use PayPal's Instant Payment Notification (IPN) to pull and display transaction details on your return page—I’ve implemented this dozens of times, so I’ll walk you through the whole process step by step.

First, a quick key point: The return URL PayPal sends users to will have some basic parameters (like txn_id), but you shouldn’t rely on those alone for displaying sensitive details (they can be tampered with). IPN is PayPal’s secure way to send you verified transaction data directly to your server, which you can then store and use to show details on your return page.


1. Configure PayPal IPN Settings

First, set up IPN in your PayPal merchant account:

  • Log into your PayPal account, go to Account Settings > Website Payments > Instant Payment Notification Settings
  • Toggle IPN to "On"
  • Enter your IPN listener script URL (e.g., https://yourdomain.com/paypal-ipn-handler.php)—this is a server-side script we’ll build next
  • Save your settings

2. Build the IPN Listener Script (Core Logic)

This script will receive verified transaction data from PayPal, validate it, and store it in your database. Here’s a PHP example (adjust for your language/stack):

<?php
// Capture raw POST data from PayPal
$rawPost = file_get_contents('php://input');
$postArray = explode('&', $rawPost);
$processedPost = [];

foreach ($postArray as $keyValue) {
    list($key, $value) = explode('=', $keyValue, 2);
    $processedPost[$key] = urldecode($value);
}

// Send data back to PayPal for verification
$validationReq = 'cmd=_notify-validate';
foreach ($processedPost as $key => $value) {
    $value = urlencode(stripslashes($value));
    $validationReq .= "&$key=$value";
}

// Use PayPal sandbox URL for testing: https://ipnpb.sandbox.paypal.com/cgi-bin/webscr
$ch = curl_init('https://ipnpb.paypal.com/cgi-bin/webscr');
curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $validationReq);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($ch, CURLOPT_FORBID_REUSE, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Connection: Close']);

$validationResponse = curl_exec($ch);
if (!$validationResponse) {
    error_log("IPN Error: " . curl_error($ch));
    curl_close($ch);
    exit;
}
curl_close($ch);

// Process verified data
if (strcmp($validationResponse, "VERIFIED") === 0) {
    // Extract key transaction details (see PayPal's IPN docs for full field list)
    $txnId = $processedPost['txn_id'];
    $amount = $processedPost['mc_gross'];
    $status = $processedPost['payment_status'];
    $payerEmail = $processedPost['payer_email'];
    $itemName = $processedPost['item_name'];

    // Store in your database (use PDO/mysqli for security)
    $pdo = new PDO('mysql:host=YOUR_DB_HOST;dbname=YOUR_DB_NAME', 'DB_USER', 'DB_PASS');
    $stmt = $pdo->prepare("INSERT INTO paypal_transactions (txn_id, amount, status, payer_email, item_name) 
                          VALUES (?, ?, ?, ?, ?) 
                          ON DUPLICATE KEY UPDATE status=VALUES(status)");
    $stmt->execute([$txnId, $amount, $status, $payerEmail, $itemName]);

} elseif (strcmp($validationResponse, "INVALID") === 0) {
    // Log invalid IPN attempts for security
    error_log("Invalid IPN Received: " . $rawPost);
}
?>

3. Display Details on Your Return Page

When PayPal redirects users back to your page (the return URL you set in your payment button/API call), it will include a txn_id parameter. Use this ID to fetch the verified data from your database and display it:

<?php
if (isset($_GET['txn_id'])) {
    $txnId = $_GET['txn_id'];

    // Fetch transaction from database
    $pdo = new PDO('mysql:host=YOUR_DB_HOST;dbname=YOUR_DB_NAME', 'DB_USER', 'DB_PASS');
    $stmt = $pdo->prepare("SELECT * FROM paypal_transactions WHERE txn_id = ?");
    $stmt->execute([$txnId]);
    $transaction = $stmt->fetch(PDO::FETCH_ASSOC);

    if ($transaction) {
        // Render transaction details (sanitize output to prevent XSS)
        echo "<h2>✅ 交易完成</h2>";
        echo "<div class='transaction-details'>";
        echo "<p><strong>交易ID:</strong> " . htmlspecialchars($transaction['txn_id']) . "</p>";
        echo "<p><strong>支付金额:</strong> $" . htmlspecialchars($transaction['amount']) . "</p>";
        echo "<p><strong>支付状态:</strong> " . htmlspecialchars($transaction['status']) . "</p>";
        echo "<p><strong>付款人邮箱:</strong> " . htmlspecialchars($transaction['payer_email']) . "</p>";
        echo "<p><strong>购买商品:</strong> " . htmlspecialchars($transaction['item_name']) . "</p>";
        echo "</div>";
    } else {
        // IPN might not have processed yet—give users a friendly message
        echo "<p>⏳ 交易详情正在加载,请稍等片刻后刷新页面。</p>";
    }
} else {
    echo "<p>❌ 无效的交易请求,请返回重新操作。</p>";
}
?>

4. Critical Tips to Avoid Issues

  • Never trust return URL parameters alone: Always validate via IPN before displaying sensitive data—return URL params can be faked.
  • Handle duplicate IPNs: PayPal might resend IPNs if it doesn’t get a 200 response from your listener. Use ON DUPLICATE KEY UPDATE (as in the script) to avoid duplicate database entries.
  • Test in sandbox first: Use PayPal’s Sandbox environment to test your listener and return page before going live.
  • Log everything: Keep logs of IPN requests/responses and database operations—this will save you time debugging later.

内容的提问来源于stack exchange,提问作者Karthik

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 07:25:03