Compare commits

...

5 Commits

10 changed files with 199 additions and 195 deletions

View File

@ -1,12 +1,15 @@
package main package main
import ( import (
"myapp/internal/models" "myapp/internal/cards"
"net/http" "net/http"
"strconv"
"github.com/go-chi/chi/v5"
) )
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)
} }
} }
@ -26,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
@ -33,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,
@ -43,12 +71,12 @@ func (app *application) PaymentSucceeded(w http.ResponseWriter, r *http.Request)
// ChargeOnce displays the page to buy one widget // ChargeOnce displays the page to buy one widget
func (app *application) ChargeOnce(w http.ResponseWriter, r *http.Request) { func (app *application) ChargeOnce(w http.ResponseWriter, r *http.Request) {
widget := models.Widget{ id := chi.URLParam(r, "id")
ID: 1, widgetID, _ := strconv.Atoi(id)
Name: "Custom Widget",
Description: "Paris 2024", widget, err := app.DB.GetWidget(widgetID)
InventoryLevel: 10, if err != nil {
Price: 1000, app.errorLog.Println(err)
} }
data := make(map[string]interface{}) data := make(map[string]interface{})
@ -56,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

@ -11,7 +11,7 @@ func (app *application) routes() http.Handler {
mux.Get("/virtual-terminal", app.VirtualTerminal) mux.Get("/virtual-terminal", app.VirtualTerminal)
mux.Post("/payment-succeeded", app.PaymentSucceeded) mux.Post("/payment-succeeded", app.PaymentSucceeded)
mux.Get("/charge-once", app.ChargeOnce) mux.Get("/widget/{id}", app.ChargeOnce)
fileServer := http.FileServer(http.Dir("./static")) fileServer := http.FileServer(http.Dir("./static"))
mux.Handle("/static/*", http.StripPrefix("/static", fileServer)) mux.Handle("/static/*", http.StripPrefix("/static", fileServer))

View File

@ -43,7 +43,7 @@
aria-expanded="false">Products</a> aria-expanded="false">Products</a>
<ul class="dropdown-menu"> <ul class="dropdown-menu">
<li> <li>
<a class="dropdown-item" href="/charge-once">Buy one widget</a> <a class="dropdown-item" href="/widget/1">Buy one widget</a>
</li> </li>
<li> <li>
<a class="dropdown-item" href="#">Subscription</a> <a class="dropdown-item" href="#">Subscription</a>

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 = String(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

@ -16,11 +16,12 @@ Virtual Terminal
<div class="mb-3"> <div class="mb-3">
<label for="amount" class="form-label">Amount</label> <label for="amount" class="form-label">Amount</label>
<input type="text" <input type="text"
id="amount" id="charge_amount"
name="amount" name="charge_amount"
autocomplete="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,5 +77,18 @@ Virtual Terminal
</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}}');
function termVal() {
const chargeAmount = document.getElementById("charge_amount");
if (chargeAmount.value !== "") {
document.getElementById("amount").value = chargeAmount.value * 100;
} else {
document.getElementById("amount").value = 0;
}
val({{.API}});
}
</script>
{{ 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

@ -69,8 +69,8 @@ type Transaction struct {
Amount int `json:"amount"` Amount int `json:"amount"`
Currency string `json:"currency"` Currency string `json:"currency"`
LastFour string `json:"last_four"` LastFour string `json:"last_four"`
BankReturnCode string `json:bank_return_code` BankReturnCode string `json:"bank_return_code"`
TransactionStatusID int `json:transaction_status_id` TransactionStatusID int `json:"transaction_status_id"`
CreatedAt time.Time `json:"-"` CreatedAt time.Time `json:"-"`
UpdatedAt time.Time `json:"-"` UpdatedAt time.Time `json:"-"`
} }
@ -92,12 +92,81 @@ func (m *DBModel) GetWidget(id int) (Widget, error) {
var widget Widget var widget Widget
query := `SELECT id, name FROM widgets WHERE id = ?` query := `SELECT id, name, description, inventory_level, price,
coalesce(image, ''),
created_at, updated_at
FROM widgets WHERE id = ?;`
row := m.DB.QueryRowContext(ctx, query, id) row := m.DB.QueryRowContext(ctx, query, id)
err := row.Scan(&widget.ID, &widget.Name) err := row.Scan(
&widget.ID,
&widget.Name,
&widget.Description,
&widget.InventoryLevel,
&widget.Price,
&widget.Image,
&widget.CreatedAt,
&widget.UpdatedAt,
)
if err != nil { if err != nil {
return widget, err return widget, err
} }
return widget, nil return widget, nil
} }
// InsertTransaction inserts a new txn, and returns its id
func (m *DBModel) InsertTransaction(txn Transaction) (int, error) {
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
defer cancel()
stmt := `INSERT INTO transactions
(amount, currency, last_four, bank_return_code,
transaction_status_id, created_at, updated_at)
VALUES (?, ?, ?, ?, ?, ?, ?)`
result, err := m.DB.ExecContext(ctx, stmt,
txn.Amount,
txn.Currency,
txn.LastFour,
txn.BankReturnCode,
txn.TransactionStatusID,
time.Now(),
time.Now(),
)
if err != nil {
return 0, err
}
id, err := result.LastInsertId()
if err != nil {
return 0, err
}
return int(id), nil
}
// InsertOrder inserts a new order, and returns its id
func (m *DBModel) InsertOrder(order Order) (int, error) {
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
defer cancel()
stmt := `INSERT INTO orders
(widget_id, transaction_id, status_id, quantity,
amount, created_at, updated_at)
VALUES (?, ?, ?, ?, ?, ?, ?)`
result, err := m.DB.ExecContext(ctx, stmt,
order.WidgetID,
order.TransactionID,
order.StatusID,
order.Quantity,
order.Amount,
time.Now(),
)
if err != nil {
return 0, err
}
id, err := result.LastInsertId()
if err != nil {
return 0, err
}
return int(id), nil
}

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,7 +97,10 @@ function val(stripe) {
}); });
} }
(function () { function stripeInit(pubKey) {
stripe = Stripe(pubKey);
(function () {
// create stripe & elements // create stripe & elements
const elements = stripe.elements(); const elements = stripe.elements();
const style = { const style = {
@ -126,4 +128,5 @@ function val(stripe) {
displayError.textContent = ""; displayError.textContent = "";
} }
}); });
})(); })();
}