72 lines
1.6 KiB
Go
72 lines
1.6 KiB
Go
package payment
|
|
|
|
import (
|
|
"bytes"
|
|
"donat-widget/internal/model/api"
|
|
"encoding/json"
|
|
"errors"
|
|
"github.com/google/uuid"
|
|
"io"
|
|
"log/slog"
|
|
"net/http"
|
|
)
|
|
|
|
func New(host, port string) *ClientPayment {
|
|
return &ClientPayment{
|
|
client: &http.Client{},
|
|
baseURL: "http://" + host + ":" + port + "/api/payment",
|
|
}
|
|
}
|
|
|
|
type ClientPayment struct {
|
|
client *http.Client
|
|
baseURL string
|
|
}
|
|
|
|
func (c *ClientPayment) CreatePayment(
|
|
streamerID int,
|
|
amount int,
|
|
orderID uuid.UUID,
|
|
) (api.CreatePaymentResponse, error) {
|
|
requestBody := map[string]any{
|
|
"sellerID": streamerID,
|
|
"amount": amount,
|
|
"orderID": orderID,
|
|
}
|
|
response, err := c.post("/buyer/pay", requestBody)
|
|
if err != nil {
|
|
slog.Error("c.post /buyer/pay", err)
|
|
return api.CreatePaymentResponse{}, err
|
|
}
|
|
|
|
var createPaymentResponse api.CreatePaymentResponse
|
|
if err = json.Unmarshal(response, &createPaymentResponse); err != nil {
|
|
slog.Error("json.Unmarshal", err)
|
|
return api.CreatePaymentResponse{}, err
|
|
}
|
|
|
|
return createPaymentResponse, nil
|
|
}
|
|
|
|
func (c *ClientPayment) post(path string, body map[string]any) ([]byte, error) {
|
|
bytesBody, _ := json.Marshal(body)
|
|
|
|
resp, err := c.client.Post(c.baseURL+path, "application/json", bytes.NewReader(bytesBody))
|
|
if err != nil {
|
|
slog.Error("c.client.Post: " + err.Error())
|
|
return nil, err
|
|
}
|
|
defer resp.Body.Close()
|
|
if resp.StatusCode != http.StatusOK {
|
|
return nil, errors.New("tinkoff: post failed: " + resp.Status)
|
|
}
|
|
|
|
response, err := io.ReadAll(resp.Body)
|
|
if err != nil {
|
|
slog.Error("io.ReadAll: " + err.Error())
|
|
return nil, err
|
|
}
|
|
|
|
return response, nil
|
|
}
|