Integrar pasarela Stripe en mi web con 9 pasos
Hola que tal amigos , bienvenidos a una entrada más ...
siendo ya muy tarde se me ocurrió pasarle como realizé la integración de la pasarela de pago Stripe
Esta pasarela nos permite cobrar desde nuestra web o nuestra app móvil a nuestros clientes ya sea que estemos vendiendo productos o sevicios.
Así que vamos a darle y empezemos lo bueno .
1.- Primeramente hay que registrarse en la página oficial de https://stripe.com/ , de entrada nos ofrece todo un manual de lo que podemos hacer con esta pasarela de pago .Me enfocaré en el pago con tarjeta para no llenarlos de información .
2.-Debemos tener en cuenta que al registrarnos nuestras dos llaves , las cuales nos permitirán acceder a la api de esta plataforma ,es importante resguardar esta información para más adelante .
3.-Vamos a comenzar colocando estos scripts en nuestro archivo.
<script src="https://js.stripe.com/v3/"></script>
<script src="https://polyfill.io/v3/polyfill.min.js?version=3.52.1&features=fetch"></script>
4.- Además colocaremos estilos propios que nos brinda la pasarela al archivo le llamaremos global.css
/* Variables */
* {
box-sizing: border-box;
}
body {
font-family: -apple-system, BlinkMacSystemFont, sans-serif;
font-size: 16px;
-webkit-font-smoothing: antialiased;
justify-content: center;
align-content: center;
height: 100vh;
width: 100vw;
}
.formstripe {
width: 30vw;
min-width: 26em;
align-self: center;
/* box-shadow: 0px 0px 0px 0.5px rgba(50, 50, 93, 0.1),
0px 2px 5px 0px rgba(50, 50, 93, 0.1), 0px 1px 1.5px 0px rgba(0, 0, 0, 0.07);*/
border-radius: 7px;
}
.result-message {
line-height: 22px;
font-size: 16px;
}
.result-message a {
color: rgb(89, 111, 214);
font-weight: 600;
text-decoration: none;
}
.hidden {
display: none;
}
#card-error {
color: rgb(105, 115, 134);
text-align: left;
font-size: 13px;
line-height: 17px;
margin-top: 12px;
}
#card-element {
border-radius: 4px 4px 0 0 ;
padding: 12px;
border: 1px solid rgba(50, 50, 93, 0.1);
height: 44px;
width: 100%;
background: white;
}
#payment-request-button {
margin-bottom: 32px;
}
/* Buttons and links */
.buttons {
background: #5469d4;
color: #ffffff;
font-family: Arial, sans-serif;
border-radius: 0 0 4px 4px;
border: 0;
padding: 12px 16px;
font-size: 16px;
font-weight: 600;
cursor: pointer;
display: block;
transition: all 0.2s ease;
box-shadow: 0px 4px 5.5px 0px rgba(0, 0, 0, 0.07);
width: 100%;
}
.buttons:hover {
filter: contrast(115%);
}
.buttons:disabled {
opacity: 0.5;
cursor: default;
}
/* spinner/processing state, errors */
.spinner,
.spinner:before,
.spinner:after {
border-radius: 50%;
}
.spinner {
color: #ffffff;
font-size: 22px;
text-indent: -99999px;
margin: 0px auto;
position: relative;
width: 20px;
height: 20px;
box-shadow: inset 0 0 0 2px;
-webkit-transform: translateZ(0);
-ms-transform: translateZ(0);
transform: translateZ(0);
}
.spinner:before,
.spinner:after {
position: absolute;
content: "";
}
.spinner:before {
width: 10.4px;
height: 20.4px;
background: #5469d4;
border-radius: 20.4px 0 0 20.4px;
top: -0.2px;
left: -0.2px;
-webkit-transform-origin: 10.4px 10.2px;
transform-origin: 10.4px 10.2px;
-webkit-animation: loading 2s infinite ease 1.5s;
animation: loading 2s infinite ease 1.5s;
}
.spinner:after {
width: 10.4px;
height: 10.2px;
background: #5469d4;
border-radius: 0 10.2px 10.2px 0;
top: -0.1px;
left: 10.2px;
-webkit-transform-origin: 0px 10.2px;
transform-origin: 0px 10.2px;
-webkit-animation: loading 2s infinite ease;
animation: loading 2s infinite ease;
}
@-webkit-keyframes loading {
0% {
-webkit-transform: rotate(0deg);
transform: rotate(0deg);
}
100% {
-webkit-transform: rotate(360deg);
transform: rotate(360deg);
}
}
@keyframes loading {
0% {
-webkit-transform: rotate(0deg);
transform: rotate(0deg);
}
100% {
-webkit-transform: rotate(360deg);
transform: rotate(360deg);
}
}
5.- Despues de hacer lo anterior, vamos a colocar el formulario de stripe
<form action="" method="post" id="payment-form" class="formstripe" style="display: none;">
<div class="form-row">
<label for="card-element">
Tarjeta de Credito o Debito
</label>
<div id="card-element">
<!-- A Stripe Element will be inserted here. -->
</div>
<!-- Used to display form errors. -->
<div id="card-errors" role="alert"></div>
</div>
<input type="hidden" id="monto">
<input type="hidden" id="nota">
<button id="button-text" class="buttons">Pagar</button>
</form>
6.- Lo podriamos hacer con submit pero en mi caso les pondre mi archivo js para que se den una idea de como realizarlo con ajax
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 stripe = Stripe("aqui va la llave publica que nos brinda stripe");
var elements = stripe.elements();
var card = elements.create('card', {style: style});
card.mount('#card-element');
$("#button-text").text('Pagar');
// Handle real-time validation errors from the card Element.
card.addEventListener('change', function(event) {
var displayError = document.getElementById('card-errors');
if (event.error) {
displayError.textContent = event.error.message;
} else {
displayError.textContent = '';
}
});
// Handle form submission.
var form = document.getElementById('payment-form');
form.addEventListener('submit', function(event) {
event.preventDefault();
stripe.createToken(card).then(function(result) {
if (result.error) {
// Inform the user if there was an error.
var errorElement = document.getElementById('card-errors');
errorElement.textContent = result.error.message;
} else {
// Send the token to your server.
stripeTokenHandler(result.token);
}
});
});
function stripeTokenHandler(token) {
//$("#button-text").prop("disabled", true);
var totalnota=localStorage.getItem('total');
var notaremision=localStorage.getItem('idnota');
// Insert the token ID into the form so it gets submitted to the server
var form = document.getElementById('payment-form');
var hiddenInput = document.createElement('input');
hiddenInput.setAttribute('type', 'hidden');
hiddenInput.setAttribute('name', 'stripeToken');
hiddenInput.setAttribute('value', token.id);
form.appendChild(hiddenInput);
var input1=document.createElement('input');
input1.setAttribute('type','hidden');
input1.setAttribute('name', 'monto');
input1.setAttribute('value', totalnota);
form.appendChild(input1);
var input2=document.createElement('input');
input2.setAttribute('type','hidden');
input2.setAttribute('name', 'nota');
input2.setAttribute('value', notaremision);
form.appendChild(input2);
// Submit the form
// form.submit();
//
$.ajax({
type: 'POST',
dataType:'json',
url: 'pedidos/stripe-pago.php',
data : $("#payment-form").serialize(),
async:false,
success: function(msj) {
console.log(msj);
if (msj.respuesta==1) {
CompraRealizada(msj.idnota);
}
if (msj.respuesta==0) {
Rechazada(msj.idnota);
}
},
error: function() { alert("Error leyendo fichero jsonP"); }
});
}
function CompraRealizada(idnota) {
var datos="idnota="+idnota;
$.ajax({
type: 'POST',
url: 'pedidos/comprarealizada.php',
data : datos,
success: function(msj) {
$("#contenedor").html(msj);
},
error: function() { alert("Error leyendo fichero jsonP"); }
});
}
function Rechazada(idnota) {
var datos="idnota="+idnota;
$.ajax({
type: 'POST',
url: 'pedidos/rechazada.php',
data : datos,
success: function(msj) {
$("#contenedor").html(msj);
},
error: function() { alert("Error leyendo fichero jsonP"); }
});
}
7.- Como ven hay funciones extras que me sirven para realizar el llamado de acuerdo a la respuesta que me brinda mi archivo php , el cual les mostrare enseguida .
require_once("../clases/stripe-php-master/init.php");
\Stripe\Stripe::setApiKey('llave privada que nos brinda stripe');
$totalapagar=(int)$total1;
$fecha_pago = date('Y-m-d H:i:s');
$idnota= $nota.'-'.$fecha_pago;
$charge = \Stripe\Charge::create([
"amount" => $totalapagar,
"currency" => "mxn",
"description" => "Pago en mi tienda...",
"source" => $token,
"metadata" => ["order_id" => $idnota]
]);
if ($charge->status=='succeeded') {
$vresponse['cargo']=$charge;
$vresponse['respuesta']=1;
$vresponse['idnota']=$nota;
}else{
$vresponse['respuesta']=0;
$vresponse['idnota']=$nota;
}
8.- Es importante importar la libreria que nos brinda stripe y que el monto sea en centavos , en mi caso estoy usando el currency para la moneda mexicana , ustedes podran utilizar la que más les convenga.
9.- Como ven al finales importante validar si se realizó correctamente el pago para devolver la respuesta.
Comentarios
Publicar un comentario
Hola que tal,dime tu opinión