I have followed this documentation to implement the Stripe Recurring Payments, which is working fine for both non-3d-Secure card and 3d-Secure enabled cards. For initial payments i get the 3d-Secure Payment authentication Modal from Stripe to authenticate payments using 3D-Secure Test cards.
The subscription is created along with invoices that Stripe generates for me. Everything's seems to be OK, BUT for 3D-Secure Enabled (Stripe Testing Cards) the First Payment goes through successfully but the subsequent payments which i have set interval of 1Day (for testing) are "Failed" by Stripe. From what i understand Stripe requires Customer's Authentication again to continue the Subscription.
In this they said
When 3D Secure is encountered, configure your billing settings to send
a hosted link to your customer to complete the flow.
That's completely OK, But why they even require the authentication step again if the first payment is succeeded and the subscription is started? I have gone through all the related Docs but found nothing to prevent that.
What if Customer does not check his/her email to come back to my Application to authenticate the payments?
OR
Is there anything wrong with the code? By that i mean that Stripe should have saved the Payment Method i.e. Card Number so it does not require the Customer Authentication on subsequent charges every time the new billing cycle start(monthly/biannually).
I have searched on internet and found and answer saying
You are using stripe.createToken which does not support 3ds
authentication. You need to migrate your client side code to
stripe.createPaymentMethod which does support it
Is that it? Any response is appreciated
My Payment.js
// set your stripe publishable key
var stripe = Stripe('pk_test_key');
var elements = stripe.elements();
var style = {
base: {
color: '#32325d',
lineHeight: '18px',
fontFamily: '"Helvetica Neue", Helvetica, sans-serif',
fontSmoothing: 'antialiased',
fontSize: '16px',
'::placeholder': {
color: '#aab7c4'
}
},
invalid: {
color: '#fa755a',
iconColor: '#fa755a'
}
};
var cardNumber = elements.create('cardNumber', {
style: style
});
cardNumber.mount('#cardNumber');
var cardExpiry = elements.create('cardExpiry', {
style: style
});
cardExpiry.mount('#cardExpiry');
var cardCvc = elements.create('cardCvc', {
style: style
});
cardCvc.mount('#cardCVC');
var cardholderName = $('#custName').val();
var amount = $('#amount').val();
var cardButton = document.getElementById('makePayment');
cardButton.addEventListener('click', function(ev) {
// alert();
ev.preventDefault();
stripe.createToken(cardNumber).then(function(result) {
if (result.error) {
} else {
//$body.addClass("loading");
fetch('process.php', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
token_id: result.token.id
})
}).then(function(result) {
// Handle server response (see Step 3)
result.json().then(function(json) {
handleServerResponse(json);
//alert();
})
});
}
});
});
function handleServerResponse(response) {
if (response.error) {
// Show error from server on payment form
} else if (response.requires_action) {
// Use Stripe.js to handle required card action
var action = response.next_action;
if (action && action.type == 'redirect_to_url') {
window.location = action.redirect_to_url.url;
}
handleAction(response);
} else {
console.log("3D" + response);
}
}
function handleAction(response) {
var paymentIntentSecret = response.payment_intent_client_secret;
stripe.handleCardPayment(paymentIntentSecret).then(function(result) {
if (result.error) {
// Display error.message in your UI.
} else {
// The payment has succeeded. Display a success message.
alert('Payment succeeded!');
}
});
}
Process.php
<?php
require_once('stripe-php/init.php');
\Stripe\Stripe::setApiKey('sk_test_key');
$json_str = file_get_contents('php://input');
$json_obj = json_decode($json_str);
//print_r($json_obj->token_id);die;
//$intent = null;
try {
if (isset($json_obj->token_id)) {
//Create Customer
$customer = \Stripe\Customer::create([
"email" => "test#gmail.com",
"name" => "Haroon",
"source" => $json_obj->token_id,
]);
//create product
$product = \Stripe\Product::create([
'name' => 'Water',
'type' => 'service',
]);
//create a plan
$plan = \Stripe\Plan::create([
'product' => $product->id,
'nickname' => 'Water',
'interval' => 'day',
'currency' => 'eur',
'amount' => 1200.00,
]);
//add subscription to stripe
$subscription = \Stripe\Subscription::create([
'customer' => $customer->id,
'items' => [[
"plan" => $plan->id],],
'expand' => ['latest_invoice.payment_intent'],
]);
}
$intent = \Stripe\PaymentIntent::retrieve($subscription->latest_invoice->payment_intent->id);
$subscription = \Stripe\Subscription::retrieve($subscription->id);
// $intent->confirm();
// }
generatePaymentResponse($intent,$subscription);
}catch (\Stripe\Error\Base $e) {
# Display error on client
echo json_encode([
'error' => $e->getMessage()
]);
}
function generatePaymentResponse($intent,$subscription) {
if ($intent->status == 'requires_action' && $subscription->status == 'incomplete' &&
$intent->next_action->type == 'use_stripe_sdk' ) {
# Tell the client to handle the action
echo json_encode([
'requires_action' => true,
'payment_intent_client_secret' => $intent->client_secret
]);
} else if ($intent->status == 'succeeded' && $subscription->status == 'active') {
# The payment didn’t need any additional actions and completed!
# Handle post-payment fulfillment
echo json_encode([
'success' => true
]);
} else if ($intent->status == 'requires_payment_method' && $subscription->status == 'incomplete') {
echo "Subscription failed";
} else {
# Invalid status
http_response_code(500);
echo json_encode(['error' => 'Invalid PaymentIntent status']);
}
}
If you are doing this for already exist card then i have done this just before some day . Refer this document https://stripe.com/docs/payments/3d-secure .
This suggest that you need to create paymentIntent and need to confirm this payment intent . and also in 3ds there are test card 4242 4242 4242 4242 This card does not require any authentication for 3ds . Giving below link for test cards
https://stripe.com/docs/payments/3d-secure/web#three-ds-cards
Related
I am having some difficulties with trying to add to cart with custom data from the front end.
My current PHP from the backend is as follows - this is placed in my functions.php for my child-theme (This code is from the following post: Adding a product to cart with custom info and price - considering I am indeed a PHP-noobie):
<?php // This captures additional posted information (all sent in one array)
add_filter('woocommerce_add_cart_item_data','wdm_add_item_data',1,10);
function wdm_add_item_data($cart_item_data, $product_id) {
global $woocommerce;
$new_value = array();
$new_value['_custom_options'] = $_POST['custom_options'];
if(empty($cart_item_data)) {
return $new_value;
} else {
return array_merge($cart_item_data, $new_value);
}
}
// This captures the information from the previous function and attaches it to the item.
add_filter('woocommerce_get_cart_item_from_session', 'wdm_get_cart_items_from_session', 1, 3 );
function wdm_get_cart_items_from_session($item,$values,$key) {
if (array_key_exists( '_custom_options', $values ) ) {
$item['_custom_options'] = $values['_custom_options'];
}
return $item;
}
// This displays extra information on basket & checkout from within the added info that was attached to the item.
add_filter('woocommerce_cart_item_name','add_usr_custom_session',1,3);
function add_usr_custom_session($product_name, $values, $cart_item_key ) {
$return_string = $product_name . "<br />" . $values['_custom_options']['description'];// . "<br />" . print_r($values['_custom_options']);
return $return_string;
}
//This adds the information as meta data so that it can be seen as part of the order (to hide any meta data from the customer just start it with an underscore)
add_action('woocommerce_add_order_item_meta','wdm_add_values_to_order_item_meta',1,2);
function wdm_add_values_to_order_item_meta($item_id, $values) {
global $woocommerce,$wpdb;
wc_add_order_item_meta($item_id,'item_details',$values['_custom_options']['description']);
wc_add_order_item_meta($item_id,'customer_image',$values['_custom_options']['another_example_field']);
wc_add_order_item_meta($item_id,'_hidden_field',$values['_custom_options']['hidden_info']);
}
and then I have a button on the frontend that runs the following script when pressed - this runs on a custom wordpress post where I have scripted have done some scripting in the background that collects information based on the users actions on the post:
function cartData() {
var metaData = {
description: 'My test Description'
another_example_field: 'test'
};
var activeVariationId = 10335;
var data = {
action: 'wdm_add_item_data',
product_id: 10324,
"add-to-cart": 10324,
quantity: 1,
variation_id: activeVariationId,
cart_item_data: metaData
};
$.ajax({
type: 'post',
url: wc_add_to_cart_params.wc_ajax_url.toString().replace( '%%endpoint%%', 'add-to-cart' ),
data: data,
beforeSend: function (response) {
//$thisbutton.removeClass('added').addClass('loading');
},
complete: function (response) {
//$thisbutton.addClass('added').removeClass('loading');
},
success: function (response) {
if (response.error & response.product_url) {
window.location = response.product_url;
return;
} else {
alert('ajax response recieved');
jQuery( document.body ).trigger( 'added_to_cart', [ response.fragments, response.cart_hash ] );
}
},
});
}
Unfortunately this only seems to add my current variation of the product to the to cart without any more custom information. Any help with nesting in this issue would be highly appreciated. If you need any more information and/or code examples I'd be happy to supply it :)
I think that I might have solved it, or at least parts of it with this PHP (this is really just a small modification of this code - adding $cart_item_data https://quadmenu.com/add-to-cart-with-woocommerce-and-ajax-step-by-step/):
add_action('wp_ajax_woocommerce_ajax_add_to_cart', 'woocommerce_ajax_add_to_cart');
add_action('wp_ajax_nopriv_woocommerce_ajax_add_to_cart', 'woocommerce_ajax_add_to_cart');
function woocommerce_ajax_add_to_cart() {
$product_id = apply_filters('woocommerce_add_to_cart_product_id', absint($_POST['product_id']));
$quantity = empty($_POST['quantity']) ? 1 : wc_stock_amount($_POST['quantity']);
$variation_id = absint($_POST['variation_id']);
// This is where you extra meta-data goes in
$cart_item_data = $_POST['meta'];
$passed_validation = apply_filters('woocommerce_add_to_cart_validation', true, $product_id, $quantity);
$product_status = get_post_status($product_id);
// Remember to add $cart_item_data to WC->cart->add_to_cart
if ($passed_validation && WC()->cart->add_to_cart($product_id, $quantity, $variation_id, $cart_item_data) && 'publish' === $product_status) {
do_action('woocommerce_ajax_added_to_cart', $product_id);
if ('yes' === get_option('woocommerce_cart_redirect_after_add')) {
wc_add_to_cart_message(array($product_id => $quantity), true);
}
WC_AJAX :: get_refreshed_fragments();
} else {
$data = array(
'error' => true,
'product_url' => apply_filters('woocommerce_cart_redirect_after_error', get_permalink($product_id), $product_id));
echo wp_send_json($data);
}
wp_die();
}
Where this is part of the JS-function:
var data = {
action: 'woocommerce_ajax_add_to_cart',
product_id: 10324,
quantity: 1,
variation_id: activeVariationId,
meta: metaData
};
$.ajax({
type: 'post',
url: wc_add_to_cart_params.ajax_url,
data: data, ...........
I am going to have to test it some more, as it seems now that all the data-fields also gets posted in the cart, email etc - I probably have to rewrite something so that some parts of it is hidden for the "non-admin", but available for me later on + adding custom product thumbnail on add to cart.
I am trying to create a customer and create a subscription.
But when I do it I get error.
I tried doing it the node.js way and the php way. via node.js
I have installed stripe and via php I've installed composer and stripe/stripe-php.
When I do it the javascript way everything goes find and handy with no error out put but when I go to the stripe daashboard there is no new creation of a customer or subscription in the test mode data.
<?php // Create a customer using a Stripe token
// If you're using Composer, use Composer's autoload:
require_once('vendor/autoload.php');
// Be sure to replace this with your actual test API key
// (switch to the live key later)
\Stripe\Stripe::setApiKey("pk_test_pjUIBAynO2WA1gA7woSLBny3");
try
{
$customer = \Stripe\Customer::create([
'email' => $_POST['stripeEmail'],
'source' => $_POST['stripeToken'],
]);
$subscription = \Stripe\Subscription::create([
'customer' => $customer->id,
'items' => [['plan' => 'gold']],
]);
if ($subscription->status != 'incomplete')
{
header('Location: thankyou.html');
}
else
{
header('Location: payment_failed.html');
error_log("failed to collect initial payment for subscription");
}
exit;
}
catch(Exception $e)
{
header('Location:oops.html');
error_log("unable to sign up customer:" . $_POST['stripeEmail'].
", error:" . $e->getMessage());
}
and this is the html file
<form action="/create_subscription.php" id="start" method="POST">
<script
src="https://checkout.stripe.com/checkout.js" class="stripe-button"
data-key="pk_test_pjUIBAynO2WA1gA7woSLBny3"
data-name="500 a month package"
data-description="Subscription will be billed every 30 days"
data-amount="50000"
data-label="Get Started!">
</script>
<script>
var stripe = require("stripe")("pk_test_pjUIBAynO2WA1gA7woSLBny3");
var stripeToken = req.body.stripeToken;
stripe.subscriptions.create({
customer: id,
items: [
{
plan: "prod_EtGDP9qICl6tvW",
interval: "month"
},
]
} , function(err, subscription) {
// asynchronously called
function(err, custumor){
if(err){
res.send({
success: false,
message:'Error'
});
} else {
const { id } = customer;
}
};
stripe.customers.create({
email:"jenny#rosen.com",
source: stripeToken,
},
function(err, custumor){
if(err){
res.send({
success: false,
message:'Error'
});
} else {
const { id } = customer;
}
});
</script>
</form>
I am trying to connect to an api using the code below, so when the customer clicks on the "place order" button on the Woocommerce checkout page, I am getting a "please try again" error:
var amount = <?php global $woocommerce; print WC()->cart->total; ?>;
var merchantOrderId = '<?php echo print time(); ?>';
var apiKey = 'm85BXXLpf_icrSvqbElR11xquEgmKZ8wfeRb2ly3-G7pIwCKDuytgplB7AQGi-5t';
renderMMoneyPaymentButton(amount, merchantOrderId, apiKey);
I am trying to pass this information to the api via this function but I am not getting a successful connection.
public function process_payment( $order_id ) {
global $woocommerce;
// we need it to get any order detailes
$order = new WC_Order($order_id);
/*
* Array with parameters for API interaction
*/
$args = array(
'amount' => '<?php global $woocommerce; print WC()->cart->total; ?>',
'merchant_order_id' => '<?php print time(); ?>',
'api_Key' => 'm85BXXLpf_icrSvqbElR11xquEgmKZ8wfeRb2ly3-G7pIwCKDuytgplB7AQGi-5t',
'currency' => 'BBD',
);
/*
* Your API interaction could be built with wp_remote_post()
*/
$response = wp_remote_post( 'https://api.mmoneybb.com/merchant/js/mmoney-payment.js', $args );
if( !is_wp_error( $response ) ) {
$body = json_decode( $response['body'], true );
// it could be different depending on your payment processor
if ( $body ['$response'] == 'APPROVED') {
// we received the payment
$order->payment_complete();
$order->reduce_order_stock();
// some notes to customer (replace true with false to make it private)
$order->add_order_note( 'Thanks for your payment!!!!', true );
// Empty cart
$woocommerce->cart->empty_cart();
// Redirect to the thank you page
return array(
'result' => 'success',
'redirect' => $this->get_return_url( $order )
);
} else {
wc_add_notice( 'Please try again.', 'error' );
return;
}
} else {
wc_add_notice( 'Connection error.', 'error' );
return;
}
}
let me know what i am doing wrong much appreciated also this is the other script as well
function renderMMoneyPaymentButton(amount, merchantOrderId, apiKey) {
let paymentParams = {
amount: amount,
api_key: apiKey,
currency: 'BBD',
merchant_order_id: merchantOrderId,
onCancel: function () { console.log('Modal closed'); },
onError: function(error) { console.log('Error', error); },
onPaid: function (invoice) { console.log('Payment complete', invoice); }
};
// "mMoney" window global provided by sourcing mmoney-payment.js script.
// Attach the button to the empty element.
mMoney.payment.button.render(paymentParams, '#mmoney-payment-button');
}
1) In your first snippet code you are using javascript and you need to get the order Id and then the order total… You can only get the Order ID after the order is placed…
There is an answer example here.
2) Your 2nd public function involves only PHP… There are some errors and mistakes in this code. Try the following revisited code instead:
public function process_payment( $order_id ) {
// Get The WC_Order Object instance
$order = wc_get_order( $order_id );
/*
* Array with parameters for API interaction
*/
$args = array(
'amount' => $order->get_total(),
'merchant_order_id' => $order_id,
'api_Key' => 'm85BXXLpf_icrSvqbElR11xquEgmKZ8wfeRb2ly3-G7pIwCKDuytgplB7AQGi-5t',
'currency' => $order->get_currency(),
);
/*
* Your API interaction could be built with wp_remote_post()
*/
$response = wp_remote_post( 'https://api.mmoneybb.com/merchant/js/mmoney-payment.js', $args );
if( !is_wp_error( $response ) ) {
$body = json_decode( $response['body'], true );
// it could be different depending on your payment processor
if ( $body ['$response'] == 'APPROVED') {
// we received the payment
$order->payment_complete();
$order->reduce_order_stock();
// some notes to customer (replace true with false to make it private)
$order->add_order_note( 'Thanks for your payment!!!!', true );
// Empty cart
$woocommerce->cart->empty_cart();
// Redirect to the thank you page
return array(
'result' => 'success',
'redirect' => $this->get_return_url( $order )
);
} else {
wc_add_notice( 'Please try again.', 'error' );
return;
}
} else {
wc_add_notice( 'Connection error.', 'error' );
return;
}
}
It should better work.
I am currently creating a login form in PHP PDO and I am using ajax to display the relevant messages on screen, e.g.
"Logging in..."
"Some input fields are empty"
"Your username is required"
"Your password is required"
Validation such as checking if input fields are empty is working fine along with when login credentials appear to be incorrect however when I login with correct credentials I just get message "Logging in..." and nothing happens, I don't even think it sets the session. I have also added a token to prevent CSRF and was just wondering if i'm using it correctly.
I'm unsure of what is causing my code not to proceed with logging in.
my ajax script:
<script type='text/javascript'>
$(document).ready(function () {
var submitButton = $("#btn-login");
submitButton.on('click', function (e) {
e.preventDefault();
// Get input field values of the contact form
var loginFormInputs = $('#login-form :input'),
userName = $('#txt_uname_email').val(),
userPassword = $('#txt_password').val(),
token = $('#token').val(),
alertMessage = $('#login-alert-message');
// Disable Inputs and display a loading message
alertMessage.html('<p style="opacity: 1"><i class="fa fa-spinner fa-spin text-success"></i> Logging in..</p>');
submitButton.html('<i class="fas fa-spinner fa-spin"></i>');
loginFormInputs.prop("disabled", true);
// Data to be sent to server
var post_data = {
'form': 'loginForm',
'userName': userName,
'userPassword': userPassword,
'token': token
};
// Ajax post data to server
$.post('./api', post_data, function (response) {
// Load jsn data from server and output message
if (response.type === 'error') {
alertMessage.html('<p><i class="fa-lg far fa-times-circle text-danger"></i> ' + response.text + '</p>');
submitButton.html('Login');
loginFormInputs.prop("disabled", false);
} else {
alertMessage.html('<p><i class="fa-lg far fa-check-circle text-success"></i> ' + response.text + '</p>');
submitButton.html('Login');
window.location = "dashboard";
}
}, 'json');
});
});
</script>
My login function (class.user.php) which is used in api.php:
public function doLogin($uname,$umail,$upass)
{
try
{
$stmt = $this->conn->prepare("SELECT * FROM `settings` LIMIT 1");
$stmt->execute();
$mainten=$stmt->fetch(PDO::FETCH_ASSOC);
$stmt = $this->conn->prepare("SELECT user_id, user_name, user_email, user_pass, status FROM users WHERE user_name=:uname OR user_email=:umail ");
$stmt->execute(array(':uname'=>$uname, ':umail'=>$umail));
$userRow=$stmt->fetch(PDO::FETCH_ASSOC);
if($stmt->rowCount() == 1)
{
if(password_verify($upass, $userRow['user_pass']))
{
session_regenerate_id(false);
return ["correctPass"=>true, "banned"=> ($userRow['status']== 1) ? true : false, "maintenance"=> ($mainten["maintenance"]== 1) ? true : false];
}
else
{
return ["correctPass"=>false];
}
}
}
catch(PDOException $e)
{
echo $e->getMessage();
}
}
api.php:
//include class.user.php here and set $login = new USER();
//set $uname, $umail, $upass, $token vars here
if( $_POST && $_POST["form"] === 'loginForm' ) {
// Use PHP To Detect An Ajax Request code is here
// Checking if the $_POST vars well provided, Exit if there is one missing code is here
// PHP validation for the fields required code is here
$validation = $login->doLogin($uname,$umail,$upass);
if($validation["correctPass"]){
if($validation["maintenance"]){
if (!in_array($uname, array('admin'))){
$output = json_encode(
array(
'type' => 'error',
'text' => 'Website under maintenance.'
));
die($output);
}
}
if($validation["banned"]){
$output = json_encode(
array(
'type' => 'error',
'text' => 'User has been banned.'
));
die($output);
}else{
if(Token::check($_POST['token'])) {
$stmtt = $login->runQuery("SELECT user_id FROM users WHERE user_name=:uname OR user_email=:umail ");
$stmtt->execute(array(':uname'=>$uname, ':umail'=>$umail));
$userRow=$stmtt->fetch(PDO::FETCH_ASSOC);
$_SESSION['user_session'] = $userRow['user_id'];
$output = json_encode(
array(
'type' => 'message',
'text' => 'Logged in successfully.'
));
die($output);
//$success = "Logged in successfully, redirecting..";
//header( "refresh:3;url=ab" );
//$login->redirect('dashboard');
} else {
$output = json_encode(
array(
'type' => 'error',
'text' => 'Unexpected error occured.'
));
die($output);
}
}
}
else{
$output = json_encode(
array(
'type' => 'error',
'text' => 'Incorrect username or password.'
));
die($output);
}
}
The below is my code I'm using for my Stripe Subscription Payments, because the site I'm implementing this into is AngularJS I want to keep the site from Refreshing so I'm opting for this AJAX option.
I have commented out a piece of the PHP which is
$charge = Stripe_Charge::create(array(
'customer' => $customer->id,
'amount' => $amount,
'currency' => 'gbp'
));
If I exclude this, the payment goes through once and I'm unsure how this application is able to process the charge if there is no call for it in the PHP file.
If I include the above snippet then the charge goes through twice.
My config.php only has require_once('Stripe.php'); along with my API keys.
So I'm hoping someone could explain why the charge goes through without the charge code piece in there if my code is actually okay for me to continue with.
HTML
<button id="proBtn">Subscribe</button>
JavaScript
Stripe.setPublishableKey('HIDDEN');
$('#proBtn').click(function(){
var token = function(res){
var $input = $('<input type="hidden" name="stripeToken" />').val(res.id);
var tokenId = $input.val();
var email = res.email;
setTimeout(function(){
$.ajax({
url:'/assets/lib/charge.php',
cache: false,
data:{ stripeEmail : email, stripeToken:tokenId, stripePlan: 'pro' },
type:'POST'
})
.done(function(data){
// If Payment Success
console.log(data);
$('#proBtn').html('Thank You').addClass('disabled');
})
.error(function(){
$('#proBtn').html('Error, Unable to Process Payment').addClass('disabled');
});
},500);
//$('form:first-child').append($input).submit();
};
StripeCheckout.open({
key: 'HIDDEN', // Your Key
address: false,
amount: 500,
currency: 'gbp',
name: 'Pro Account',
description: '',
panelLabel: 'Checkout',
allowRememberMe: false,
token: token
});
return false;
});
charge.php
<?php
require_once($_SERVER['DOCUMENT_ROOT'].'/assets/lib/config.php');
$token = $_POST['stripeToken'];
$email = $_POST['stripeEmail'];
$plan = $_POST['stripePlan'];
if ( $plan == 'pro' ) {
$amount = 500;
$amountFormat = number_format( $amount / 100, 2) ;
$plan = 'pro';
}
if ( $plan == 'team' ) {
$amount = 2000;
$amountFormat = number_format( $amount / 100, 2) ;
$plan = 'team';
}
Stripe_Plan::retrieve("pro");
Stripe_Plan::retrieve("team");
$customer = Stripe_Customer::create(array(
'email' => $email,
'card' => $token,
'plan' => $plan
));
try {
/*
$charge = Stripe_Charge::create(array(
'customer' => $customer->id,
'amount' => $amount,
'currency' => 'gbp'
));*/
echo 'success';
} catch(Stripe_CardError $e) {
echo "The card has been declined";
echo $token;
}
print_r($token);
echo '<br/>';
print_r($email);
echo '<br/>';
echo $customer->id;
echo '<h1>Successfully charged '.$amountFormat.'!</h1>';
?>
When you create a customer in Stripe it automatically charges them if you pass in a plan. You're basically saying create this customer and sign them up for this plan. That's why you are charging them twice.
Here's a link to the Customer API:
https://stripe.com/docs/api#create_customer