forked from QuantumNous/new-api
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwaffo_pancake.go
More file actions
483 lines (453 loc) · 17.1 KB
/
Copy pathwaffo_pancake.go
File metadata and controls
483 lines (453 loc) · 17.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
package service
import (
"context"
"fmt"
"strings"
"github.com/QuantumNous/new-api/model"
"github.com/QuantumNous/new-api/setting"
pancake "github.com/waffo-com/waffo-pancake-sdk-go"
)
// WaffoPancakePriceSnapshot is the per-session price override sent with checkout.
type WaffoPancakePriceSnapshot struct {
Amount string
TaxCategory string
}
// WaffoPancakeCreateSessionParams is the input to CreateWaffoPancakeCheckoutSession.
// BuyerIdentity must be stable per user (see WaffoPancakeBuyerIdentityFromUserID).
// OrderMerchantExternalID = our trade_no; Pancake echoes it back in webhooks.
type WaffoPancakeCreateSessionParams struct {
ProductID string
BuyerIdentity string
PriceSnapshot *WaffoPancakePriceSnapshot
BuyerEmail string
ExpiresInSeconds *int
OrderMerchantExternalID string
}
// WaffoPancakeCheckoutSession is the response of CreateWaffoPancakeCheckoutSession.
// CheckoutURL already carries the `#token=...` fragment; Token / TokenExpiresAt
// are exposed separately for self-service flows driven from new-api's own UI.
type WaffoPancakeCheckoutSession struct {
SessionID string
CheckoutURL string
ExpiresAt string
OrderID string
Token string
TokenExpiresAt string
}
// WaffoPancakeWebhookEvent mirrors the SDK's WebhookEvent shape using plain
// strings so controllers don't have to import the SDK package.
type WaffoPancakeWebhookEvent struct {
ID string
Timestamp string
EventType string
EventID string
StoreID string
Mode string
Data WaffoPancakeWebhookData
}
type WaffoPancakeWebhookData struct {
// OrderID = Pancake ORD_* (logs); OrderMerchantExternalID = our trade_no (lookup).
OrderID string
OrderMerchantExternalID string
BuyerEmail string
Currency string
Amount string
TaxAmount string
ProductName string
MerchantProvidedBuyerIdentity string
}
// NormalizedEventType returns the event type or empty string for a nil event.
func (e *WaffoPancakeWebhookEvent) NormalizedEventType() string {
if e == nil {
return ""
}
return e.EventType
}
// newWaffoPancakeClient builds an SDK client from persisted settings. The
// runtime checkout / webhook paths use this; configuration endpoints use
// newWaffoPancakeClientFromCreds so the operator can verify typed-but-not-
// yet-saved credentials.
func newWaffoPancakeClient() (*pancake.Client, error) {
return pancake.New(pancake.Config{
MerchantID: setting.WaffoPancakeMerchantID,
PrivateKey: setting.WaffoPancakePrivateKey,
})
}
func newWaffoPancakeClientFromCreds(merchantID, privateKey string) (*pancake.Client, error) {
if strings.TrimSpace(merchantID) == "" || strings.TrimSpace(privateKey) == "" {
return nil, fmt.Errorf("merchant id and private key are required")
}
return pancake.New(pancake.Config{
MerchantID: merchantID,
PrivateKey: privateKey,
})
}
// CreateWaffoPancakeCheckoutSession creates an Authenticated-mode checkout
// session: the order is bound to BuyerIdentity (stable per user) so it stays
// attributable even if the buyer edits the email on Waffo's checkout form.
func CreateWaffoPancakeCheckoutSession(ctx context.Context, params *WaffoPancakeCreateSessionParams) (*WaffoPancakeCheckoutSession, error) {
if params == nil {
return nil, fmt.Errorf("missing checkout params")
}
if strings.TrimSpace(params.BuyerIdentity) == "" {
return nil, fmt.Errorf("missing buyer identity")
}
if strings.TrimSpace(params.OrderMerchantExternalID) == "" {
return nil, fmt.Errorf("missing order merchant external id")
}
client, err := newWaffoPancakeClient()
if err != nil {
return nil, fmt.Errorf("build Waffo Pancake client: %w", err)
}
sdkParams := pancake.AuthenticatedCheckoutParams{
CreateCheckoutSessionParams: pancake.CreateCheckoutSessionParams{
ProductID: params.ProductID,
Currency: "USD",
BuyerEmail: optionalString(params.BuyerEmail),
ExpiresInSeconds: params.ExpiresInSeconds,
OrderMerchantExternalID: optionalString(params.OrderMerchantExternalID),
},
BuyerIdentity: params.BuyerIdentity,
}
if params.PriceSnapshot != nil {
sdkParams.PriceSnapshot = &pancake.PriceInfo{
Amount: params.PriceSnapshot.Amount,
TaxCategory: pancake.TaxCategory(params.PriceSnapshot.TaxCategory),
}
}
session, err := client.Checkout.Authenticated.Create(ctx, sdkParams)
if err != nil {
return nil, err
}
if session == nil || strings.TrimSpace(session.CheckoutURL) == "" || strings.TrimSpace(session.SessionID) == "" {
return nil, fmt.Errorf("Waffo Pancake returned empty checkout session")
}
return &WaffoPancakeCheckoutSession{
SessionID: session.SessionID,
CheckoutURL: session.CheckoutURL,
ExpiresAt: session.ExpiresAt,
Token: session.Token,
TokenExpiresAt: session.TokenExpiresAt,
}, nil
}
func optionalString(s string) *string {
if strings.TrimSpace(s) == "" {
return nil
}
v := s
return &v
}
// WaffoPancakeBuyerIdentityFromUserID renders the canonical buyer identity
// for checkout. Webhook handlers compare against the value rendered here to
// reject identity mismatches, so both call sites must use this function.
func WaffoPancakeBuyerIdentityFromUserID(userID int) string {
return fmt.Sprintf("new-api-user-%d", userID)
}
// VerifyConfiguredWaffoPancakeWebhook verifies the signature header. The SDK
// picks the matching test / prod public key from the payload's `mode` field.
func VerifyConfiguredWaffoPancakeWebhook(payload string, signatureHeader string) (*WaffoPancakeWebhookEvent, error) {
evt, err := pancake.VerifyWebhookTyped[pancake.WebhookEventData](payload, signatureHeader, nil)
if err != nil {
return nil, err
}
identity := ""
if evt.Data.MerchantProvidedBuyerIdentity != nil {
identity = *evt.Data.MerchantProvidedBuyerIdentity
}
externalID := ""
if evt.Data.OrderMerchantExternalID != nil {
externalID = *evt.Data.OrderMerchantExternalID
}
return &WaffoPancakeWebhookEvent{
ID: evt.ID,
Timestamp: evt.Timestamp,
EventType: evt.EventType,
EventID: evt.EventID,
StoreID: evt.StoreID,
Mode: string(evt.Mode),
Data: WaffoPancakeWebhookData{
OrderID: evt.Data.OrderID,
OrderMerchantExternalID: externalID,
BuyerEmail: evt.Data.BuyerEmail,
Currency: evt.Data.Currency,
Amount: evt.Data.Amount,
TaxAmount: evt.Data.TaxAmount,
ProductName: evt.Data.ProductName,
MerchantProvidedBuyerIdentity: identity,
},
}, nil
}
// ResolveWaffoPancakeTradeNo maps a verified webhook event to a local TopUp
// trade_no via OrderMerchantExternalID, and rejects buyer-identity mismatches.
func ResolveWaffoPancakeTradeNo(event *WaffoPancakeWebhookEvent) (string, error) {
if event == nil {
return "", fmt.Errorf("missing webhook event")
}
tradeNo := strings.TrimSpace(event.Data.OrderMerchantExternalID)
if tradeNo == "" {
return "", fmt.Errorf("missing webhook orderMerchantExternalId")
}
topUp := model.GetTopUpByTradeNo(tradeNo)
if topUp == nil || topUp.PaymentProvider != model.PaymentProviderWaffoPancake {
return "", fmt.Errorf("waffo pancake order not found for tradeNo=%s", tradeNo)
}
expectedIdentity := WaffoPancakeBuyerIdentityFromUserID(topUp.UserId)
actualIdentity := strings.TrimSpace(event.Data.MerchantProvidedBuyerIdentity)
if actualIdentity != expectedIdentity {
return "", fmt.Errorf(
"waffo pancake buyer identity mismatch for tradeNo=%s: expected=%q actual=%q",
tradeNo,
expectedIdentity,
actualIdentity,
)
}
return tradeNo, nil
}
// ResolveWaffoPancakeSubscriptionTradeNo is the SubscriptionOrder counterpart
// of ResolveWaffoPancakeTradeNo.
func ResolveWaffoPancakeSubscriptionTradeNo(event *WaffoPancakeWebhookEvent) (string, error) {
if event == nil {
return "", fmt.Errorf("missing webhook event")
}
tradeNo := strings.TrimSpace(event.Data.OrderMerchantExternalID)
if tradeNo == "" {
return "", fmt.Errorf("missing webhook orderMerchantExternalId")
}
order := model.GetSubscriptionOrderByTradeNo(tradeNo)
if order == nil || order.PaymentProvider != model.PaymentProviderWaffoPancake {
return "", fmt.Errorf("waffo pancake subscription order not found for tradeNo=%s", tradeNo)
}
expectedIdentity := WaffoPancakeBuyerIdentityFromUserID(order.UserId)
actualIdentity := strings.TrimSpace(event.Data.MerchantProvidedBuyerIdentity)
if actualIdentity != expectedIdentity {
return "", fmt.Errorf(
"waffo pancake buyer identity mismatch for subscription tradeNo=%s: expected=%q actual=%q",
tradeNo,
expectedIdentity,
actualIdentity,
)
}
return tradeNo, nil
}
// Deterministic default names for "+ Create": stable bodies mean stable
// X-Idempotency-Key, which lets Pancake dedupe retries server-side.
const (
defaultWaffoPancakeStoreName = "new-api-store"
defaultWaffoPancakeProductName = "new-api-charge-product"
)
// CreateWaffoPancakePrimaryStore creates a Pancake Store using in-flight
// (not-yet-persisted) credentials and returns the new store ID.
func CreateWaffoPancakePrimaryStore(ctx context.Context, merchantID, privateKey string) (string, error) {
client, err := newWaffoPancakeClientFromCreds(merchantID, privateKey)
if err != nil {
return "", err
}
storeRes, err := client.Stores.Create(ctx, pancake.CreateStoreParams{
Name: defaultWaffoPancakeStoreName,
})
if err != nil {
return "", fmt.Errorf("create Waffo Pancake store: %w", err)
}
return storeRes.Store.ID, nil
}
// CreateWaffoPancakeProductForPlan mints (and publishes) a Pancake
// OnetimeProduct priced at `amount` USD, used as a subscription plan's
// SubscriptionPlan.WaffoPancakeProductId.
//
// OnetimeProduct (not SubscriptionProduct) because new-api has no renewal-
// event handling; Pancake auto-renewing without new-api extending user
// access would be a UX divergence. Revisit if renewal handling is added.
func CreateWaffoPancakeProductForPlan(ctx context.Context, merchantID, privateKey, storeID, name, amount, returnURL string) (string, error) {
storeID = strings.TrimSpace(storeID)
if storeID == "" {
return "", fmt.Errorf("store id is required to create a product")
}
name = strings.TrimSpace(name)
if name == "" {
return "", fmt.Errorf("plan name is required")
}
amount = strings.TrimSpace(amount)
if amount == "" {
return "", fmt.Errorf("plan price is required")
}
client, err := newWaffoPancakeClientFromCreds(merchantID, privateKey)
if err != nil {
return "", err
}
prodRes, err := client.OnetimeProducts.Create(ctx, pancake.CreateOnetimeProductParams{
StoreID: storeID,
Name: name,
Prices: pancake.Prices{
"USD": {
Amount: amount,
TaxCategory: pancake.TaxCategory("saas"),
},
},
SuccessURL: optionalString(strings.TrimSpace(returnURL)),
})
if err != nil {
return "", fmt.Errorf("create Waffo Pancake plan product: %w", err)
}
productID := prodRes.Product.ID
if _, err := client.OnetimeProducts.Publish(ctx, pancake.PublishOnetimeProductParams{ID: productID}); err != nil {
return "", fmt.Errorf("publish Waffo Pancake plan product: %w", err)
}
return productID, nil
}
// CreateWaffoPancakePrimaryProduct mints (and publishes) the wallet-top-up
// OnetimeProduct under storeID. Per-checkout price overrides via PriceSnapshot
// are what make the "1.00" seed price irrelevant at runtime.
func CreateWaffoPancakePrimaryProduct(ctx context.Context, merchantID, privateKey, storeID, returnURL string) (string, error) {
storeID = strings.TrimSpace(storeID)
if storeID == "" {
return "", fmt.Errorf("store id is required to create a product")
}
client, err := newWaffoPancakeClientFromCreds(merchantID, privateKey)
if err != nil {
return "", err
}
prodRes, err := client.OnetimeProducts.Create(ctx, pancake.CreateOnetimeProductParams{
StoreID: storeID,
Name: defaultWaffoPancakeProductName,
Prices: pancake.Prices{
"USD": {
Amount: "1.00", // overridden at checkout via PriceSnapshot
TaxCategory: pancake.TaxCategory("saas"),
},
},
SuccessURL: optionalString(strings.TrimSpace(returnURL)),
})
if err != nil {
return "", fmt.Errorf("create Waffo Pancake product: %w", err)
}
productID := prodRes.Product.ID
if _, err := client.OnetimeProducts.Publish(ctx, pancake.PublishOnetimeProductParams{ID: productID}); err != nil {
return "", fmt.Errorf("publish Waffo Pancake product: %w", err)
}
return productID, nil
}
// WaffoPancakePairResult is the response of CreateWaffoPancakePrimaryPair.
// When OrphanStore is true the store was created but the product wasn't,
// so the caller can surface a partial-failure message with StoreID.
type WaffoPancakePairResult struct {
StoreID string
StoreName string
ProductID string
ProductName string
OrphanStore bool
}
// CreateWaffoPancakePrimaryPair mints a Store + OnetimeProduct in one
// round-trip — the canonical "+ Create" entry point. Nothing is persisted
// to settings; the operator's final Save commits the chosen IDs.
func CreateWaffoPancakePrimaryPair(ctx context.Context, merchantID, privateKey, returnURL string) (*WaffoPancakePairResult, error) {
storeID, err := CreateWaffoPancakePrimaryStore(ctx, merchantID, privateKey)
if err != nil {
return nil, err
}
productID, err := CreateWaffoPancakePrimaryProduct(ctx, merchantID, privateKey, storeID, returnURL)
if err != nil {
return &WaffoPancakePairResult{
StoreID: storeID,
StoreName: defaultWaffoPancakeStoreName,
OrphanStore: true,
}, fmt.Errorf("store created at %s but product creation failed: %w", storeID, err)
}
return &WaffoPancakePairResult{
StoreID: storeID,
StoreName: defaultWaffoPancakeStoreName,
ProductID: productID,
ProductName: defaultWaffoPancakeProductName,
}, nil
}
// SaveWaffoPancakeConfig persists the operator-controlled fields atomically
// at the end of the configuration flow via model.UpdateOptionsBulk (single
// DB transaction). A blank privateKey is treated as "keep current"
// (Stripe-style API-secret UX) and is omitted from the bulk payload.
func SaveWaffoPancakeConfig(ctx context.Context, merchantID, privateKey, returnURL, storeID, productID string) error {
merchantID = strings.TrimSpace(merchantID)
storeID = strings.TrimSpace(storeID)
productID = strings.TrimSpace(productID)
if merchantID == "" || storeID == "" || productID == "" {
return fmt.Errorf("merchant id, store id, and product id are required to save")
}
values := map[string]string{
"WaffoPancakeMerchantID": merchantID,
"WaffoPancakeReturnURL": strings.TrimSpace(returnURL),
"WaffoPancakeStoreID": storeID,
"WaffoPancakeProductID": productID,
}
if pk := strings.TrimSpace(privateKey); pk != "" {
values["WaffoPancakePrivateKey"] = pk
}
if err := model.UpdateOptionsBulk(values); err != nil {
return fmt.Errorf("persist Waffo Pancake config: %w", err)
}
return nil
}
type WaffoPancakeCatalogProduct struct {
ID string `json:"id"`
Name string `json:"name"`
Status string `json:"status"`
}
// WaffoPancakeCatalogStore nests its OnetimeProducts so the UI can render a
// dependent store→product select without a second round-trip.
type WaffoPancakeCatalogStore struct {
ID string `json:"id"`
Name string `json:"name"`
Status string `json:"status"`
ProdEnabled bool `json:"prodEnabled"`
OnetimeProducts []WaffoPancakeCatalogProduct `json:"onetimeProducts"`
}
type WaffoPancakeCatalog struct {
Stores []WaffoPancakeCatalogStore `json:"stores"`
}
// ListWaffoPancakeCatalog queries Pancake's GraphQL `stores` for the
// merchant's stores + onetime products. A successful call also proves
// the supplied credentials authenticate (doubles as a credential probe).
func ListWaffoPancakeCatalog(ctx context.Context, merchantID, privateKey string) (*WaffoPancakeCatalog, error) {
client, err := newWaffoPancakeClientFromCreds(merchantID, privateKey)
if err != nil {
return nil, err
}
type queryShape struct {
Stores []WaffoPancakeCatalogStore `json:"stores"`
}
// `limit: 100` because the API returns a single store when limit is
// omitted, even for multi-store merchants. Bump to paginated fetches
// (via `offset`) if real catalogs ever cross the cap.
resp, err := pancake.GraphQLQuery[queryShape](ctx, client, pancake.GraphQLParams{
Query: `query {
stores(limit: 100) {
id
name
status
prodEnabled
onetimeProducts {
id
name
status
}
}
}`,
})
if err != nil {
return nil, fmt.Errorf("query Waffo Pancake catalog: %w", err)
}
if len(resp.Errors) > 0 {
return nil, fmt.Errorf("waffo pancake catalog query returned %d errors: %s",
len(resp.Errors), resp.Errors[0].Message)
}
// Drop non-active products. Operators should only see items they can
// actually bind without later hitting "product unavailable" at checkout.
stores := resp.Data.Stores
for i := range stores {
active := stores[i].OnetimeProducts[:0]
for _, p := range stores[i].OnetimeProducts {
if strings.EqualFold(strings.TrimSpace(p.Status), "active") {
active = append(active, p)
}
}
stores[i].OnetimeProducts = active
}
return &WaffoPancakeCatalog{Stores: stores}, nil
}