diff --git a/frontend/style/app/pay/pay.go b/frontend/style/app/pay/pay.go new file mode 100644 index 00000000..f9623067 --- /dev/null +++ b/frontend/style/app/pay/pay.go @@ -0,0 +1,205 @@ +package main + +import ( + "bytes" + "database/sql" + "encoding/json" + "fmt" + "log" + "net/http" + "os" + "strconv" + + "github.com/google/uuid" + "github.com/gorilla/handlers" + _ "github.com/mattn/go-sqlite3" +) + +// Структура для тела запроса на localhost:5000 +type PaymentRequest struct { + ID string `json:"id"` + Sum float64 `json:"sum"` +} + +// Структура для ответа от localhost:5000 +type PaymentResponse struct { + Message string `json:"message"` + URL string `json:"url"` +} + +var db *sql.DB + +func initDB() { + var err error + dbFile := "users.db" + db, err = sql.Open("sqlite3", dbFile) + if err != nil { + log.Fatal("Ошибка подключения к базе данных:", err) + } + + // Создаем таблицу pay_urls, если она не существует + createTableSQL := ` + CREATE TABLE IF NOT EXISTS pay_urls ( + id TEXT PRIMARY KEY, + url TEXT NOT NULL + );` + _, err = db.Exec(createTableSQL) + if err != nil { + log.Fatal("Ошибка при создании таблицы pay_urls:", err) + } + + fmt.Println("База данных готова к работе.") +} + +func payHandler(w http.ResponseWriter, r *http.Request) { + + cookie, err := r.Cookie("amount") + if err != nil { + http.Error(w, "Не удалось получить amount из cookies", http.StatusBadRequest) + return + } + + // Преобразуем amount из строки в float64 + amount, err := strconv.ParseFloat(cookie.Value, 64) + if err != nil { + http.Error(w, "Некорректное значение amount в cookies", http.StatusBadRequest) + return + } + // Генерируем новый UUID + newUUID := uuid.New().String() + + // Создаем тело запроса для localhost:5000 + paymentRequest := PaymentRequest{ + ID: newUUID, + Sum: amount, + } + + // Преобразуем тело запроса в JSON + requestBody, err := json.Marshal(paymentRequest) + if err != nil { + http.Error(w, "Ошибка при создании запроса", http.StatusInternalServerError) + return + } + + // Отправляем POST-запрос на localhost:5000 + resp, err := http.Post("http://localhost:5000/pay", "application/json", bytes.NewBuffer(requestBody)) + if err != nil { + http.Error(w, "Ошибка при отправке запроса на сервер", http.StatusInternalServerError) + return + } + defer resp.Body.Close() + + // Читаем ответ от сервера + var paymentResponse PaymentResponse + if err := json.NewDecoder(resp.Body).Decode(&paymentResponse); err != nil { + http.Error(w, "Ошибка при чтении ответа от сервера", http.StatusInternalServerError) + return + } + + // Сохраняем данные в базу данных + insertSQL := `INSERT INTO pay_urls (id, url) VALUES (?, ?)` + _, err = db.Exec(insertSQL, newUUID, paymentResponse.URL) + if err != nil { + http.Error(w, "Ошибка при сохранении данных в базу данных", http.StatusInternalServerError) + return + } + + // Формируем ответ клиенту в виде простого текста + response := fmt.Sprintf("UUID: %s\nURL: %s", newUUID, paymentResponse.URL) + + // Отправляем ответ в виде простого текста + w.Header().Set("Content-Type", "text/plain") + w.WriteHeader(http.StatusOK) + w.Write([]byte(response)) +} + +func checkPayHandler(w http.ResponseWriter, r *http.Request) { + // Извлекаем uuid из запроса (например, из query-параметра) + uuid := r.URL.Query().Get("uuid") + if uuid == "" { + http.Error(w, "Не указан uuid", http.StatusBadRequest) + return + } + + // Проверяем существование uuid в базе данных + var exists bool + querySQL := `SELECT EXISTS(SELECT 1 FROM pay_urls WHERE id = ?)` + err := db.QueryRow(querySQL, uuid).Scan(&exists) + if err != nil { + http.Error(w, "Ошибка при проверке uuid в базе данных", http.StatusInternalServerError) + return + } + + if !exists { + http.Error(w, "UUID не найден", http.StatusNotFound) + return + } + + // Создаем тело запроса для localhost:5000/check_pay + checkRequest := struct { + UUID string `json:"uuid"` + }{ + UUID: uuid, + } + + requestBody, err := json.Marshal(checkRequest) + if err != nil { + http.Error(w, "Ошибка при создании запроса", http.StatusInternalServerError) + return + } + + // Отправляем POST-запрос на localhost:5000/check_pay + resp, err := http.Post("http://localhost:5000/check_pay", "application/json", bytes.NewBuffer(requestBody)) + if err != nil { + http.Error(w, "Ошибка при отправке запроса на сервер", http.StatusInternalServerError) + return + } + defer resp.Body.Close() + + // Читаем ответ от сервера + var checkResponse struct { + Mes string `json:"mes"` + } + if err := json.NewDecoder(resp.Body).Decode(&checkResponse); err != nil { + http.Error(w, "Ошибка при чтении ответа от сервера", http.StatusInternalServerError) + return + } + + // Формируем ответ клиенту в зависимости от полученного результата + var response string + if checkResponse.Mes == "OK" { + response = "Успешная оплата" + } else { + response = "Ошибка при оплате" + } + + // Отправляем ответ в виде простого текста + w.Header().Set("Content-Type", "text/plain") + w.WriteHeader(http.StatusOK) + w.Write([]byte(response)) +} + +func main() { + + initDB() + defer db.Close() + // Setup CORS + cors := handlers.CORS( + handlers.AllowedOrigins([]string{"*"}), + handlers.AllowedMethods([]string{"GET", "POST"}), + handlers.AllowedHeaders([]string{"Content-Type"}), + ) + + // Register handlers + http.HandleFunc("/api/pay", payHandler) + http.HandleFunc("api/check_pay", checkPayHandler) + + // Start server with CORS middleware + port := os.Getenv("PORT") + if port == "" { + port = "8080" + } + + fmt.Println("Go-сервер запущен на порту", port) + log.Fatal(http.ListenAndServe(":"+port, cors(http.DefaultServeMux))) +}