Compare commits

..

No commits in common. "13725426201f2448b20ff037c10f5479758bbaca" and "d32667acd168e7e28e0dddb73f1d4db5e5ac1b96" have entirely different histories.

10 changed files with 195 additions and 199 deletions

View File

@ -1,15 +1,12 @@
package main
import (
"myapp/internal/cards"
"myapp/internal/models"
"net/http"
"strconv"
"github.com/go-chi/chi/v5"
)
func (app *application) VirtualTerminal(w http.ResponseWriter, r *http.Request) {
if err := app.renderTemplate(w, r, "terminal", &templateData{}); err != nil {
if err := app.renderTemplate(w, r, "terminal", &templateData{}, "stripe-js"); err != nil {
app.errorLog.Println(err)
}
}
@ -29,27 +26,6 @@ func (app *application) PaymentSucceeded(w http.ResponseWriter, r *http.Request)
paymentAmount := r.Form.Get("payment_amount")
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["cardholder"] = cardHolder
data["email"] = email
@ -57,10 +33,6 @@ func (app *application) PaymentSucceeded(w http.ResponseWriter, r *http.Request)
data["pm"] = paymentMethod
data["pa"] = paymentAmount
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{
Data: data,
@ -71,12 +43,12 @@ func (app *application) PaymentSucceeded(w http.ResponseWriter, r *http.Request)
// ChargeOnce displays the page to buy one widget
func (app *application) ChargeOnce(w http.ResponseWriter, r *http.Request) {
id := chi.URLParam(r, "id")
widgetID, _ := strconv.Atoi(id)
widget, err := app.DB.GetWidget(widgetID)
if err != nil {
app.errorLog.Println(err)
widget := models.Widget{
ID: 1,
Name: "Custom Widget",
Description: "Paris 2024",
InventoryLevel: 10,
Price: 1000,
}
data := make(map[string]interface{})
@ -84,7 +56,7 @@ func (app *application) ChargeOnce(w http.ResponseWriter, r *http.Request) {
if err := app.renderTemplate(w, r, "buy-once", &templateData{
Data: data,
}); err != nil {
}, "stripe-js"); err != nil {
app.errorLog.Println(err)
}
}

View File

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

View File

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

View File

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

View File

@ -0,0 +1,136 @@
{{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,7 +11,4 @@ Payment Succedded!
<p>Payment Method: {{ index .Data "pm" }}</p>
<p>Payment Amount: {{ index .Data "pa" }}</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 }}

View File

@ -16,12 +16,11 @@ Virtual Terminal
<div class="mb-3">
<label for="amount" class="form-label">Amount</label>
<input type="text"
id="charge_amount"
name="charge_amount"
autocomplete="charge_amount-new"
id="amount"
name="amount"
autocomplete="amount-new"
required=""
class="form-control">
<input type="hidden" id="amount" name="amount" value="value">
</div>
<div class="mb-3">
<label for="cardholder-name" class="form-label">Cardholder Name</label>
@ -52,7 +51,7 @@ Virtual Terminal
<a href="javascript:void(0)"
id="pay-button"
class="btn btn-primary"
onclick="termVal()">Charge Card</a>
onclick="val()">Charge Card</a>
<div class="text-center d-none" id="processing-payment">
<div class="spinner-border text-primary" role="status">
<span class="visually-hidden">Loading...</span>
@ -77,18 +76,5 @@ Virtual Terminal
</form>
{{ end }}
{{ define "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>
{{ template "stripe-js" . }}
{{ end }}

View File

@ -3,7 +3,6 @@ package cards
import (
"github.com/stripe/stripe-go/v79"
"github.com/stripe/stripe-go/v79/paymentintent"
"github.com/stripe/stripe-go/v79/paymentmethod"
)
type Card struct {
@ -49,28 +48,6 @@ func (c *Card) CreatePaymentIntent(
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 {
msg := ""

View File

@ -69,8 +69,8 @@ type Transaction struct {
Amount int `json:"amount"`
Currency string `json:"currency"`
LastFour string `json:"last_four"`
BankReturnCode string `json:"bank_return_code"`
TransactionStatusID int `json:"transaction_status_id"`
BankReturnCode string `json:bank_return_code`
TransactionStatusID int `json:transaction_status_id`
CreatedAt time.Time `json:"-"`
UpdatedAt time.Time `json:"-"`
}
@ -92,81 +92,12 @@ func (m *DBModel) GetWidget(id int) (Widget, error) {
var widget Widget
query := `SELECT id, name, description, inventory_level, price,
coalesce(image, ''),
created_at, updated_at
FROM widgets WHERE id = ?;`
query := `SELECT id, name FROM widgets WHERE id = ?`
row := m.DB.QueryRowContext(ctx, query, id)
err := row.Scan(
&widget.ID,
&widget.Name,
&widget.Description,
&widget.InventoryLevel,
&widget.Price,
&widget.Image,
&widget.CreatedAt,
&widget.UpdatedAt,
)
err := row.Scan(&widget.ID, &widget.Name)
if err != nil {
return widget, err
}
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,6 +4,8 @@ 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");
@ -28,7 +30,7 @@ function showCardSuccess() {
cardMessages.innerText = "Trasaction successful";
}
function val(api) {
function val(stripe) {
let form = document.getElementById("charge_form");
if (form.checkValidity() === false) {
@ -40,8 +42,7 @@ function val(api) {
form.classList.add("was-validated");
hidePayButton();
let amountToCharge = document.getElementById("amount").value;
console.log(amountToCharge);
let amountToCharge = String(parseFloat(document.getElementById("amount").value));
let payload = {
amount: amountToCharge,
currency: 'eur',
@ -56,7 +57,7 @@ function val(api) {
body: JSON.stringify(payload),
};
fetch(api + "/api/payment-intent", requestOptions)
fetch("{{.API}}/api/payment-intent", requestOptions)
.then(response => response.text())
.then(response => {
let data;
@ -78,7 +79,7 @@ function val(api) {
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;
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");
@ -97,36 +98,32 @@ function val(api) {
});
}
function stripeInit(pubKey) {
stripe = Stripe(pubKey);
(function () {
// create stripe & elements
const elements = stripe.elements();
const style = {
base: {
fontSize: '16px',
lineHeight: '24px',
}
};
(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");
// 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 = "";
}
});
})();
}
// 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 = "";
}
});
})();