Getting more info abount transaction ad move js partial to js file

This commit is contained in:
vinchent 2024-08-07 14:35:30 +02:00
parent 625929cf25
commit 1372542620
7 changed files with 109 additions and 185 deletions

View File

@ -1,6 +1,7 @@
package main package main
import ( import (
"myapp/internal/cards"
"net/http" "net/http"
"strconv" "strconv"
@ -8,7 +9,7 @@ import (
) )
func (app *application) VirtualTerminal(w http.ResponseWriter, r *http.Request) { func (app *application) VirtualTerminal(w http.ResponseWriter, r *http.Request) {
if err := app.renderTemplate(w, r, "terminal", &templateData{}, "stripe-js"); err != nil { if err := app.renderTemplate(w, r, "terminal", &templateData{}); err != nil {
app.errorLog.Println(err) app.errorLog.Println(err)
} }
} }
@ -28,6 +29,27 @@ func (app *application) PaymentSucceeded(w http.ResponseWriter, r *http.Request)
paymentAmount := r.Form.Get("payment_amount") paymentAmount := r.Form.Get("payment_amount")
paymentCurrency := r.Form.Get("payment_currency") paymentCurrency := r.Form.Get("payment_currency")
card := cards.Card{
Secret: app.config.stripe.secret,
Key: app.config.stripe.key,
}
pi, err := card.RetrievePaymentIntent(paymentIntent)
if err != nil {
app.errorLog.Println(err)
return
}
pm, err := card.GetPaymentMethod(paymentMethod)
if err != nil {
app.errorLog.Println(err)
return
}
lastFour := pm.Card.Last4
expiryMonth := pm.Card.ExpMonth
expiryYear := pm.Card.ExpYear
data := make(map[string]interface{}) data := make(map[string]interface{})
data["cardholder"] = cardHolder data["cardholder"] = cardHolder
data["email"] = email data["email"] = email
@ -35,6 +57,10 @@ func (app *application) PaymentSucceeded(w http.ResponseWriter, r *http.Request)
data["pm"] = paymentMethod data["pm"] = paymentMethod
data["pa"] = paymentAmount data["pa"] = paymentAmount
data["pc"] = paymentCurrency data["pc"] = paymentCurrency
data["last_four"] = lastFour
data["expiry_month"] = expiryMonth
data["expiry_year"] = expiryYear
data["bank_return_code"] = pi.LatestCharge.ID
if err := app.renderTemplate(w, r, "succeeded", &templateData{ if err := app.renderTemplate(w, r, "succeeded", &templateData{
Data: data, Data: data,
@ -58,7 +84,7 @@ func (app *application) ChargeOnce(w http.ResponseWriter, r *http.Request) {
if err := app.renderTemplate(w, r, "buy-once", &templateData{ if err := app.renderTemplate(w, r, "buy-once", &templateData{
Data: data, Data: data,
}, "stripe-js"); err != nil { }); err != nil {
app.errorLog.Println(err) app.errorLog.Println(err)
} }
} }

View File

@ -1,4 +1,4 @@
{{ template "base" .}} {{ template "base" . }}
{{ define "title" }} {{ define "title" }}
Buy one widget Buy one widget
{{ end }} {{ end }}
@ -9,7 +9,6 @@ Buy one widget
<img src="/static/img/widget.jpeg" <img src="/static/img/widget.jpeg"
alt="widget" alt="widget"
class="image-fluid rounded mx-auto d-block"> class="image-fluid rounded mx-auto d-block">
<div class="alert alert-danger text-center d-none" id="card-messages"></div> <div class="alert alert-danger text-center d-none" id="card-messages"></div>
<form action="/payment-succeeded" <form action="/payment-succeeded"
method="post" method="post"
@ -20,10 +19,9 @@ Buy one widget
novalidate=""> novalidate="">
<input type="hidden" name="product_id" value="{{$widget.ID}}"> <input type="hidden" name="product_id" value="{{$widget.ID}}">
<input type="hidden" id="amount" name="amount" value="{{$widget.Price}}"> <input type="hidden" id="amount" name="amount" value="{{$widget.Price}}">
<h3 class="mt-2 mb-3 text-center">{{$widget.Name}}: {{formatCurrency $widget.Price}}</h3> <h3 class="mt-2 mb-3 text-center">{{$widget.Name}}: {{ formatCurrency $widget.Price }}</h3>
<p class="mt-2 mb-3 text-center">{{$widget.Description}}</p> <p class="mt-2 mb-3 text-center">{{$widget.Description}}</p>
<hr> <hr>
<div class="mb-3"> <div class="mb-3">
<label for="cardholder-name" class="form-label">Cardholder Name</label> <label for="cardholder-name" class="form-label">Cardholder Name</label>
<input type="text" <input type="text"
@ -53,7 +51,7 @@ Buy one widget
<a href="javascript:void(0)" <a href="javascript:void(0)"
id="pay-button" id="pay-button"
class="btn btn-primary" class="btn btn-primary"
onclick="val()">Charge Card</a> onclick="val({{.API}})">Charge Card</a>
<div class="text-center d-none" id="processing-payment"> <div class="text-center d-none" id="processing-payment">
<div class="spinner-border text-primary" role="status"> <div class="spinner-border text-primary" role="status">
<span class="visually-hidden">Loading...</span> <span class="visually-hidden">Loading...</span>
@ -78,5 +76,7 @@ Buy one widget
</form> </form>
{{ end }} {{ end }}
{{ define "js" }} {{ define "js" }}
{{ template "stripe-js" . }} <script src="https://js.stripe.com/v3/"></script>
<script src="/static/js/stripe.js"></script>
<script>stripeInit('{{.StripePubKey}}');</script>
{{ end }} {{ end }}

View File

@ -1,136 +0,0 @@
{{define "stripe-js"}}
<script src="https://js.stripe.com/v3/"></script>
<script>
let card;
let stripe;
const cardMessages = document.getElementById("card-messages");
const payButton = document.getElementById("pay-button");
const processing = document.getElementById("processing-payment");
stripe = Stripe('{{.StripePubKey}}');
function hidePayButton() {
payButton.classList.add("d-none");
processing.classList.remove("d-none");
}
function showPayButton() {
payButton.classList.remove("d-none");
processing.classList.add("d-none");
}
function showCardError(msg) {
cardMessages.classList.add("alert-danger");
cardMessages.classList.remove("alert-success");
cardMessages.classList.remove("d-none");
cardMessages.innerText = msg;
}
function showCardSuccess() {
cardMessages.classList.add("alert-success");
cardMessages.classList.remove("alert-danger");
cardMessages.classList.remove("d-none");
cardMessages.innerText = "Trasaction successful";
}
function val() {
let form = document.getElementById("charge_form");
if (form.checkValidity() === false) {
this.event.preventDefault();
this.event.stopPropagation();
form.classList.add("was-validated");
return;
}
form.classList.add("was-validated");
hidePayButton();
let amountToCharge = parseFloat(document.getElementById("amount").value);
let payload = {
amount: amountToCharge,
currency: 'eur',
};
const requestOptions = {
method: 'post',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify(payload),
};
fetch("{{.API}}/api/payment-intent", requestOptions)
.then(response => response.text())
.then(response => {
let data;
try {
data = JSON.parse(response);
stripe.confirmCardPayment(data.client_secret, {
payment_method: {
card: card,
billing_details: {
name: document.getElementById("cardholder-name").value,
}
}
}).then(function(result) {
if (result.error) {
// card declined, or sth went wrong with the card
showCardError(result.error.message);
showPayButton();
} else if (result.paymentIntent) {
if (result.paymentIntent.status === "succeeded") {
// we have charged the card
document.getElementById("payment_intent").value = result.paymentIntent.id;
document.getElementById("payment_method").value = result.paymentIntent.payment_method_types[0];
document.getElementById("payment_amount").value = result.paymentIntent.amount;
document.getElementById("payment_currency").value = result.paymentIntent.currency;
processing.classList.add("d-none");
showCardSuccess();
document.getElementById("charge_form").submit();
}
}
})
console.log(data);
} catch (err) {
console.log(err);
showCardError("Invalid response from payment gateway!");
showPayButton();
}
});
}
(function () {
// create stripe & elements
const elements = stripe.elements();
const style = {
base: {
fontSize: '16px',
lineHeight: '24px',
}
};
// create card entry
card = elements.create('card', {
style:style,
hidePostalCode: true,
});
card.mount("#card-element");
// check for input errors
card.addEventListener('change', function(event) {
var displayError = document.getElementById("card-errors");
if (event.error) {
displayError.classList.remove('d-none');
displayError.textContent = event.error.message;
} else {
displayError.classList.add('d-none');
displayError.textContent = "";
}
});
})();
</script>
{{end}}

View File

@ -11,4 +11,7 @@ Payment Succedded!
<p>Payment Method: {{ index .Data "pm" }}</p> <p>Payment Method: {{ index .Data "pm" }}</p>
<p>Payment Amount: {{ index .Data "pa" }}</p> <p>Payment Amount: {{ index .Data "pa" }}</p>
<p>Currency: {{ index .Data "pc" }}</p> <p>Currency: {{ index .Data "pc" }}</p>
<p>Last Four: {{ index .Data "last_four" }}</p>
<p>Bank Return Code: {{ index .Data "bank_return_code" }}</p>
<p>Expiry Date: {{ index .Data "expiry_month" }}/{{index .Data "expiry_year"}}</p>
{{ end }} {{ end }}

View File

@ -21,6 +21,7 @@ Virtual Terminal
autocomplete="charge_amount-new" autocomplete="charge_amount-new"
required="" required=""
class="form-control"> class="form-control">
<input type="hidden" id="amount" name="amount" value="value">
</div> </div>
<div class="mb-3"> <div class="mb-3">
<label for="cardholder-name" class="form-label">Cardholder Name</label> <label for="cardholder-name" class="form-label">Cardholder Name</label>
@ -51,7 +52,7 @@ Virtual Terminal
<a href="javascript:void(0)" <a href="javascript:void(0)"
id="pay-button" id="pay-button"
class="btn btn-primary" class="btn btn-primary"
onclick="val()">Charge Card</a> onclick="termVal()">Charge Card</a>
<div class="text-center d-none" id="processing-payment"> <div class="text-center d-none" id="processing-payment">
<div class="spinner-border text-primary" role="status"> <div class="spinner-border text-primary" role="status">
<span class="visually-hidden">Loading...</span> <span class="visually-hidden">Loading...</span>
@ -76,14 +77,18 @@ Virtual Terminal
</form> </form>
{{ end }} {{ end }}
{{ define "js" }} {{ define "js" }}
<script src="https://js.stripe.com/v3/"></script>
<script src="/static/js/stripe.js"></script>
<script> <script>
document.getElementById("charge_amount", function(evt) { stripeInit('{{.StripePubKey}}');
if (evt.target.value !== "") { function termVal() {
document.getElementById("amount").value = evt.target.value * 100; const chargeAmount = document.getElementById("charge_amount");
} else { if (chargeAmount.value !== "") {
document.getElementById("amount").value = 0; document.getElementById("amount").value = chargeAmount.value * 100;
} else {
document.getElementById("amount").value = 0;
}
val({{.API}});
} }
});
</script> </script>
{{ template "stripe-js" . }}
{{ end }} {{ end }}

View File

@ -3,6 +3,7 @@ package cards
import ( import (
"github.com/stripe/stripe-go/v79" "github.com/stripe/stripe-go/v79"
"github.com/stripe/stripe-go/v79/paymentintent" "github.com/stripe/stripe-go/v79/paymentintent"
"github.com/stripe/stripe-go/v79/paymentmethod"
) )
type Card struct { type Card struct {
@ -48,6 +49,28 @@ func (c *Card) CreatePaymentIntent(
return pi, "", nil return pi, "", nil
} }
// GetPaymentMethod gets the payment method by payment intend id
func (c *Card) GetPaymentMethod(s string) (*stripe.PaymentMethod, error) {
stripe.Key = c.Secret
pm, err := paymentmethod.Get(s, nil)
if err != nil {
return nil, err
}
return pm, nil
}
// RetrievePaymentMethod gets an existing payment intent by id
func (c *Card) RetrievePaymentIntent(id string) (*stripe.PaymentIntent, error) {
stripe.Key = c.Secret
pi, err := paymentintent.Get(id, nil)
if err != nil {
return nil, err
}
return pi, nil
}
func cardErrorMessage(code stripe.ErrorCode) string { func cardErrorMessage(code stripe.ErrorCode) string {
msg := "" msg := ""

View File

@ -4,8 +4,6 @@ const cardMessages = document.getElementById("card-messages");
const payButton = document.getElementById("pay-button"); const payButton = document.getElementById("pay-button");
const processing = document.getElementById("processing-payment"); const processing = document.getElementById("processing-payment");
stripe = Stripe('{{.StripePubKey}}');
function hidePayButton() { function hidePayButton() {
payButton.classList.add("d-none"); payButton.classList.add("d-none");
processing.classList.remove("d-none"); processing.classList.remove("d-none");
@ -30,7 +28,7 @@ function showCardSuccess() {
cardMessages.innerText = "Trasaction successful"; cardMessages.innerText = "Trasaction successful";
} }
function val(stripe) { function val(api) {
let form = document.getElementById("charge_form"); let form = document.getElementById("charge_form");
if (form.checkValidity() === false) { if (form.checkValidity() === false) {
@ -42,7 +40,8 @@ function val(stripe) {
form.classList.add("was-validated"); form.classList.add("was-validated");
hidePayButton(); hidePayButton();
let amountToCharge = String(parseFloat(document.getElementById("amount").value)); let amountToCharge = document.getElementById("amount").value;
console.log(amountToCharge);
let payload = { let payload = {
amount: amountToCharge, amount: amountToCharge,
currency: 'eur', currency: 'eur',
@ -57,7 +56,7 @@ function val(stripe) {
body: JSON.stringify(payload), body: JSON.stringify(payload),
}; };
fetch("{{.API}}/api/payment-intent", requestOptions) fetch(api + "/api/payment-intent", requestOptions)
.then(response => response.text()) .then(response => response.text())
.then(response => { .then(response => {
let data; let data;
@ -79,7 +78,7 @@ function val(stripe) {
if (result.paymentIntent.status === "succeeded") { if (result.paymentIntent.status === "succeeded") {
// we have charged the card // we have charged the card
document.getElementById("payment_intent").value = result.paymentIntent.id; document.getElementById("payment_intent").value = result.paymentIntent.id;
document.getElementById("payment_method").value = result.paymentIntent.payment_method_types[0]; document.getElementById("payment_method").value = result.paymentIntent.payment_method;
document.getElementById("payment_amount").value = result.paymentIntent.amount; document.getElementById("payment_amount").value = result.paymentIntent.amount;
document.getElementById("payment_currency").value = result.paymentIntent.currency; document.getElementById("payment_currency").value = result.paymentIntent.currency;
processing.classList.add("d-none"); processing.classList.add("d-none");
@ -98,32 +97,36 @@ function val(stripe) {
}); });
} }
(function () { function stripeInit(pubKey) {
// create stripe & elements stripe = Stripe(pubKey);
const elements = stripe.elements();
const style = {
base: {
fontSize: '16px',
lineHeight: '24px',
}
};
// create card entry (function () {
card = elements.create('card', { // create stripe & elements
style:style, const elements = stripe.elements();
hidePostalCode: true, const style = {
}); base: {
card.mount("#card-element"); fontSize: '16px',
lineHeight: '24px',
}
};
// check for input errors // create card entry
card.addEventListener('change', function(event) { card = elements.create('card', {
var displayError = document.getElementById("card-errors"); style:style,
if (event.error) { hidePostalCode: true,
displayError.classList.remove('d-none'); });
displayError.textContent = event.error.message; card.mount("#card-element");
} else {
displayError.classList.add('d-none'); // check for input errors
displayError.textContent = ""; card.addEventListener('change', function(event) {
} var displayError = document.getElementById("card-errors");
}); if (event.error) {
})(); displayError.classList.remove('d-none');
displayError.textContent = event.error.message;
} else {
displayError.classList.add('d-none');
displayError.textContent = "";
}
});
})();
}