Integrating stripe payments (JS and PHP) with a custom amount (JS variable) - javascript

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?

Related

Wordpress Api request using plugin

I want to make an API request using a simple wp plugin I created by submitting a form and the form will submit to action.php
<?php
/** * Plugin Name: Taofeeq Wodpress Plugin demo
* Plugin URI: #
* Description: Display content using a shortcode to insert in a page or post
* Version: 0.1
* Text Domain: tbare-wordpress-plugin-demo
* Author: Taofeeq Tajudeen
* Author URI: #
*/
function tt_wordpress_plugin_demo($atts) {
?>
<form id="ct" method="POST">
<label for="source">Source:</label>
<input type="txt" name="source" required>
<label for="target">Target:</label>
<input type="text" name="target" id= "trg" required>
<input type="submit" value="Submit">
</form>
<?php
}
add_shortcode('tt-plugin-demo', 'tt_wordpress_plugin_demo');
action.php
`<?php
if (isset($_post['submit'])){
$source = $_post['source'];
$target = $_post['target'];
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => 'https://api.apyhub.com/data/convert/currency',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => '',
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => 'POST',
CURLOPT_POSTFIELDS =>'{
"source":$source,
"target":$target
}',
CURLOPT_HTTPHEADER => array(
'Content-Type: application/json',
'apy-token: my_api_token'
),
));
$response = curl_exec($curl);
curl_close($curl);
return $response;
}
What I need assistance with is submitting the form without reloading the page where I insert the form shortcode. Also how to submit it to action.php since the file is in a plugin? Maybe you guys can assist me in a way that instead of submitting to action.php, it will submit to the same page where i will insert the action.php codes and action.php will no longer be needed.
I tried adding everything on the same page and after submission, the page will reload and return nothing.
I tried submitting it to action.php, it says page not found.
I tried submitting it to
action="<?php echo esc_attr(admin_url( 'admin-post.php' ) ); ?>"
but it brought me to the admin login page and after logging in it displays nothing.
Lastly, I don't know how to submit without reloading the page.

how do we retrive checkout session in stripe success page

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.

static amount not variable

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.

How can i get a stripe token on my controller with checkout?

i'm trying to get a stripe token when i use checkout, but when i submit the embeded form i don't have a POST method and i don't know how i can have the token on my php controller too.
Here is my code :
<script>
var handler = StripeCheckout.configure({
key: 'pk_test_WWlLRtqEY2yfJUlfA4TRRcyf',
image: 'https://stripe.com/img/documentation/checkout/marketplace.png',
locale: 'auto',
token: function(token) {
console.log(token.id);
}
});
document.getElementById('customButton').addEventListener('click', function(e) {
// Open Checkout with further options:
handler.open({
name: 'Musée du Louvre',
description: 'Biletterie en ligne',
currency: 'eur',
amount: '{{ price }}' * 100,
email: '{{ mail }}',
allowRememberMe: false,
});
e.preventDefault();
});
// Close Checkout on page navigation:
window.addEventListener('popstate', function() {
handler.close();
});
i tried with this :
<form post="" method="post">
my script code
</form>
but when i click on pay the page don't resfresh.
Someone can help me?
The idea is to change the code in the token callback to send the token to your server instead of logging it to the console.
Change your form to have a hidden field for the stripe token id and the email entered by the customer:
<form action="/your/route" method="POST" id="payment-form">
<input type="hidden" id="stripeToken" name="stripeToken" value="tok_XXX" />
<input type="hidden" id="stripeEmail" name="stripeEmail" value="email#example.com" />
</form>
And then change your JS to set those values and submit the form:
token: function(token) {
$("#stripeToken").val(token.id);
$("#stripeEmail").val(token.email);
$("#payment-form").submit();
}
This will submit your form and your route on the server will receive the stripeToken and the stripeEmail values in the POST parameters.

Google Invisible Recaptcha: Cannot contact reCAPTCHA. Check your connection and try again

I'm trying to implement Google Invisible Recaptcha on a website online after the domain registration on google recaptcha site, I followed the documentation, but not works. When send the form, show the alert error:
Cannot contact reCAPTCHA. Check your connection and try again.
This is my code (only the interesting points), HTML/JS:
<script src='https://www.google.com/recaptcha/api.js?
onload=onloadCallback&render=explicit&hl=it' async defer></script>
</head>
<body>
<form method="post" action="contact.php" name="contactform" id="contactform">
<fieldset>
<input name="email" type="text" id="email" required/>
<input type="submit" class="submit" id="submit" value="Contact!" />
</fieldset>
</form>
<script type="text/javascript">
var onSubmit = function(token) {
// ajax call
};
var onloadCallback = function() {
grecaptcha.render('submit', {
'sitekey' : 'PUBLIC_KEY',
'callback' : onSubmit
});
};
</script>
and the contact.php file:
class Captcha
{
private $key = 'PRIVATE_KEY';
public $goo;
public function verify()
{
$postData = http_build_query(
array(
'secret' => $this->key,
'response' => $this->goo,
'remoteip' => $_SERVER['REMOTE_ADDR']
)
);
$options = array('http' =>
array(
'method' => 'POST',
'header' => 'Content-type: application/x-www-form-urlencoded',
'content' => $postData
)
);
$context = stream_context_create($options);
$response = file_get_contents('https://www.google.com/recaptcha/api/siteverify', false, $context);
return json_decode($response);
}
}
$captcha = new Captcha();
$captcha->goo = $_POST['g-recaptcha-response'];
$response = $captcha->verify();
if (!$response->success) {
// not works
}
else {
// works
}
I don't understand what is incorrect.
Thanks for help!

Categories