Files
yhy-mager/backend/internal/payments/payments.go
xiewenjun dc2efcde08
Some checks failed
Check / delivery-static (push) Has been cancelled
Check / api (push) Has been cancelled
Check / web (push) Has been cancelled
feat: add online payment management and checkout
Co-Authored-By: Craft Agent <agents-noreply@craft.do>
2026-10-15 09:26:40 +08:00

131 lines
3.7 KiB
Go

package payments
import (
"context"
"errors"
"fmt"
"net/http"
"net/url"
"os"
"strings"
)
type Notification struct {
EventID, MerchantOrderNo, TradeNo, Currency string
AmountCents int64
Paid bool
}
type Provider interface {
Create(context.Context, string, int64, string) (string, error)
Query(context.Context, string) (Notification, error)
Verify(*http.Request) (Notification, error)
Close(context.Context, string) error
Refund(context.Context, string, string, int64) error
}
// Config holds channel settings using the documented ALIPAY_* and WECHAT_* keys.
// NewProvider reads this map synchronously and never modifies it or the process environment.
type Config map[string]string
const (
alipayEndpoint = "https://openapi.alipay.com/gateway.do"
wechatEndpoint = "https://api.mch.weixin.qq.com"
)
// RequiredSettings returns an independent slice. Unknown channels return nil.
func RequiredSettings(channel string) []string {
switch channel {
case "alipay":
return []string{"ALIPAY_APP_ID", "ALIPAY_SELLER_ID", "ALIPAY_PRIVATE_KEY", "ALIPAY_PUBLIC_KEY", "ALIPAY_NOTIFY_URL"}
case "wechat":
return []string{"WECHAT_MCH_ID", "WECHAT_APP_ID", "WECHAT_SERIAL_NO", "WECHAT_PRIVATE_KEY", "WECHAT_API_V3_KEY", "WECHAT_NOTIFY_URL"}
default:
return nil
}
}
// ConfigFromEnv returns a snapshot of the channel's nonempty settings, including
// its legacy endpoint setting. Unknown channels return an empty map.
func ConfigFromEnv(channel string) Config {
c := Config{}
keys := RequiredSettings(channel)
if len(keys) == 0 {
return c
}
if channel == "wechat" {
keys = append(keys, "WECHAT_PUBLIC_KEY_ID", "WECHAT_PUBLIC_KEY", "WECHAT_PLATFORM_SERIAL", "WECHAT_PLATFORM_PUBLIC_KEY")
}
keys = append(keys, strings.ToUpper(channel)+"_ENDPOINT")
for _, key := range keys {
if v := strings.TrimSpace(os.Getenv(key)); v != "" {
c[key] = v
}
}
return c
}
// NewProvider validates settings without making network requests. Endpoints are
// fixed to the official production gateways; a conflicting override is rejected.
func NewProvider(channel string, config Config) (Provider, error) {
keys := RequiredSettings(channel)
if len(keys) == 0 {
return nil, fmt.Errorf("unsupported payment channel %q", channel)
}
for _, key := range keys {
if _, err := config.required(key); err != nil {
return nil, fmt.Errorf("%s: %w", channel, err)
}
}
endpoint := alipayEndpoint
if channel == "wechat" {
endpoint = wechatEndpoint
}
if override := config.value(strings.ToUpper(channel) + "_ENDPOINT"); override != "" && override != endpoint {
return nil, fmt.Errorf("%s: endpoint must be the official production gateway", channel)
}
var p Provider
var err error
switch channel {
case "alipay":
p, err = newAlipay(config)
case "wechat":
p, err = newWechat(config)
}
if err != nil {
return nil, fmt.Errorf("%s: %w", channel, err)
}
return p, nil
}
func LoadFromEnv() (map[string]Provider, error) {
out := map[string]Provider{}
for _, channel := range []string{"alipay", "wechat"} {
c := ConfigFromEnv(channel)
if len(c) == 0 {
continue
}
p, err := NewProvider(channel, c)
if err != nil {
return nil, err
}
out[channel] = p
}
return out, nil
}
func (c Config) value(key string) string { return strings.TrimSpace(c[key]) }
func (c Config) required(key string) (string, error) {
v := c.value(key)
if v == "" {
return "", errors.New("missing " + key)
}
return v, nil
}
func validateNotifyURL(key, value string) error {
u, err := url.Parse(value)
if err != nil || u.Scheme != "https" || u.Hostname() == "" || u.User != nil || u.Fragment != "" {
return fmt.Errorf("%s must be an absolute HTTPS URL without userinfo or fragment", key)
}
return nil
}