Sending invoice from the BE

This commit is contained in:
2024-08-27 13:52:36 +02:00
parent 9b31ff0bbb
commit 082c75283d
3 changed files with 111 additions and 2 deletions

View File

@ -1,6 +1,7 @@
package main
import (
"bytes"
"encoding/json"
"errors"
"fmt"
@ -103,6 +104,17 @@ func (app *application) GetWidgetByID(w http.ResponseWriter, r *http.Request) {
w.Write(out)
}
type Invoice struct {
ID int `json:"id"`
Quantity int `json:"quantity"`
Amount int `json:"amount"`
Product string `json:"product"`
FirstName string `json:"first_name"`
LastName string `json:"last_name"`
Email string `json:"email"`
CreatedAt time.Time `json:"created_at"`
}
func (app *application) CreateCustomerAndSubscribeToPlan(w http.ResponseWriter, r *http.Request) {
var data stripePayload
@ -183,11 +195,27 @@ func (app *application) CreateCustomerAndSubscribeToPlan(w http.ResponseWriter,
Amount: amount,
}
_, err = app.SaveOrder(order)
orderID, err := app.SaveOrder(order)
if err != nil {
app.errorLog.Println(err)
return
}
inv := Invoice{
ID: orderID,
Quantity: order.Quantity,
Amount: order.Amount,
Product: "Bronze Plan",
FirstName: data.FirstName,
LastName: data.LastName,
Email: data.Email,
CreatedAt: time.Now(),
}
err = app.callInvoiceMicro(inv)
if err != nil {
app.errorLog.Println(err)
// Don't stop the program
}
}
resp := JSONResponse{
@ -205,6 +233,30 @@ func (app *application) CreateCustomerAndSubscribeToPlan(w http.ResponseWriter,
w.Write(out)
}
func (app *application) callInvoiceMicro(inv Invoice) error {
// TODO: Do not hard code this.
url := "http://localhost:5000/invoice/create-and-send"
out, err := json.MarshalIndent(inv, "", "\t")
if err != err {
return err
}
req, err := http.NewRequest("POST", url, bytes.NewBuffer(out))
if err != nil {
return nil
}
req.Header.Set("Content-Type", "application/json")
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
app.infoLog.Println(resp.Body)
return nil
}
func (app *application) SaveCustomer(firstName, lastName, email string) (int, error) {
customer := models.Customer{
FirstName: firstName,