PHP Stripe get the transaction id after successful purchase

限于喜欢 提交于 2019-12-11 12:57:03

问题


I'm trying to get the transaction ID after the purchase, but it returns empty on thankyou page

order.php

<?php
\Stripe\Stripe::setApiKey('<test token>');

$amount = 100;
$card = $_POST['stripeToken'];

// Create a Customer
$customer = \Stripe\Customer::create(array(
    "source" => $card,
    "email" => $email,
    "description" => "Example description")
);

// Charge the Customer instead of the card
$charge = \Stripe\Charge::create(array(
    "amount" => 100,
    "currency" => "usd",
    "customer" => $customer->id)
);

// Save the billing info
set_billing([
    'customer_id' => $customer->id,
    'address' => $address,
    'address2' => $address2,
    'city' => $city,
    'state' => $state,
    'country' => $country,
    'postal' => $postal,
    'trans_id' => $charge->id // Save the transaction id
]);

function set_billing($fields = array())
{
    $bdate = time();

    $query = "INSERT INTO billings (
        customer_id, address, address2, city,
        state, postal, country, billing_date, trans_id
    ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)";

    $stmt = $GLOBALS['sqlConnection']->prepare($query);
    $stmt->bind_param(
        'sssssssis', $fields['customer_id'], $fields['address'], $fields['address2'], $fields['city'], $fields['state'], $fields['postal'], $fields['country'], $bdate, $fields['trans_id']);
    $stmt->execute();
}

// If successful, redirect to thank you page
header('Location: /thankyou.php?id=' . $user_id);
exit;

thankyou.php

<?php
$s = $sql->prepare('SELECT trans_id FROM billings WHERE user_id = ?');
$s->bind_param('i', $_GET['id']);
$s->execute();
$s->bind_result($trans_id);
$s->fetch();
?>

<ul>
    <li>Transaction id: <?php echo $trans_id ?></li>
</ul>

Is there any problem with my code?


回答1:


When you are charging the customer using this

$charge = \Stripe\Charge::create(array(
    "amount" => 100,
    "currency" => "usd",
    "customer" => $customer->id)
);

Also try print_r($charge); // to check the output variables

You'll get its response as $charge->id this is nothing but the transaction id, insert this transaction id in your database for future use. And then apply your further code.

And then in thankyou.php fetch the value that you have inserted




回答2:


You can directly use $charge->id

Update your line in order.php

// If successful, redirect to thank you page
header('Location: /thankyou.php?id=' . $charge->id );

Update your code in thankyou.php

<ul>
    <li>Transaction id: <?php echo $_GET['id'] ?></li>
</ul>


来源:https://stackoverflow.com/questions/37671218/php-stripe-get-the-transaction-id-after-successful-purchase

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!