简体   繁体   中英

Self enter charge amount for Stripe Payment

I am trying to implement the Stripe payment into my website so that the client can charge the amount themselves. The stripe documentation is not straightforward having difficulties with the integration.

<form action="charge.php" method="POST">
  <script
    src="https://checkout.stripe.com/checkout.js" class="stripe-button"
    data-key="pk_test_xxxxxxxxxxxxxxxxxxxx"
    data-amount="CHARGE AMOUNT"
    data-name="Maid In Raleigh"
    data-description="Service Charge"
    data-image="/128x128.png">
  </script>
</form>

I would like my client to change the "data-amount" so that they can change the value of the payment. I am sure that the charge.php given below is a mess. I cannot make it to work although the dashboard registers the token in their log file.

<?php
\Stripe\Stripe::setApiKey("sk_test_xxxxxxxxxxxxxxxxxxxxxxx");
// Get the credit card details submitted by the form
$token = $_POST['stripeToken'];
// Create the charge on Stripe's servers - this will charge the user's card
try {
$charge = \Stripe\Charge::create(array(
  "amount" => CHARGEAMOUNT, // amount in cents, again
  "currency" => "usd",
  "source" => $token,
  "description" => "Service Charge")
);
    echo "<h2>Thank you!</h2>"
    echo $_POST['stripeEmail'];
} catch(\Stripe\Error\Card $e) {
  // The card has been declined
}
    echo "<h2>Thank you!</h2>"
?>

Is there any way to avoid charging from the client's side javascript and instead use PHP to process?

Thanks if anyone can help!

A few days back I had to work with stripe api to process payment for dynamic amount. I have used the following code, I haven't used namespaces. But I'm sure you'll be able to work.

$card = array(
    "number" => '',     // credit card number you are about to charge
    "exp_month" => '', // card expire month
    "exp_year" => '',   // card expire year
    "cvc" => '' // cvc code
);

This array is required to generate the token.

$token_id = Stripe_Token::create(array(
    "card" => $card 
));

Now its time to process the payment. But first check the token is valid

if($token_id->id !=''){
    $charge = Stripe_Charge::create(array( 
        "amount" => '', // amount to charge
        "currency" => '', // currency
        "card" => $token_id->id, // generated token id
        "metadata" => '' // some metadata that you want to store with the payment
    ));

    if ($charge->paid == true) {
      // payment successful
    }
    else{
      // payment failed
    }
}
else{
    // card is declined.
}

I used this code to setup a recurring payment system. And it worked!. I hope this would help you as well. :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM