how can i send variable amount on my line item as it only accept integers please rest everything works but this varible amount is not working tried $params->amount not working
<?php
require_once('vendor/autoload.php');
\Stripe\Stripe::setApiKey('sk_test_key');
$session = \Stripe\Checkout\Session::create([
'payment_method_types' => ['card'],
'line_items' => [[
'price_data' => [
'currency' => 'usd',
'product_data' => [
'name' => 'T-shirt',
],
'unit_amount' => 2000,
],
'quantity' => 1,
]],
'mode' => 'payment',
'success_url' => 'https://example.com/success',
'cancel_url' => 'https://example.com/cancel',
]);
?>
<html>
<head>
<title>Buy cool new product</title>
<script src="https://js.stripe.com/v3/"></script>
</head>
<body>
<div class="field">
<label for="amount">Amount to pay</label>
<input type="number" id="amount" step="0.01" value="5.00">
</div>
<button id="checkout-button">Checkout</button>
<script>
var stripe = Stripe('pk_test_51JWkHLK7X12cK8Ptf5y5DQn6Ugf6miu3AqSuhH9wdLsyTB9ouf0TY31vDQxq19xIt6YH76uMTEX1kU9HMyrcEb6w00MTxHnGxc');
var amount = document.getElementById('amount');
const btn = document.getElementById("checkout-button")
btn.addEventListener('click', function(e) {
e.preventDefault();
stripe.redirectToCheckout({
sessionId: "<?php echo $session->id; ?>"
});
})
</script>
</body>
</html>
how can i send variable amount on my line item as it only accept integers please rest everything works but this varible amount is not working tried $params->amount not working
The code to create the payment intent with your secret key needs to be run server-side - you must not use your secret key in client-side code.
You should follow the guide here to see how you can generate a payment intent and provide the secret key in a server rendered template, or you can make an async request to your server from an SPA to get a payment intent client secret. The guide goes through both options.
Related
This is my server side code
<?php
ini_set('display_errors',1);
error_reporting(E_ALL);
use Slim\Http\Request;
use Slim\Http\Response;
use Stripe\Stripe;
require 'vendor/autoload.php';
$dotenv = Dotenv\Dotenv::create(__DIR__);
$dotenv->load();
require './config.php';
$app = new \Slim\App;
$app->add(function ($request, $response, $next) {
Stripe::setApiKey(getenv('STRIPE_SECRET_KEY'));
return $next($request, $response);
});
$app->get('/', function (Request $request, Response $response, array $args) {
return $response->write(file_get_contents(getenv('STATIC_DIR') . '/index.html'));
});
$app->post('/checkout_sessions', function(Request $request, Response $response) use ($app) {
$params = json_decode($request->getBody());
$payment_method_types = [
'usd' => ['card'],
'eur' => ['card'],
'cad' => ['card']
];
$products = [
'cause-a' => 'prod_KP3YP2a3IGYqsb',
'cause-b' => 'prod_KP3iZRGcEjn5W8',
];
$session = \Stripe\Checkout\Session::create([
'success_url' => 'http://localhost:4242/success.html?session_id={CHECKOUT_SESSION_ID}',
'cancel_url' => 'http://localhost:4242/?cancel=true',
'mode' => 'payment',
'payment_method_types' => $payment_method_types[$params->currency],
'metadata' => [
'cause' => $params->cause,
'currency' => $params->currency,
],
'submit_type' => 'donate',
'line_items' => [[
'price_data' => [
'currency' => $params->currency,
'product' => $products[$params->cause],
'unit_amount' => $params->amount,
],
'quantity' => 1,
]]
]);
return $response->withJson([
'id' => $session->id
]);
});
$app->get('/order', function (Request $request, Response $response) {
$id = $_GET['sessionId'];
$checkout_session = \Stripe\Checkout\Session::retrieve($id);
echo json_encode($checkout_session);
});
$app->run();
this is the success page with javascript
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Order Confirm</title>
</head>
<body>
<div id="main">
<div id="checkout">
<div id="payment-forum">
<h1>Success</h1>
payment status: <span id="payment-status"></span>
<pre>
</pre>
</div>
</div>
</div>
</body>
<script>
var paymentStatus = document.getElementById('payment-status');
var urlParams = new URLSearchParams(window.location.search);
var sessionId = urlParams.get("session_id")
if (sessionId) {
fetch("/order?sessionId=" + sessionId).then(function(result){
return result.json()
}).then(function(session){
var sessionJSON = JSON.stringify(session, null, 2);
document.querySelector("pre").textContent = sessionJSON;
}).catch(function(err){
console.log('Error when fetching Checkout session', err);
});
}
</script>
</html>
i need help with product detail , customer name , amount on success page and if possible payment paid or not paid status on it.... cant find any tutorial on it or any detail step by step guide on it
i am close but cant get it to bullseyes please help me with it
yeah on success page all i get is payment status and blank
Looks like here is what happened:
Your Checkout Session defined success_url to success.html
Your success.html fired another request to "/success?session_id=xxx"
Your backend handled this with $app->get('/success', function...
It could be confusing to name both HTML in step 2 and the handling URL in step 3 as "success". You may want to use a different name such as "success" and "get-checkout-session" like Stripe example on Github. After that, debug your server log on step 3 to see whether you got the session id correctly and have retrieved the Customer Id.
There is more information to extract from a CheckoutSession. See Stripe's API Reference on available properties. You probably want to expand its payment_intent to see the amount and payment status.
I use the samples (https://github.com/stripe-samples/checkout-single-subscription/tree/master/server/php) from Stripe to create a subscription. What I don't really understand, how can I pass metadata from my index.html over script.js to the create-checkout-session.php.
I thought I just add data attributes to the index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Stripe</title>
<meta name="description" content="A demo of Stripe Payment Intents" />
<link rel="icon" href="favicon.ico" type="image/x-icon" />
<script src="https://js.stripe.com/v3/"></script>
<script src="./script.js" defer></script>
</head>
<body>
<div class="sr-root">
<div class="sr-main" style="display: flex;">
<div class="sr-container">
<section class="container">
<button id="basic-plan-btn" data-partner="name" data-package="basic">USD 6.90</button>
</section>
<section class="container">
<button id="pro-plan-btn" data-partner="name" data-package="premium">USD 11.90</button>
</section>
</div>
</div>
</div>
</body>
</html>
then I have to read them somehow out in the script.js. But that I don't really figure out how.
// Create a Checkout Session with the selected plan ID
var createCheckoutSession = function(priceId) {
return fetch("/fileadmin/restaurant/stripe/create-checkout-session.php", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({
priceId: priceId,
partner: 'name',
package: 'premium'
})
}).then(function(result) {
return result.json();
});
};
// Handle any errors returned from Checkout
var handleResult = function(result) {
if (result.error) {
var displayError = document.getElementById("error-message");
displayError.textContent = result.error.message;
}
};
/* Get your Stripe publishable key to initialize Stripe.js */
fetch("/fileadmin/restaurant/stripe/config.php")
.then(function(result) {
return result.json();
})
.then(function(json) {
var publishableKey = json.publishableKey;
var basicPriceId = json.basicPrice;
var proPriceId = json.proPrice;
var stripe = Stripe(publishableKey);
// Setup event handler to create a Checkout Session when button is clicked
document
.getElementById("basic-plan-btn")
.addEventListener("click", function(evt) {
createCheckoutSession(basicPriceId).then(function(data) {
// Call Stripe.js method to redirect to the new Checkout page
stripe
.redirectToCheckout({
sessionId: data.sessionId
})
.then(handleResult);
});
});
// Setup event handler to create a Checkout Session when button is clicked
document
.getElementById("pro-plan-btn")
.addEventListener("click", function(evt) {
createCheckoutSession(proPriceId).then(function(data) {
// Call Stripe.js method to redirect to the new Checkout page
stripe
.redirectToCheckout({
sessionId: data.sessionId
})
.then(handleResult);
});
});
});
by that I receive them in the create-checkout-session.php
<?php
require_once 'shared.php';
$domain_url = $config['domain'];
$checkout_session = \Stripe\Checkout\Session::create([
'success_url' => $domain_url . 'success.php?session_id={CHECKOUT_SESSION_ID}',
'cancel_url' => $domain_url . 'canceled.php',
'payment_method_types' => ['card'],
'mode' => 'subscription',
'allow_promotion_codes' => true,
'line_items' => [[
'price' => $body->priceId,
'quantity' => 1,
]],
'subscription_data' => ['trial_period_days' => 60],
'metadata' => [
'partner' => $body->partner,
'package' => $body->package
],
]);
echo json_encode(['sessionId' => $checkout_session['id']]);
Thank You.
What you've done adding to the JSON body of the fetch call looks right to me. If you're trying to set the 'name' and 'premium' values dynamically from some input, then take a look at this previous answer for some approaches for getting input values.
I'm trying stripe.redirectToCheckout in Laravel 6. And it's been days now, I can't find anything helpful on internet. I used strip documentation for creating a user session and redirectToCheckout and implemented stripe session in web/routes and redirectToCheckout in JavaScript.
The following is the button for pay with stripe
<button id="checkout-button"
data="{{$id}}" href="https://checkout.stripe.com/checkout.js"
role="link" style="width: 100%"
class="btn btn-dark">Pay with stripe
</button>
The following is the JavaScript function for redirectToCheckout
<script>
(function () {
var stripe = window.Stripe('pk_test_ZuGUA3XxCsWvZVbqnOkFMQnM00PV2c0Acm');
var checkoutButton = document.getElementById('checkout-button');
checkoutButton.addEventListener('click', function () {
// When the customer clicks on the button, redirect
// them to Checkout.
console.log('button clicked');
var product_name = document.getElementById('#p_name');
var product_price = document.getElementById('#p_price');
var name, price;
// var checkout_btn = document.getElementById('#checkout-button-plan_GI1dhi4ljEzk0R');
btn = $(this).attr('data');
console.log(btn);
stripe.redirectToCheckout({
items: [
// Replace with the ID of your SKU
{sku: 'sku****', quantity: 1}
],
successUrl: 'http://4c655de9.ngrok.io/success',
cancelUrl: 'http://4c655de9.ngrok.io/canceled',
clientReferenceId: btn
}).then(function (result) {
console.log('result');
// If `redirectToCheckout` fails due to a browser or network
// error, display the localized error message to your customer
// using `result.error.message`.
console.log(result.error.message);
});
});
})();
</script>
The following is the web/route.php function for \Stripe\Checkout\Session
Route::get('/', function () {
\Stripe\Stripe::setApiKey('sk****');
$session = \Stripe\Checkout\Session::create([
'success_url' => 'http://4c655de9.ngrok.io/success',
'cancel_url' => 'http://4c655de9.ngrok.io/canceled',
'payment_method_types' => ['card'],
'line_items' => [
[
'name' => 'T-shirt',
'description' => 'Comfortable cotton t-shirt',
'amount' => 1500,
'currency' => 'usd',
'quantity' => 2,
],
],
]);
$id = $session->id;
return view('home')->with('id', $id);
I've been trying to figure this out for days with no luck.
I'm trying to implement Stripe Payments Checkout into my website. The payment amount is on the payments page as a JS variable. I was able to get Basic Checkout working, but apparently that can't use a custom amount, or send any data to the PHP processing page (email, and some order attributes). I've been trying to use the Custom Checkout but I can't figure it out. Any help?
So far I have this in config.php:
<?php
require_once('vendor/autoload.php');
$stripe = array(
"secret_key" => "MY SECRET KEY IS HERE",
"publishable_key" => "MY PUBLISHED KEY IS HERE"
);
\Stripe\Stripe::setApiKey($stripe['secret_key']);
?>
and this is in a file called process.php:
<?php
require_once('./config.php');
$token = $_POST['stripeToken'];
$input = $_POST["totalprice"];
$customer = \Stripe\Customer::create(array(
'email' => 'customer#example.com',
'source' => $token
));
$charge = \Stripe\Charge::create(array(
'customer' => $customer->id,
'amount' => $input,
'currency' => 'usd'
));
echo $input;
?>
And in the initial PHP file I have:
<?php require_once('./config.php'); ?>
<form action="process.php" method="POST">
<script
src="https://checkout.stripe.com/checkout.js" class="stripe-button"
data-key="MY PUBLIC TEST KEY IS HERE"
data-amount= amt * 100
data-name="Test Name"
data-description="Widget"
data-image="/img/logo.jpg"
data-locale="auto"
>
<form type=hidden name="totalprice" value=amt*100 action="process.php" method="POST">
</script>
</form>
With that said though, I've had a bunch of other code I've tried before that hasn't worked, so this current code probably should be scrapped. I'd really appreciate any help I can get!
Well, following is the sample code of Custom Integration.
<script src="https://checkout.stripe.com/checkout.js"></script>
<button id="customButton">Purchase</button>
<script>
var handler = StripeCheckout.configure({
key: 'pk_test_6pRNASCoBOKtIshFeQd4XMUh',
image: 'https://stripe.com/img/documentation/checkout/marketplace.png',
locale: 'auto',
token: function(token) {
// You can access the token ID with `token.id`.
// Get the token ID to your server-side code for use.
}
});
document.getElementById('customButton').addEventListener('click', function(e) {
// Open Checkout with further options:
handler.open({
name: 'Stripe.com',
description: '2 widgets',
zipCode: true,
amount: 2000
});
e.preventDefault();
});
// Close Checkout on page navigation:
window.addEventListener('popstate', function() {
handler.close();
});
</script>
The source code is given on this page
So is that what you are looking for?
I keep receiving error code 400 on my stripe dashboard. It seems like im using the same stripe token more than once and this produces an error. Below is my code.
Js:
<script src="https://checkout.stripe.com/checkout.js"></script>
<script>
var handler = StripeCheckout.configure({
key: 'pk_test_******************',
image: '/img/documentation/checkout/marketplace.png',
token: function(token) {
/*$.post("php/charge.php",{stripeToken:token.id},function(data,status){
console.log("Data: "+ data+"\nStatus: "+status);
});*/
alert(token.used);//alerts false
$.post("php/charge.php",{stripeToken:token.id});
alert(token.used);// still alerts false
}
});
$('#myButton').on('click', function(e) {
// Open Checkout with further options
handler.open({
name: 'Demo Site',
description: '2 widgets',
currency: "cad",
amount: 2000
});
e.preventDefault();
});
// Close Checkout on page navigation
$(window).on('popstate', function() {
handler.close();
});
</script>
Php:
<?php
require_once('config.php');
$token = $_POST['stripeToken'];
$customer = \Stripe\Customer::create(array(
'email' => 'test#test.com',
'card' => $token
));
//try {
$charge = \Stripe\Charge::create(array(
"amount" => 1000, // amount in cents, again
"currency" => "cad",
"source" => $token,
"description" => "Example charge")
);
//}catch(\Stripe\Error\Card $e) {
// The card has been declined
//}
?>
Can anyone tell my why I cant charge a customer? How am I using a key multiple times?
You do use the token twice.
First, when creating the customer.
Second, when trying to charge the card.
Instead, you can create a customer and and then pass $customer->id to Stripe when you create the charge:
$charge = \Stripe\Charge::create(array(
"amount" => 1000, // amount in cents, again
"currency" => "cad",
"customer" => $customer->id,
"description" => "Example charge")
);
You have to create the customer to charge him multiple times.
1) Add the Credit card token to customer and create customer
2) Use the customer Id to charge users
if (isset($_POST['stripeToken'])){
$token = $_POST['stripeToken'];
// Create a Customer
$customer = \Stripe\Customer::create(array(
"source" => $token,
"description" => "Example customer")
);
// Charge the Customer instead of the card
\Stripe\Charge::create(array(
"amount" => 1000, # amount in cents, again
"currency" => "usd",
"customer" => $customer->id)
);
}
for more help visit: https://stripe.com/docs/tutorials/charges