Moving js to a reusable file and change the dir for the img

This commit is contained in:
vinchent 2024-08-06 13:56:39 +02:00
parent f398af39eb
commit 525e4fe50d
6 changed files with 145 additions and 138 deletions

View File

@ -9,7 +9,7 @@ func (app *application) VirtualTerminal(w http.ResponseWriter, r *http.Request)
stringMap["publishable_key"] = app.config.stripe.key stringMap["publishable_key"] = app.config.stripe.key
if err := app.renderTemplate(w, r, "terminal", &templateData{ if err := app.renderTemplate(w, r, "terminal", &templateData{
StringMap: stringMap, StringMap: stringMap,
}); err != nil { }, "stripe-js"); err != nil {
app.errorLog.Println(err) app.errorLog.Println(err)
} }
} }
@ -46,7 +46,7 @@ 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) {
if err := app.renderTemplate(w, r, "buy-once", nil); err != nil { if err := app.renderTemplate(w, r, "buy-once", nil, "stripe-js"); err != nil {
app.errorLog.Println(err) app.errorLog.Println(err)
} }
} }

View File

@ -80,7 +80,7 @@ func (app *application) parseTemplate(
// build partials // build partials
if len(partials) > 0 { if len(partials) > 0 {
for i, x := range partials { for i, x := range partials {
partials[i] = fmt.Sprintf("tempaltes/%s.partial.gohtml", x) partials[i] = fmt.Sprintf("templates/%s.partial.gohtml", x)
} }
t, err = template.New(fmt.Sprintf("%s.page.gohtml", page)). t, err = template.New(fmt.Sprintf("%s.page.gohtml", page)).
Funcs(functions). Funcs(functions).

View File

@ -1,11 +1,11 @@
{{ template "base" }} {{ template "base" .}}
{{ define "title" }} {{ define "title" }}
Buy one widget Buy one widget
{{ end }} {{ end }}
{{ define "content" }} {{ define "content" }}
<h2 class="mt-3 text-center">Buy One Widget</h2> <h2 class="mt-3 text-center">Buy One Widget</h2>
<hr> <hr>
<img src="/static/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">
@ -79,3 +79,6 @@ Buy one widget
value="payment_currency"> value="payment_currency">
</form> </form>
{{ end }} {{ end }}
{{ define "js" }}
{{ 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('{{index .StringMap "publishable_key"}}');
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) * 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 () {
// 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

@ -76,137 +76,5 @@ Virtual Terminal
</form> </form>
{{ end }} {{ end }}
{{ define "js" }} {{ define "js" }}
<script src="https://js.stripe.com/v3/"></script> {{ template "stripe-js" . }}
<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('{{index .StringMap "publishable_key"}}');
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) * 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 () {
// 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 }} {{ end }}

View File

Before

Width:  |  Height:  |  Size: 67 KiB

After

Width:  |  Height:  |  Size: 67 KiB