I'm using stripe with checkout but when i want to pay it return this error
You did not set a valid publishable key. Call Stripe.setPublishableKey() with your publishable key.
I have 3 files (config.php - stripeIPN.php and the html where is button)
config.php
require_once "stripe-php-master/init.php";
$stripeDetails = array(
"secretKey" => "sk_test_xxx",
"publishableKey" => "pk_test_xxx"
);
\Stripe\Stripe::setApiKey($stripeDetails['secretKey']);
$pubkey = json_encode($stripeDetails['publishableKey']);
return $pubkey;
stripeIPN.php
require_once "config.php";
\Stripe\Stripe::setVerifySslCerts(false);
$token = $_POST['stripeToken'];
$charge = \Stripe\Charge::create(array(
"amount" => 100,
"currency" => "eur",
"description" => "",
"source" => $token
));
html
<script src="https://js.stripe.com/v3/"></script>
<div id="button-stripe-vab">
<form action="stripeIPN.php" method="POST">
<script id="stripe-link"
src="https://checkout.stripe.com/checkout.js" class="stripe-button"
data-key=""
data-amount=""
data-name=""
data-description=""
data-image="image.png"
data-locale="auto"
data-label="Pay with card">
</script>
</form>
</div>
in data-key i should to add my publishable key and in effect, the payment works, if i write it.
But i want to add it with `Ajax:
$.ajax({
type: "POST",
url: "config.php",
dataType:"json",
success: function (result) { //se funziona
var pubkey = JSON.parse(JSON.stringify(result));
$('#stripe-link').attr("data-key",pubkey);
}
});
I know my code is good because ajax works and with firebug i know that data-key after ajax has my publishable key but why stripe button return error ?
I have a doubt: maybe is it possible that the stripe button (so the DOM) is created before the execution of ajax?
Thanks a lot
try below:-
var pubKey = "Your_key_here";
$.ajax({
type: "POST",
url: "config.php",
dataType:"json",
data: { data_key: pubKey }
success: function (result) { //se funziona
var pubkey = JSON.parse(JSON.stringify(result));
}
});
Related
I wrote a simple PHP script to make PayPal popup payment button :
<!-- Load the required checkout.js script -->
<script src="https://www.paypalobjects.com/api/checkout.js" data-version-4></script>
<!-- Load the required Braintree components. -->
<script src="https://js.braintreegateway.com/web/3.87.0/js/client.min.js?"></script>
<script src="https://js.braintreegateway.com/web/3.87.0/js/paypal-checkout.min.js"></script>
<script type="text/javascript" src="js/jquery.min.js"></script>
<script>
<?php
require_once 'vendor/lib/Braintree.php';
$access_token = 'access_token$sandbox$...3';
$gateway = new Braintree\Gateway([
'accessToken' => $access_token,
]);
$clientToken = $gateway->clientToken()->generate();
?>
paypal.Button.render({
braintree: braintree,
client: {
//production: '<?= $clientToken ?>',
sandbox: '<?= $clientToken ?>'
},
env: 'sandbox',
style: {
shape: 'rect',
color: 'blue',
layout: 'horizontal',
label: 'pay',
},
payment: function (data, actions) {
return actions.braintree.create({
flow: 'checkout', // Required
amount: 10.00, // Required
currency: 'USD', // Required
intent: 'sale',
enableShippingAddress: false
});
},
onAuthorize: function (payload) {
$.ajax({
url : 'verify.php',
type : 'POST',
data: {
"payment_method_nonce": payload.nonce
},
success : function (result) {
alert(result);
},
error : function () {
alert(result);
}
});
},
}, '#paypal-button');
</script>
<div id="paypal-button"></div>
All steps (including settle) are working but the problem is that I have some JS errors with code 401 from PayPal server because of Client Id as below :
https://pasteboard.co/PABp8HzbdfhB.png
Failed to load resource: the server responded with a status of 401 ()
I searched in PayPal & Braintree docs but couldn't find how to pass my client id. All manuals are about older versions of SDK!
So what's the solution?
Link a PayPal sandbox account in the Braintree gateway settings, Processing.
I want to create a custom form (for name, email, adress, etc.) with stripe, but I don't know how to get the form data, that can be used in my php file. Few years back it was possible to send everything easlily with the post method,but now I can't figure out how it is possible to customize the given form.
The JS code:
fetch("../create.php", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(purchase)
})
.then(function(result) {
return result.json();
})
.then(function(data) {
var elements = stripe.elements();
var card = elements.create("card", { style: style });
card.mount("#card-element");
card.on("change", function (event) {
document.querySelector("button").disabled = event.empty;
document.querySelector("#card-error").textContent = event.error ? event.error.message : "";
});
var form = document.getElementById("payment-form");
form.addEventListener("submit", function(event) {
event.preventDefault();
const name = form.querySelector('#name');
payWithCard(stripe, card, data.clientSecret);
});
});
PHP:
<?php
require 'vendor/autoload.php';
\Stripe\Stripe::setApiKey('sk_test:my_api_key');
function calculateOrderAmount(array $items): int {
return 1400;
}
header('Content-Type: application/json');
try {
$json_str = file_get_contents('php://input');
$json_obj = json_decode($json_str);
$paymentIntent = \Stripe\PaymentIntent::create([
'amount' => calculateOrderAmount($json_obj->items),
'currency' => 'usd',
]);
$output = [
'clientSecret' => $paymentIntent->client_secret,
];
echo json_encode($output);
} catch (Error $e) {
http_response_code(500);
echo json_encode(['error' => $e->getMessage()]);
}
HTML:
<form id="payment-form">
<div id="card-element"><!--Stripe.js injects the Card Element--></div>
<button id="submit">
<div class="spinner hidden" id="spinner"></div>
<span id="button-text">Pay now</span>
</button>
<p id="card-error" role="alert"></p>
<p class="result-message hidden">
Payment succeeded, see the result in your
Stripe dashboard. Refresh the page to pay again.
</p>
</form>
With async payment flows you need to handle more of the payment flow client-side to support things like SCA and 3D Secure. Usually this means sending information to your server with async JavaScript calls rather than an HTML form.
You mentioned form fields like name, email, etc. in your question, but the code you shared doesn't contain anything like that, so it's difficult to provide an answer specific to your situation. Instead I can provide some basic guidance...
If you have an HTML element on your page like this:
<input id="email" type="email">
You can get the value of that input using JavaScript like this:
var email = document.querySelector('#email').value;
Then you can send it to your server async using code like this:
fetch("server.php", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({
email: email
})
}).then(/*...*/);
Then, in server.php you can do something like this to get the email value:
<?php
$rawBody = #file_get_contents('php://input');
$body = json_decode($body, true);
$email = $body['email'];
You should of course add in error handling, server-side input validation, etc., but those are the basic building blocks.
I have the following fairly basic implementation of Stripe. It successfully creates a new customer but it won´t charge and return the "SUCCESS ERROR" message in the console. The token seems to be created correctly so my guess is i am missing something in the charge.php.
NOTE: I have not used composer to install stripe but load the init.php in config.php (could that be the problem?). Also is the neccessary even though i use ajax?(removing it won´t solve the problem though)
Index.php
<?php require_once('stripe/config.php'); ?>
<form action="charge.php" method="post">
<script src="https://checkout.stripe.com/checkout.js"></script>
<button id="customButton">Purchase</button>
<script>
var handler = StripeCheckout.configure({
key: 'pk_test_*******************',
token: function(token) {
// Use the token to create the charge with a server-side script.
// You can access the token ID with `token.id`
console.log(token)
$.ajax({
url: 'stripe/charge.php',
type: 'post',
data: {tokenid: token.id, email: token.email},
success: function(data) {
if (data == 'success') {
console.log("Card successfully charged!");
}
else {
console.log("Success Error!");
}
},
error: function(data) {
console.log("Ajax Error!");
console.log(data);
}
}); // end ajax call
}
});
$('#customButton').on('click', function(e) {
// Open Checkout with further options
handler.open({
name: 'shipping free',
description: '2 widgets',
amount: 2000
});
e.preventDefault();
});
// Close Checkout on page navigation
$(window).on('popstate', function() {
handler.close();
});
</script>
</form>
CONFIG.PHP
<?php require_once('init.php');
$stripe = array(
secret_key => 'sk_test_************************',
publishable_key => 'pk_test_************************'
);
Stripe::setApiKey($stripe['secret_key']);
?>
CHARGE.PHP
<?php require_once('/config.php');
$tokenid = $_POST['tokenid'];
$email = $_POST['email'];
$customer = \Stripe\Customer::create(array(
'email' => $email,
'card' => $tokenid
));
$charge = \Stripe\Charge::create(array(
'email' => $email,
'card' => $tokenid
'amount' => 5000,
'currency' => 'usd',
));
echo '<h1>Successfully charged $50.00!</h1>';
?>
In this line, 'card' => $tokenid. you are missing comma(,).
Add comma in that line.
$charge = \Stripe\Charge::create(array(
'email' => $email,
'card' => $tokenid,
'amount' => 5000,
'currency' => 'usd',
));
Using Stripe, I want to store a customer email address from the email they supplied in Checkout. Unfortunately, posting stripeEmail in my charge.php file returns null.
How can I return the email from checkout so I can use it to send a receipt?
Here's my form code:
<script src="https://checkout.stripe.com/v2/checkout.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.js"></script>
<form action="charge.php" method="post">
<input type="hidden" id="amount" name="chargeAmount"/>
<button data-charge-amount="300000" data-charge-name="Name" data-charge-description="Description">Select Pledge Level</button>
<button data-charge-amount="123123" data-charge-name="Name2" data-charge-description="Description2">Donate</button>
</form>
<script>
$('button').click(function(){
var token = function(res){
var $theToken = $('<input type=hidden name=stripeToken />').val(res.id);
$('form').append($theToken).submit();
};
var amount = $(this).data("chargeAmount");
var name = $(this).data("chargeName");
var description = $(this).data("chargeDescription");
$('input#amount').val(amount);
StripeCheckout.open({
key: 'pk_test_xxxxxxxxxxxxxxxxxxxxxxxx',
address: true,
amount: amount,
currency: 'usd',
name: name,
description: description,
panelLabel: 'Pledge',
token: token,
});
return false;
});
</script>
Here is my charge.php code:
<?php
require_once('./config.php');
$token = $_POST['stripeToken'];
$amount = $_POST['chargeAmount'];
$customer = \Stripe\Customer::create(array(
'email' => $email,
'card' => $token,
));
$charge = \Stripe\Charge::create(array(
'customer' => $customer->id,
'amount' => $amount,
'currency' => 'usd',
));
?>
Here is my config.php code:
<?php
require_once('./stripe-php-2.1.2/init.php');
$stripe = array(
"secret_key" => "sk_test_xxxxxxxxxxxxxxxxxxxxxxxx",
"publishable_key" => "pk_test_xxxxxxxxxxxxxxxxxxxxxxxx"
);
\Stripe\Stripe::setApiKey($stripe['secret_key']);
?>
Any help would be much appreciated.
THANKS!
The issue here is that you're using Custom Checkout which means that Checkout won't post the data to your server automatically but instead give it in the token callback. In your case you're only retrieving the token id here which is why you are not seeing the email.
Update your code so that the token callback also retrieves the email and send it in the stripeEmail parameter:
var token = function(res){
var $theToken = $('<input type="hidden" name="stripeToken" />').val(res.id);
var $theEmail = $('<input type="hidden" name="stripeEmail" />').val(res.email);
$('form').append($theToken).append($theEmail).submit();
};
I just spent all night on this problem! #Koopajah helped a ton, so here's my entire solution in case anyone else happens to run across this.
Here's the form:
<form action="/charge.php" method="post">
<input
type="submit"
id="payMe"
class="btn btn-default btn-lg btn-success"
value=" Pay "
data-key="xxxxxxx"
data-amount="199"
data-currency="usd"
data-name="Stuff"
data-description="20 Whozits ($19.99)"
data-image="images/image.jpg"
data-bitcoin="true"
/>
<script src="https://checkout.stripe.com/v2/checkout.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js"></script>
<script>
$(document).ready(function() {
$('#payMe').on('click', function(event) {
event.preventDefault();
var $button = $(this),
$form = $button.parents('form');
var opts = $.extend({}, $button.data(), {
token: function(result) {
var $theToken = $('<input>').attr({ type: 'hidden', name: 'stripeToken', value: result.id })
var $theEmail = $('<input>').attr({ type: 'hidden', name: 'stripeEmail', value: result.email })
$form.append($theToken).append($theEmail).submit();
}
});
StripeCheckout.open(opts);
});
});
</script>
</form>
And here's charge.php:
<?php
require_once('vendor/autoload.php');
$stripe = array(
"secret_key" => "xxxx",
"publishable_key" => "xxxx"
);
\Stripe\Stripe::setApiKey($stripe['secret_key']);
$token = $_POST['stripeToken'];
$email = $_POST['stripeEmail'];
\Stripe\Customer::create(array(
"source" => $token,
"email" => $email,
"description" => "It Worked!"
));
try {
$charge = \Stripe\Charge::create(array(
"amount" => 199, // amount in cents, again
"currency" => "usd",
"source" => $_POST['stripeToken'],
"description" => "Cat Facts"));
} catch(\Stripe\Error\Card $e) {
$error = $e->getMessage();
}
?>
I have had a very similar issue but am using node.js. I modified koopajah's answer and placed it in a charge.js file
const token = req.body.stripeToken;<br>
const email = req.body.stripeEmail;
and then I used this email variable like so...
return stripe.charges.create({
// ensures we send a number, and not a string
amount: parseInt(process.env.STRIPE_COST, 10),
currency: process.env.STRIPE_CCY,
source: token,
description: 'My product', // 👈 remember to change this!
receipt_email: email, // that line sends a receipt email to the customer, you can customise that email inside stripe
metadata: {},
});
I hope this is a useful answer to someone.
I was previously charging users a fixed amount, say, "$20," but I wanted to create a donation box that would accept variables. I understand that there is "StripeCheckout.open," but does anyone know how it would look?
That being said, I am currently using the code below to charge a user a fixed amount, though I'm desperate to find out how to set a variable amount that can be charged.
<?php
require_once('config.php');
$token = $_POST['stripeToken'];
$customer = Stripe_Customer::create(array(
'email' => 'customer#example.com',
'card' => $token
));
$charge = Stripe_Charge::create(array(
'customer' => $customer->id,
'amount' => variable,
'currency' => 'cad'
));
?>
Ok, you probably should use V2 instead of V1, and what you want to do is something like this:
$('#sendPledgeBtn').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:'make-payment.php',
cache: false,
data:{ email : email, token:tokenId },
type:'POST'
})
.done(function(data){
// If Payment Success
$('#sendPledgeBtn').html('Thank You').addClass('disabled');
})
.error(function(){
$('#sendPledgeBtn').html('Error, Unable to Process Payment').addClass('disabled');
});
},500);
$('form:first-child').append($input).submit();
};
StripeCheckout.open({
key: 'pk_live_XXXXXXXXX', // Your Key
address: false,
amount: $('#amount').val(),
currency: 'usd',
name: 'Canted Pictures',
description: 'Donation',
panelLabel: 'Checkout',
token: token
});
return false;
});