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

基于Braintree支付网关的电商订单处理技术问询

Hey there! Let’s walk through how to handle your Braintree payment processing while saving the order details to your database. I’ll help you polish that PHP code to make it secure and functional.

Braintree Payment Processing + Database Storage Workflow

First, let’s fix the foundational issues in your code and build out the full logic step by step.

1. Fix Initialization Order & Input Validation

Always start with session_start() before any output (including includes that might have whitespace), and validate that you’re receiving the required data from the Dropin form.

<?php
// Critical: Start session FIRST (no output allowed before this)
session_start();

// Include dependencies
include_once("connection.php");
require "boot.php";

// Fetch session data with fallback
$active_country_code = $_SESSION["active_country_code"] ?? '';
if (empty($active_country_code)) {
    // Redirect if country code is missing
    header("Location: country-selection.php");
    exit;
}

// Validate we got the Braintree nonce (required for payment)
if (!isset($_POST['payment_method_nonce'])) {
    die("Invalid payment submission. Please try again.");
}

// Capture other form data (adjust fields to match your form)
$nonce = $_POST['payment_method_nonce'];
$amount = $_POST['amount'] ?? '0.00';
$user_email = $_POST['user_email'] ?? '';

// Add basic input validation (example for amount)
if (!is_numeric($amount) || $amount <= 0) {
    header("Location: payment-form.php?error=" . urlencode("Invalid amount entered."));
    exit;
}
?>

2. Process the Braintree Payment

Use Braintree’s transaction API to charge the payment method, then handle success/failure cases.

<?php
// ... (previous code above)

// Create Braintree transaction
$result = Braintree\Transaction::sale([
    'amount' => $amount,
    'paymentMethodNonce' => $nonce,
    'options' => [
        'submitForSettlement' => true // Set to false if you want to settle later manually
    ],
    'billing' => [
        'countryCodeAlpha2' => $active_country_code
    ]
]);

// Handle payment result
if ($result->success) {
    // Payment went through - grab transaction details
    $transaction_id = $result->transaction->id;
    $payment_status = $result->transaction->status;

    // 3. Save Order to Database
    // Use prepared statements to prevent SQL injection
    $stmt = $pdo->prepare("
        INSERT INTO orders (transaction_id, amount, user_email, country_code, status, created_at)
        VALUES (:transaction_id, :amount, :user_email, :country_code, :status, NOW())
    ");

    // Bind parameters securely
    $stmt->bindParam(':transaction_id', $transaction_id);
    $stmt->bindParam(':amount', $amount);
    $stmt->bindParam(':user_email', $user_email);
    $stmt->bindParam(':country_code', $active_country_code);
    $stmt->bindParam(':status', $payment_status);

    if ($stmt->execute()) {
        // Success: Redirect to confirmation page
        header("Location: payment-success.php?txn=" . $transaction_id);
        exit;
    } else {
        // Database save failed - log the error for debugging
        error_log("DB Save Error: " . print_r($stmt->errorInfo(), true));
        die("Payment was successful, but we couldn't save your order details. Please reach out to support.");
    }
} else {
    // Payment failed - send user back to form with error
    $error_msg = $result->message;
    header("Location: payment-form.php?error=" . urlencode($error_msg));
    exit;
}
?>

Key Best Practices to Remember

  • Session Placement: session_start() must be the first line of code (no whitespace or HTML before it) to avoid headers already sent errors.
  • Input Sanitization: Always validate and sanitize user input (like checking that the amount is a positive number) to avoid bad data.
  • SQL Injection Protection: Never concatenate user input directly into SQL queries—use prepared statements like the example above.
  • Error Handling: Don’t expose raw Braintree errors to users; show friendly messages and log detailed errors for your team.
  • Braintree Environment: Make sure boot.php uses the correct API keys (sandbox for testing, production for live payments).

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 08:03:22