work on payment code

This commit is contained in:
Joerg Lehmann 2019-07-27 13:32:58 +02:00
parent e053b64625
commit 495871b3fe
4 changed files with 125 additions and 89 deletions

10
main.go
View File

@ -56,7 +56,7 @@ func serveTemplate(w http.ResponseWriter, r *http.Request) {
var last_metrics []OneMetric var last_metrics []OneMetric
var checkout_session_id string var checkout_session_id string
if (r.URL.Path == "/scales.html") || (r.URL.Path == "/abos.html") { if (r.URL.Path == "/scales.html") {
// wir holen noch die letzten Metriken // wir holen noch die letzten Metriken
for _, v := range scales { for _, v := range scales {
last_metric := getLastMetrics(v) last_metric := getLastMetrics(v)
@ -64,13 +64,6 @@ func serveTemplate(w http.ResponseWriter, r *http.Request) {
} }
} }
if (r.URL.Path == "/abos.html") {
// wir generieren die Stripe Session ID
checkout_session_id = GetStripeSessionID()
logit("Stripe Session ID: " + checkout_session_id)
}
data := struct { data := struct {
UserName string UserName string
DateTimeString string DateTimeString string
@ -107,6 +100,7 @@ func main() {
http.HandleFunc("/metrics", metricsHandler) http.HandleFunc("/metrics", metricsHandler)
http.HandleFunc("/lastmetrics", lastmetricsHandler) http.HandleFunc("/lastmetrics", lastmetricsHandler)
http.HandleFunc("/save_scale_settings", save_scale_settingsHandler) http.HandleFunc("/save_scale_settings", save_scale_settingsHandler)
http.HandleFunc("/getstripesession", getstripesessionHandler)
logit("Starting Web Application...") logit("Starting Web Application...")
http.ListenAndServe("127.0.0.1:4000", nil) http.ListenAndServe("127.0.0.1:4000", nil)

View File

@ -1,50 +0,0 @@
{{define "body_content"}}
<p class="title is-4">Abos</p>
<p>Hier k&ouml;nnen blablabla...</p>
<div class="columns is-marginless">
<div class="column is-full"></div>
</div>
{{ if ne .UserName "" }}
{{range .LastMetrics}}
<div class="columns is-vcentered is-marginless">
<div class="column is-full has-background-primary">
<span id="alias_{{.Deveui}}" class="is-size-7-mobile is-size-4-tablet">{{.Alias}} (bis 01.01.2099)</span>
<div class="select is-pulled-right is-vcentered is-size-7-mobile">
<select class="has-background-light">
<option>keine</option>
<option>1 Jahr</option>
<option>2 Jahre</option>
<option>3 Jahre</option>
</select>
</div>
</div>
</div>
<div class="columns">
<div class="column is-full"></div>
</div>
{{end}}
<div>
<button id="pay-button" class="button is-success">Pay</button>
</div>
<script src="https://js.stripe.com/v3/"></script>
<script>
var stripe = Stripe('pk_test_YkSGqH3Tk9WKK9HrlY63GhAg');
$("#pay-button").click(function() {
stripe.redirectToCheckout({
sessionId: '{{.CheckoutSessionID}}'
}).then(function (result) {
// If `redirectToCheckout` fails due to a browser or network
// error, display the localized error message to your customer
// using `result.error.message`.
});
});
</script>
{{ else }}
<h4>Bitte zuerst <a href="login.html">einloggen</a></h4>
{{end}}
{{end}}

View File

@ -179,25 +179,11 @@ $(".show-modal").click(function() {
$("#modal").addClass("is-active"); $("#modal").addClass("is-active");
}); });
$(".abo_pay").click(function() {
console.log("pay...");
el = $(this).parent().find(".abo_add_years");
counter = Number(el.html());
if (counter > 0) {
$("#cart").addClass("is-active");
}
});
$("#cart-close").click(function() { $("#cart-close").click(function() {
console.log("blabla"); console.log("blabla");
$("#cart").removeClass("is-active"); $("#cart").removeClass("is-active");
}); });
$("#cart-pay").click(function() {
console.log("hoopla");
$("#cart").removeClass("is-active");
});
$(".abo_plus").click(function() { $(".abo_plus").click(function() {
console.log("abo_plus"); console.log("abo_plus");
el = $(this).parent().find(".abo_add_years"); el = $(this).parent().find(".abo_add_years");
@ -232,6 +218,15 @@ $(".abo_minus").click(function() {
} }
}); });
$(".abo_pay").click(function() {
console.log("pay...");
el = $(this).parent().find(".abo_add_years");
counter = Number(el.html());
if (counter > 0) {
$("#cart").addClass("is-active");
}
});
$("#modal-close").click(function() { $("#modal-close").click(function() {
console.log("blabla"); console.log("blabla");
$("#modal").removeClass("is-active"); $("#modal").removeClass("is-active");
@ -303,6 +298,52 @@ $("#modal-save").click(function() {
$("#modal").removeClass("is-active"); $("#modal").removeClass("is-active");
}); });
});
</script>
<script src="https://js.stripe.com/v3/"></script>
<script>
var stripe = Stripe('pk_test_YkSGqH3Tk9WKK9HrlY63GhAg');
$("#cart-pay").click(function() {
console.log("hoopla");
$("#cart").removeClass("is-active");
$.ajax({
url: "getstripesession",
type: "get", //send it through get method
dataType: "json",
data: {
charge_name: "Abo",
charge_description: "Desription",
charge_amount_rappen: 500,
charge_quantity: 1
},
success: function(response) {
console.log('pay success');
console.log(response.stripesessionid);
console.log('rc: '+response.rc);
if (response.rc == 0) {
console.log('redirectToCheckout');
stripe.redirectToCheckout({
sessionId: response.stripesessionid
}).then(function (result) {
// If `redirectToCheckout` fails due to a browser or network
// error, display the localized error message to your customer
// using `result.error.message`.
});
}
},
error: function(xhr) {
console.log('getstripesession error');
//Do Something to handle error
}
});
}); });
</script> </script>

View File

@ -1,11 +1,58 @@
package main package main
import ( import (
"fmt"
"log"
"strconv"
"net/http"
"github.com/stripe/stripe-go" "github.com/stripe/stripe-go"
"github.com/stripe/stripe-go/checkout/session" "github.com/stripe/stripe-go/checkout/session"
) )
func GetStripeSessionID() string { func getstripesessionHandler(response http.ResponseWriter, request *http.Request) {
name := getUserName(request)
if name != "" {
charge_name, ok := request.URL.Query()["charge_name"]
if !ok || len(charge_name[0]) < 1 {
log.Println("Url Param 'charge_name' is missing")
fmt.Fprintf(response, "{ \"rc\": 1, \"msg\": \"charge_name must be specified in URL\" }")
return
}
charge_description, ok := request.URL.Query()["charge_description"]
if !ok || len(charge_description[0]) < 1 {
log.Println("Url Param 'charge_description' is missing")
fmt.Fprintf(response, "{ \"rc\": 2, \"msg\": \"charge_description must be specified in URL\" }")
return
}
charge_quantity, ok := request.URL.Query()["charge_quantity"]
if !ok || len(charge_quantity[0]) < 1 {
log.Println("Url Param 'charge_quantity' is missing")
fmt.Fprintf(response, "{ \"rc\": 3, \"msg\": \"charge_quantity must be specified in URL\" }")
return
}
charge_quantity_int64, err := strconv.Atoi(charge_quantity[0])
if err == nil {
fmt.Println(charge_quantity_int64)
} else {
fmt.Println(charge_quantity[0], "is not an integer.")
}
charge_amount_rappen, ok := request.URL.Query()["charge_amount_rappen"]
if !ok || len(charge_amount_rappen[0]) < 1 {
log.Println("Url Param 'charge_amount_rappen' is missing")
fmt.Fprintf(response, "{ \"rc\": 4, \"msg\": \"charge_amount_rappen must be specified in URL\" }")
return
}
charge_amount_rappen_int64, err := strconv.Atoi(charge_amount_rappen[0])
if err == nil {
fmt.Println(charge_amount_rappen_int64,)
} else {
fmt.Println(charge_amount_rappen[0], "is not an integer.")
}
stripe.Key = "sk_test_GJbXPD0IAFNvvGpNEpaeDfhl" stripe.Key = "sk_test_GJbXPD0IAFNvvGpNEpaeDfhl"
params := &stripe.CheckoutSessionParams{ params := &stripe.CheckoutSessionParams{
@ -14,11 +61,11 @@ func GetStripeSessionID() string {
}), }),
LineItems: []*stripe.CheckoutSessionLineItemParams{ LineItems: []*stripe.CheckoutSessionLineItemParams{
&stripe.CheckoutSessionLineItemParams{ &stripe.CheckoutSessionLineItemParams{
Name: stripe.String("Abo"), Name: stripe.String(charge_name[0]),
Description: stripe.String("Abo mini-beieli.ch"), Description: stripe.String(charge_description[0]),
Amount: stripe.Int64(500), Amount: stripe.Int64(int64(charge_amount_rappen_int64)),
Currency: stripe.String(string(stripe.CurrencyCHF)), Currency: stripe.String(string(stripe.CurrencyCHF)),
Quantity: stripe.Int64(1), Quantity: stripe.Int64(int64(charge_quantity_int64)),
}, },
}, },
SuccessURL: stripe.String("https://mini-beieli.ch/payment_received.html"), SuccessURL: stripe.String("https://mini-beieli.ch/payment_received.html"),
@ -27,8 +74,12 @@ func GetStripeSessionID() string {
session, err := session.New(params) session, err := session.New(params)
if err != nil { if err != nil {
return "" fmt.Fprintf(response,"{ \"rc\": 5, \"stripesessionid\": \"%s\" }\n","ERROR")
} else { } else {
return session.ID fmt.Fprintf(response,"{ \"rc\": 0, \"stripesessionid\": \"%s\" }\n",session.ID )
}
} else {
fmt.Fprintf(response, "{ \"rc\": 6, \"msg\": \"Only available for logged in users\" }")
} }
} }