Compare commits

..

3 Commits

5 changed files with 206 additions and 2 deletions

View File

@ -343,3 +343,65 @@ func (app *application) CheckAuthentication(w http.ResponseWriter, r *http.Reque
payload.Message = fmt.Sprintf("authenticated user %s", user.Email)
app.writeJSON(w, http.StatusOK, payload)
}
func (app *application) VirtualTerminalPaymentSucceeded(w http.ResponseWriter, r *http.Request) {
var txnData struct {
PaymentAmount int `json:"amount"`
PaymentCurrency string `json:"currency"`
FirstName string `json:"first_name"`
LastName string `json:"last_name"`
Email string `json:"email"`
PaymentIntent string `json:"payment_intent"`
PaymentMethod string `json:"payment_method"`
BankReturnCode string `json:"bank_return_code"`
ExpiryMonth int `json:"expiry_month"`
ExpiryYear int `json:"expiry_year"`
LastFour string `json:"last_four"`
}
err := app.readJSON(w, r, &txnData)
if err != nil {
app.badRequest(w, r, err)
return
}
card := cards.Card{
Secret: app.config.stripe.secret,
Key: app.config.stripe.key,
}
pi, err := card.RetrievePaymentIntent(txnData.PaymentIntent)
if err != nil {
app.badRequest(w, r, err)
return
}
pm, err := card.GetPaymentMethod(txnData.PaymentMethod)
if err != nil {
app.badRequest(w, r, err)
return
}
txnData.LastFour = pm.Card.Last4
txnData.ExpiryMonth = int(pm.Card.ExpMonth)
txnData.ExpiryYear = int(pm.Card.ExpYear)
txn := models.Transaction{
Amount: txnData.PaymentAmount,
Currency: txnData.PaymentCurrency,
LastFour: txnData.LastFour,
ExpiryMonth: txnData.ExpiryMonth,
ExpiryYear: txnData.ExpiryYear,
BankReturnCode: pi.LatestCharge.ID,
PaymentIntent: txnData.PaymentIntent,
PaymentMethod: txnData.PaymentMethod,
TransactionStatusID: 2,
}
_, err = app.SaveTransaction(txn)
if err != nil {
app.badRequest(w, r, err)
}
app.writeJSON(w, http.StatusOK, txn)
}

14
cmd/api/middleware.go Normal file
View File

@ -0,0 +1,14 @@
package main
import "net/http"
func (app *application) Auth(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
_, err := app.authenticateToken(r)
if err != nil {
app.invalidCredentials(w)
return
}
next.ServeHTTP(w, r)
})
}

View File

@ -24,6 +24,15 @@ func (app *application) routes() http.Handler {
mux.Post("/api/authenticate", app.CreateAuthToken)
mux.Post("/api/is-authenticated", app.CheckAuthentication)
mux.Route("/api/admin", func(mux chi.Router) {
mux.Use(app.Auth)
mux.Get("/test", func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("got in"))
})
mux.Post("/virtual-terminal-succeeded", app.VirtualTerminalPaymentSucceeded)
})
return mux
}

View File

@ -6,7 +6,7 @@ Virtual Terminal
<h2 class="mt-3 text-center">Virtual Terminal</h2>
<hr>
<div class="alert alert-danger text-center d-none" id="card-messages"></div>
<form action="/virtual-terminal-payment-succeeded"
<form action=""
method="post"
name="charge_form"
id="charge_form"
@ -72,12 +72,26 @@ Virtual Terminal
name="payment_currency"
value="payment_currency">
</form>
<div class="row">
<div class="col-md-5 offset-md-3 d-none" id="receipt">
<h3 class="mt-3 text-center">Receipt</h3>
<hr>
<p>
<strong>Bank Return Code</strong>: <span id="bank-return-code"></span>
</p>
<p>
<a href="/virtual-terminal" class="btn btn-primary">
Charge another card
</a>
</p>
</div>
</div>
{{ end }}
{{ define "js" }}
<script src="https://js.stripe.com/v3/"></script>
<script type="module">
import {stripeInit, checkAuth} from "/static/js/common.js";
import {val} from "/static/js/stripe.js"
import {val} from "/static/js/terminal.js"
checkAuth({{.API}});
stripeInit('{{.StripePubKey}}');

105
static/js/terminal.js Normal file
View File

@ -0,0 +1,105 @@
import {
hidePayButton,
showPayButton,
showError,
showSuccess,
stripe,
card,
processing,
} from './common.js';
export function val(api) {
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 = document.getElementById("amount").value;
console.log(amountToCharge);
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
showError("card-messages", result.error.message);
showPayButton();
} else if (result.paymentIntent) {
if (result.paymentIntent.status === "succeeded") {
saveTransaction(api, result);
}
}
})
console.log(data);
} catch (err) {
console.log(err);
showCardError("Invalid response from payment gateway!");
showPayButton();
}
});
}
function saveTransaction(api, result) {
let payload = {
amount: parseInt(document.getElementById("amount").value, 10),
currency: result.paymentIntent.currency,
first_name: "",
last_name: "",
email: document.getElementById("cardholder-email").value,
payment_intent: result.paymentIntent.id,
payment_method: result.paymentIntent.payment_method,
};
let token = localStorage.getItem("token");
const requestOptions = {
method: "post",
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + token,
},
body: JSON.stringify(payload),
};
fetch(api + "/api/admin/virtual-terminal-succeeded", requestOptions)
.then(response => response.json())
.then(function (data) {
console.log(data);
processing.classList.add("d-none");
showSuccess("card-messages", "Trasaction successful!");
document.getElementById("bank-return-code").innerHTML = data.bank_return_code;
document.getElementById("receipt").classList.remove("d-none");
})
}