package chapa import ( "Yimaru-Backend/internal/domain" "Yimaru-Backend/internal/services/checkoutsubscription" "context" "encoding/json" "errors" "fmt" "net/http" "strings" "time" "github.com/google/uuid" ) var ( ErrInvalidChapaDirectChargeMethod = errors.New("invalid chapa direct charge method") ErrChapaDirectChargeFailed = errors.New("chapa direct charge failed") ) type subscriptionPaymentPrep struct { Plan *domain.SubscriptionPlan Email string TxRef string ExpiresAt time.Time } func (s *Service) prepareSubscriptionPayment(ctx context.Context, userID, planID int64, email string) (*subscriptionPaymentPrep, error) { plan, err := s.subscriptionStore.GetSubscriptionPlanByID(ctx, planID) if err != nil { return nil, fmt.Errorf("failed to get subscription plan: %w", err) } if !plan.IsActive { return nil, errors.New("subscription plan is not active") } hasActive, err := s.subscriptionStore.HasActiveSubscriptionByCategory(ctx, userID, plan.Category) if err != nil { return nil, fmt.Errorf("failed to check active subscription: %w", err) } if hasActive { return nil, errors.New("user already has an active subscription for this category") } user, err := s.userStore.GetUserByID(ctx, userID) if err != nil { return nil, fmt.Errorf("failed to get user: %w", err) } resolvedEmail := strings.TrimSpace(email) if resolvedEmail == "" { resolvedEmail = user.Email } if resolvedEmail == "" { return nil, errors.New("email is required for payment") } return &subscriptionPaymentPrep{ Plan: plan, Email: resolvedEmail, TxRef: uuid.NewString(), ExpiresAt: time.Now().Add(15 * time.Minute), }, nil } // InitiateDirectChargeSubscription starts a Chapa Direct Charge for a subscription plan. func (s *Service) InitiateDirectChargeSubscription(ctx context.Context, userID int64, req domain.InitiateChapaDirectChargeRequest) (*domain.InitiateChapaDirectChargeResponse, error) { if err := s.configured(); err != nil { return nil, err } chargeType, err := domain.ParseChapaDirectChargeType(req.PaymentMethod) if err != nil { return nil, fmt.Errorf("%w: %s", ErrInvalidChapaDirectChargeMethod, err.Error()) } prep, err := s.prepareSubscriptionPayment(ctx, userID, req.PlanID, req.Email) if err != nil { return nil, err } phone := formatChapaPhone(req.Phone) if phone == "" { user, userErr := s.userStore.GetUserByID(ctx, userID) if userErr == nil && user.PhoneNumber != "" { phone = formatChapaPhone(user.PhoneNumber) } } if phone == "" { return nil, errors.New("phone is required for direct charge") } method := domain.ChapaDirectChargePaymentMethod(chargeType) pendingSub, err := checkoutsubscription.CreatePending( ctx, s.subscriptionStore, userID, prep.Plan, prep.TxRef, method, ) if err != nil { return nil, err } pendingSubID := pendingSub.ID payment, err := s.paymentStore.CreatePayment(ctx, domain.CreatePaymentInput{ UserID: userID, PlanID: &req.PlanID, SubscriptionID: &pendingSubID, Amount: prep.Plan.Price, Currency: prep.Plan.Currency, PaymentMethod: &method, Nonce: prep.TxRef, ExpiresAt: &prep.ExpiresAt, }) if err != nil { checkoutsubscription.AbandonPending(ctx, s.subscriptionStore, &pendingSubID) return nil, fmt.Errorf("failed to create payment record: %w", err) } chargeData, err := s.initiateDirectCharge(ctx, chargeType, directChargeFields{ Amount: formatAmount(prep.Plan.Price), Currency: normalizeCurrency(prep.Plan.Currency), Mobile: phone, TxRef: prep.TxRef, Email: prep.Email, }) if err != nil { _ = s.paymentStore.UpdatePaymentStatus(ctx, payment.ID, string(domain.PaymentStatusFailed)) checkoutsubscription.AbandonPending(ctx, s.subscriptionStore, &pendingSubID) return nil, err } chapaRef := chargeData.reference() requestID := chargeData.requestID() authType := strings.ToLower(strings.TrimSpace(chargeData.authType())) if authType == "" { authType = strings.ToLower(strings.TrimSpace(chargeData.metaVerificationType())) } requiresAuthorize := authType == "otp" || strings.EqualFold(chargeData.metaVerificationType(), "otp") if chapaRef != "" { if err := s.paymentStore.UpdatePaymentSessionID(ctx, payment.ID, chapaRef, ""); err != nil { return nil, fmt.Errorf("failed to update payment session: %w", err) } } if !requiresAuthorize { _ = s.paymentStore.UpdatePaymentStatus(ctx, payment.ID, string(domain.PaymentStatusProcessing)) } message := chargeData.userMessage() if message == "" { if requiresAuthorize { message = "OTP sent to your phone. Authorize the payment to continue." } else { message = "USSD push sent to your phone. Approve the payment to continue." } } return &domain.InitiateChapaDirectChargeResponse{ PaymentID: payment.ID, SessionID: prep.TxRef, ChapaReference: chapaRef, RequestID: requestID, AuthType: authType, RequiresAuthorize: requiresAuthorize, Message: message, PortalHTML: chargeData.portalHTML(), Amount: prep.Plan.Price, Currency: prep.Plan.Currency, ExpiresAt: prep.ExpiresAt.Format(time.RFC3339), }, nil } // AuthorizeDirectChargeSubscription completes OTP-based Chapa direct charge authorization. func (s *Service) AuthorizeDirectChargeSubscription(ctx context.Context, userID int64, req domain.AuthorizeChapaDirectChargeRequest) (*domain.AuthorizeChapaDirectChargeResponse, error) { if err := s.configured(); err != nil { return nil, err } if strings.TrimSpace(s.cfg.CHAPA_ENCRYPTION_KEY) == "" { return nil, ErrChapaEncryptionNotConfigured } payment, err := s.lookupPayment(ctx, req.SessionID) if err != nil { return nil, ErrPaymentNotFound } if payment.UserID != userID { return nil, errors.New("unauthorized") } if payment.PaymentMethod == nil || !domain.IsChapaPaymentMethod(*payment.PaymentMethod) { return nil, ErrInvalidChapaDirectChargeMethod } if payment.Status == string(domain.PaymentStatusSuccess) { return &domain.AuthorizeChapaDirectChargeResponse{ Success: true, Message: "Payment already completed", PaymentID: payment.ID, }, nil } chargeType, err := chapaDirectChargeTypeFromPaymentMethod(*payment.PaymentMethod) if err != nil { return nil, err } reference := derefString(payment.SessionID) if reference == "" { return nil, errors.New("missing chapa reference on payment") } encrypted, err := encryptChapaDirectChargePayload(s.cfg.CHAPA_ENCRYPTION_KEY, req.RequestID, req.OTP) if err != nil { return nil, err } body, statusCode, err := s.postMultipart(ctx, "/validate?type="+string(chargeType), map[string]string{ "reference": reference, "client": encrypted, }) if err != nil { return nil, err } if statusCode != http.StatusOK { return nil, fmt.Errorf("%w: %s", ErrChapaDirectChargeFailed, string(body)) } var result domain.ChapaAuthorizeDirectChargeResponse if err := json.Unmarshal(body, &result); err != nil { return nil, fmt.Errorf("invalid authorize response from Chapa: %w", err) } if !strings.EqualFold(result.Status, "success") { return &domain.AuthorizeChapaDirectChargeResponse{ Success: false, Message: result.Message, }, nil } if err := s.paymentStore.UpdatePaymentStatus(ctx, payment.ID, string(domain.PaymentStatusProcessing)); err != nil { return nil, err } verified, err := s.VerifyPayment(ctx, payment.Nonce) if err != nil { return &domain.AuthorizeChapaDirectChargeResponse{ Success: true, Message: "Authorization accepted. Payment verification is still in progress.", PaymentID: payment.ID, }, nil } msg := "Payment authorized successfully" if verified.Status != string(domain.PaymentStatusSuccess) { msg = "Authorization accepted. Complete approval on your phone if prompted, then verify again." } return &domain.AuthorizeChapaDirectChargeResponse{ Success: true, Message: msg, PaymentID: payment.ID, }, nil } func (s *Service) GetDirectChargeMethods() []domain.ChapaDirectChargeMethod { return []domain.ChapaDirectChargeMethod{ {Name: string(domain.ChapaDirectChargeTelebirr), DisplayName: "Telebirr", AuthType: "ussd"}, {Name: string(domain.ChapaDirectChargeMPesa), DisplayName: "M-Pesa", AuthType: "ussd"}, {Name: string(domain.ChapaDirectChargeCBEBirr), DisplayName: "CBE Birr", AuthType: "otp"}, {Name: string(domain.ChapaDirectChargeEBirr), DisplayName: "E-Birr", AuthType: "otp"}, {Name: string(domain.ChapaDirectChargeAwashBirr), DisplayName: "Awash Birr", AuthType: "ussd"}, {Name: string(domain.ChapaDirectChargeYaya), DisplayName: "Yaya Wallet", AuthType: "ussd"}, {Name: string(domain.ChapaDirectChargeBOAUSSD), DisplayName: "BOA USSD", AuthType: "ussd"}, {Name: string(domain.ChapaDirectChargeCoopayEBirr), DisplayName: "Coopay E-Birr", AuthType: "ussd"}, {Name: string(domain.ChapaDirectChargeAmole), DisplayName: "Amole", AuthType: "otp"}, {Name: string(domain.ChapaDirectChargeEnatBank), DisplayName: "Enat Bank", AuthType: "portal"}, } } type directChargeFields struct { Amount string Currency string Mobile string TxRef string Email string } type parsedDirectChargeData struct { flat domain.ChapaDirectChargeData nested domain.ChapaDirectChargeData raw domain.ChapaDirectChargeData } func (p parsedDirectChargeData) reference() string { if ref := strings.TrimSpace(p.nested.Reference); ref != "" { return ref } if p.nested.Meta != nil && strings.TrimSpace(p.nested.Meta.RefID) != "" { return strings.TrimSpace(p.nested.Meta.RefID) } if ref := strings.TrimSpace(p.flat.Reference); ref != "" { return ref } return "" } func (p parsedDirectChargeData) requestID() string { if p.nested.Meta != nil { if v := strings.TrimSpace(p.nested.Meta.Data); v != "" { return v } } return "" } func (p parsedDirectChargeData) authType() string { if v := strings.TrimSpace(p.nested.AuthType); v != "" { return v } return strings.TrimSpace(p.flat.AuthType) } func (p parsedDirectChargeData) metaVerificationType() string { if p.nested.Meta != nil { return strings.TrimSpace(p.nested.Meta.VerificationType) } return "" } func (p parsedDirectChargeData) userMessage() string { if p.nested.Meta != nil && strings.TrimSpace(p.nested.Meta.Message) != "" { return strings.TrimSpace(p.nested.Meta.Message) } return "" } func (p parsedDirectChargeData) portalHTML() string { if html := strings.TrimSpace(p.nested.PortalHTML); html != "" && strings.Contains(strings.ToLower(html), "<") { return html } return "" } func (s *Service) initiateDirectCharge(ctx context.Context, chargeType domain.ChapaDirectChargeType, fields directChargeFields) (parsedDirectChargeData, error) { endpoint := "/charges?type=" + string(chargeType) body, statusCode, err := s.postMultipart(ctx, endpoint, map[string]string{ "amount": fields.Amount, "currency": fields.Currency, "mobile": fields.Mobile, "tx_ref": fields.TxRef, "email": fields.Email, }) if err != nil { return parsedDirectChargeData{}, err } if statusCode != http.StatusOK { return parsedDirectChargeData{}, fmt.Errorf("%w (status %d): %s", ErrChapaDirectChargeFailed, statusCode, string(body)) } var envelope domain.ChapaDirectChargeResponse if err := json.Unmarshal(body, &envelope); err != nil { return parsedDirectChargeData{}, fmt.Errorf("invalid direct charge response from Chapa: %w", err) } if !strings.EqualFold(envelope.Status, "success") { return parsedDirectChargeData{}, fmt.Errorf("%w: %s", ErrChapaDirectChargeFailed, envelope.Message) } parsed, err := parseDirectChargeData(envelope.Data) if err != nil { return parsedDirectChargeData{}, err } return parsed, nil } func parseDirectChargeData(raw json.RawMessage) (parsedDirectChargeData, error) { if len(raw) == 0 { return parsedDirectChargeData{}, fmt.Errorf("%w: empty data", ErrChapaDirectChargeFailed) } var flat domain.ChapaDirectChargeData if err := json.Unmarshal(raw, &flat); err != nil { return parsedDirectChargeData{}, err } var nested domain.ChapaDirectChargeData _ = json.Unmarshal(raw, &nested) return parsedDirectChargeData{ flat: flat, nested: nested, raw: flat, }, nil } func chapaDirectChargeTypeFromPaymentMethod(method string) (domain.ChapaDirectChargeType, error) { const prefix = "CHAPA_DIRECT:" upper := strings.ToUpper(strings.TrimSpace(method)) if !strings.HasPrefix(upper, prefix) { return "", ErrInvalidChapaDirectChargeMethod } return domain.ParseChapaDirectChargeType(strings.ToLower(strings.TrimPrefix(upper, prefix))) } func derefString(p *string) string { if p == nil { return "" } return *p }