RezinaLMS-BackEnd/internal/domain/subscription_checkout_link.go
Yared Yemane 2791894e14 Add web checkout link API for iOS subscription paywall.
Send checkout URLs by email or SMS via POST /subscriptions/request-checkout-link, with LEARNER_WEB_CHECKOUT_BASE_URL config, RBAC permission, rate limiting, and client integration docs.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-24 13:09:09 +03:00

89 lines
2.5 KiB
Go

package domain
import (
"errors"
"fmt"
"net/mail"
"net/url"
"strings"
)
var ErrNoContactForCheckoutLink = errors.New("no email or phone number on file to send checkout link")
type CheckoutLinkDeliveryChannel string
const (
CheckoutLinkDeliveryEmail CheckoutLinkDeliveryChannel = "email"
CheckoutLinkDeliverySMS CheckoutLinkDeliveryChannel = "sms"
)
// ResolveCheckoutLinkDeliveryChannel picks email vs SMS from the learner's registration contact.
// Verified phone/email is preferred; otherwise falls back to the single contact on file.
func ResolveCheckoutLinkDeliveryChannel(user User) (CheckoutLinkDeliveryChannel, string, error) {
phone := strings.TrimSpace(user.PhoneNumber)
email := strings.TrimSpace(user.Email)
if user.PhoneVerified && phone != "" {
return CheckoutLinkDeliverySMS, phone, nil
}
if user.EmailVerified && email != "" {
return CheckoutLinkDeliveryEmail, email, nil
}
if phone != "" && email == "" {
return CheckoutLinkDeliverySMS, phone, nil
}
if email != "" && phone == "" {
return CheckoutLinkDeliveryEmail, email, nil
}
if phone != "" {
return CheckoutLinkDeliverySMS, phone, nil
}
if email != "" {
if _, err := mail.ParseAddress(email); err != nil {
return "", "", fmt.Errorf("invalid email on file: %w", err)
}
return CheckoutLinkDeliveryEmail, email, nil
}
return "", "", ErrNoContactForCheckoutLink
}
// BuildWebCheckoutURL builds a deep link into the standalone web checkout app.
func BuildWebCheckoutURL(baseURL string, planID *int64, category *string) string {
base := strings.TrimRight(strings.TrimSpace(baseURL), "/")
if base == "" {
return ""
}
if planID != nil && *planID > 0 {
return fmt.Sprintf("%s/subscribe/checkout?plan_id=%d", base, *planID)
}
if category != nil {
cat := strings.TrimSpace(*category)
if cat != "" {
return fmt.Sprintf("%s/subscribe?category=%s", base, url.QueryEscape(strings.ToUpper(cat)))
}
}
return base + "/subscribe"
}
// MaskCheckoutLinkDestination returns a safe hint for API responses (e.g. ***5678, j***@example.com).
func MaskCheckoutLinkDestination(channel CheckoutLinkDeliveryChannel, destination string) string {
dest := strings.TrimSpace(destination)
if dest == "" {
return ""
}
switch channel {
case CheckoutLinkDeliverySMS:
if len(dest) <= 4 {
return "***" + dest
}
return "***" + dest[len(dest)-4:]
default:
parts := strings.Split(dest, "@")
if len(parts) != 2 || parts[0] == "" {
return "***"
}
prefix := parts[0][:1]
return prefix + "***@" + parts[1]
}
}