handler.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. package billing
  2. import (
  3. "io"
  4. "net/http"
  5. "git.linuxforward.com/byom/byom-onboard/internal/common/models"
  6. "git.linuxforward.com/byom/byom-onboard/internal/platform/database"
  7. "github.com/gin-gonic/gin"
  8. )
  9. type Handler struct {
  10. client BillingClient
  11. db *database.Database
  12. }
  13. func NewHandler(client BillingClient, db *database.Database) *Handler {
  14. return &Handler{
  15. client: client,
  16. db: db,
  17. }
  18. }
  19. func (h *Handler) CreatePayment(c *gin.Context) {
  20. var req models.PaymentRequest
  21. if err := c.ShouldBindJSON(&req); err != nil {
  22. c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid request format"})
  23. return
  24. }
  25. intent, err := h.client.CreatePaymentIntent(req.Amount, req.Currency, req.PaymentMethodID)
  26. if err != nil {
  27. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  28. return
  29. }
  30. c.JSON(http.StatusOK, intent)
  31. }
  32. func (h *Handler) HandleWebhook(c *gin.Context) {
  33. payload, err := io.ReadAll(c.Request.Body)
  34. if err != nil {
  35. c.JSON(http.StatusBadRequest, gin.H{"error": "Unable to read request body"})
  36. return
  37. }
  38. signature := c.GetHeader("Stripe-Signature")
  39. if err := h.client.HandleWebhook(payload, signature); err != nil {
  40. c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  41. return
  42. }
  43. c.JSON(http.StatusOK, gin.H{"received": true})
  44. }
  45. func (h *Handler) InitiateSubscription(c *gin.Context) {
  46. var req struct {
  47. SessionToken string `json:"session_token" binding:"required"`
  48. PlanID string `json:"plan_id" binding:"required"`
  49. }
  50. if err := c.ShouldBindJSON(&req); err != nil {
  51. c.JSON(400, gin.H{"error": "Invalid request"})
  52. return
  53. }
  54. // Get plan details from DefaultPlans
  55. plan, exists := models.GetPlan(req.PlanID)
  56. if !exists {
  57. c.JSON(400, gin.H{"error": "Invalid plan"})
  58. return
  59. }
  60. // Create payment intent with plan price
  61. intent, err := h.client.CreatePaymentIntent(plan.Price, plan.Currency, "")
  62. if err != nil {
  63. c.JSON(500, gin.H{"error": "Failed to create payment"})
  64. return
  65. }
  66. c.JSON(200, intent)
  67. }