Compare commits

..

4 Commits

Author SHA1 Message Date
d3e477eebd passing key using form 2024-08-04 18:35:34 +02:00
bfaf8965b3 Generating a receipt page 2024-08-04 18:17:56 +02:00
48695949e3 Updating the front end JS to call paymentIntent handler 2024-08-04 17:34:39 +02:00
1b4d1aef58 Getting the paymentIntent 2024-08-04 16:52:03 +02:00
7 changed files with 177 additions and 12 deletions

View File

@ -2,7 +2,9 @@ package main
import ( import (
"encoding/json" "encoding/json"
"myapp/internal/cards"
"net/http" "net/http"
"strconv"
) )
type stripePayload struct { type stripePayload struct {
@ -12,21 +14,54 @@ type stripePayload struct {
type jsonResponse struct { type jsonResponse struct {
OK bool `json:"ok"` OK bool `json:"ok"`
Message string `json:"message"` Message string `json:"message,omitempty"`
Content string `json:"content"` Content string `json:"content,omitempty"`
ID int `json:"id"` ID int `json:"id,omitempty"`
} }
func (app *application) GetPaymentIntent(w http.ResponseWriter, r *http.Request) { func (app *application) GetPaymentIntent(w http.ResponseWriter, r *http.Request) {
j := jsonResponse{ var payload stripePayload
OK: true,
}
out, err := json.MarshalIndent(j, "", " ") err := json.NewDecoder(r.Body).Decode(&payload)
if err != nil { if err != nil {
app.errorLog.Println(err) app.errorLog.Println(err)
return // TODO: return a valid json
} }
amount, err := strconv.Atoi(payload.Amount)
if err != nil {
app.errorLog.Println(err)
return // TODO: return a valid json
}
card := cards.Card{
Secret: app.config.stripe.secret,
Key: app.config.stripe.key,
Currency: payload.Currency,
}
pi, msg, err := card.Charge(payload.Currency, amount)
if err != nil {
j := jsonResponse{
OK: false,
Message: msg,
Content: "",
}
out, err := json.MarshalIndent(j, "", " ")
if err != nil {
app.errorLog.Println(err)
}
w.Header().Set("Content-Type", "application/json")
w.Write(out)
return
}
out, err := json.MarshalIndent(pi, "", " ")
if err != nil {
app.errorLog.Println(err)
return // TODO: return a valid json
}
w.Header().Set("Content-Type", "application/json") w.Header().Set("Content-Type", "application/json")
w.Write(out) w.Write(out)
} }

View File

@ -18,6 +18,6 @@ func (app *application) routes() http.Handler {
MaxAge: 300, MaxAge: 300,
})) }))
mux.Get("/api/payment-intent", app.GetPaymentIntent) mux.Post("/api/payment-intent", app.GetPaymentIntent)
return mux return mux
} }

View File

@ -5,7 +5,41 @@ 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", nil); err != nil { stringMap := make(map[string]string)
stringMap["publishable_key"] = app.config.stripe.key
if err := app.renderTemplate(w, r, "terminal", &templateData{
StringMap: stringMap,
}); err != nil {
app.errorLog.Println(err)
}
}
func (app *application) PaymentSucceeded(w http.ResponseWriter, r *http.Request) {
err := r.ParseForm()
if err != nil {
app.errorLog.Println(err)
return
}
// read posted data
cardHolder := r.Form.Get("cardholder_name")
email := r.Form.Get("cardholder_email")
paymentIntent := r.Form.Get("payment_intent")
paymentMethod := r.Form.Get("payment_method")
paymentAmount := r.Form.Get("payment_amount")
paymentCurrency := r.Form.Get("payment_currency")
data := make(map[string]interface{})
data["cardholder"] = cardHolder
data["email"] = email
data["pi"] = paymentIntent
data["pm"] = paymentMethod
data["pa"] = paymentAmount
data["pc"] = paymentCurrency
if err := app.renderTemplate(w, r, "succeeded", &templateData{
Data: data,
}); err != nil {
app.errorLog.Println(err) app.errorLog.Println(err)
} }
} }

View File

@ -28,7 +28,8 @@ var functions = template.FuncMap{}
var templateFS embed.FS var templateFS embed.FS
func (app *application) addDefaultData(td *templateData, r *http.Request) *templateData { func (app *application) addDefaultData(td *templateData, r *http.Request) *templateData {
return nil td.API = app.config.api
return td
} }
func (app *application) renderTemplate( func (app *application) renderTemplate(

View File

@ -10,6 +10,7 @@ func (app *application) routes() http.Handler {
mux := chi.NewRouter() mux := chi.NewRouter()
mux.Get("/virtual-terminal", app.VirtualTerminal) mux.Get("/virtual-terminal", app.VirtualTerminal)
mux.Post("/payment-succeeded", app.PaymentSucceeded)
return mux return mux
} }

View File

@ -0,0 +1,14 @@
{{ template "base" . }}
{{ define "title" }}
Payment Succedded!
{{ end }}
{{ define "content" }}
<h2 class="mt-5">Payment Succeeded</h2>
<hr>
<p>Payment Intent: {{ index .Data "pi" }}</p>
<p>Cardholder: {{ index .Data "cardholder" }}</p>
<p>Email: {{ index .Data "email" }}</p>
<p>Payment Method: {{ index .Data "pm" }}</p>
<p>Payment Amount: {{ index .Data "pa" }}</p>
<p>Currency: {{ index .Data "pc" }}</p>
{{ end }}

View File

@ -6,7 +6,7 @@ Virtual Terminal
<h2 class="mt-3 text-center">Virtual Terminal</h2> <h2 class="mt-3 text-center">Virtual Terminal</h2>
<hr> <hr>
<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-succecded" <form action="/payment-succeeded"
method="post" method="post"
name="charge_form" name="charge_form"
id="charge_form" id="charge_form"
@ -57,6 +57,12 @@ Virtual Terminal
<span class="visually-hidden">Loading...</span> <span class="visually-hidden">Loading...</span>
</div> </div>
</div> </div>
<input id="payment_intent" type="hidden" name="payment_intent" value="payment_intent">
<input id="payment_method" type="hidden" name="payment_method" value="payment_method">
<input id="payment_amount" type="hidden" name="payment_amount" value="payment_amount">
<input id="payment_currency" type="hidden" name="payment_currency" value="payment_currency">
</form> </form>
{{ end }} {{ end }}
{{ define "js" }} {{ define "js" }}
@ -69,13 +75,32 @@ 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(''); // TODO: Publish key to be added stripe = Stripe('{{index .StringMap "publishable_key"}}');
function hidePayButton() { function hidePayButton() {
payButton.classList.add("d-none"); payButton.classList.add("d-none");
processing.classList.remove("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() { function val() {
let form = document.getElementById("charge_form"); let form = document.getElementById("charge_form");
@ -87,6 +112,61 @@ function val() {
} }
form.classList.add("was-validated"); form.classList.add("was-validated");
hidePayButton(); hidePayButton();
let amountToCharge = String(parseFloat(document.getElementById("amount").value) * 100);
let payload = {
amount: amountToCharge,
currency: 'eur',
};
const requestOptions = {
method: 'post',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify(payload),
};
fetch("{{index .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 () { (function () {