@mathrunet/masamune 2.0.0 → 2.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (57) hide show
  1. package/CHANGELOG.md +9 -0
  2. package/dist/functions/agora_cloud_recording.js +44 -47
  3. package/dist/functions/agora_cloud_recording.js.map +1 -1
  4. package/dist/functions/agora_token.js +34 -37
  5. package/dist/functions/agora_token.js.map +1 -1
  6. package/dist/functions/android_auth_code.js +19 -22
  7. package/dist/functions/android_auth_code.js.map +1 -1
  8. package/dist/functions/android_token.js +39 -42
  9. package/dist/functions/android_token.js.map +1 -1
  10. package/dist/functions/consumable_verify_android.js +38 -41
  11. package/dist/functions/consumable_verify_android.js.map +1 -1
  12. package/dist/functions/consumable_verify_ios.js +33 -36
  13. package/dist/functions/consumable_verify_ios.js.map +1 -1
  14. package/dist/functions/geocoding.js +23 -26
  15. package/dist/functions/geocoding.js.map +1 -1
  16. package/dist/functions/gmail.js +30 -33
  17. package/dist/functions/gmail.js.map +1 -1
  18. package/dist/functions/nonconsumable_verify_android.js +37 -40
  19. package/dist/functions/nonconsumable_verify_android.js.map +1 -1
  20. package/dist/functions/nonconsumable_verify_ios.js +32 -35
  21. package/dist/functions/nonconsumable_verify_ios.js.map +1 -1
  22. package/dist/functions/openai_chat_gpt.js +34 -37
  23. package/dist/functions/openai_chat_gpt.js.map +1 -1
  24. package/dist/functions/purchase_webhook_android.js +2 -2
  25. package/dist/functions/purchase_webhook_android.js.map +1 -1
  26. package/dist/functions/purchase_webhook_ios.js +82 -85
  27. package/dist/functions/purchase_webhook_ios.js.map +1 -1
  28. package/dist/functions/scheduler.js +4 -4
  29. package/dist/functions/scheduler.js.map +1 -1
  30. package/dist/functions/send_grid.js +30 -33
  31. package/dist/functions/send_grid.js.map +1 -1
  32. package/dist/functions/send_notification.js +32 -35
  33. package/dist/functions/send_notification.js.map +1 -1
  34. package/dist/functions/stripe.js +853 -856
  35. package/dist/functions/stripe.js.map +1 -1
  36. package/dist/functions/stripe_webhook.js +355 -358
  37. package/dist/functions/stripe_webhook.js.map +1 -1
  38. package/dist/functions/stripe_webhook_connect.js +65 -68
  39. package/dist/functions/stripe_webhook_connect.js.map +1 -1
  40. package/dist/functions/stripe_webhook_secure.js +63 -66
  41. package/dist/functions/stripe_webhook_secure.js.map +1 -1
  42. package/dist/functions/subscription_verify_android.js +54 -57
  43. package/dist/functions/subscription_verify_android.js.map +1 -1
  44. package/dist/functions/subscription_verify_ios.js +54 -57
  45. package/dist/functions/subscription_verify_ios.js.map +1 -1
  46. package/dist/lib/call_process_function_base.d.ts +3 -1
  47. package/dist/lib/call_process_function_base.js +1 -2
  48. package/dist/lib/call_process_function_base.js.map +1 -1
  49. package/dist/lib/functions_base.d.ts +1 -1
  50. package/dist/lib/functions_base.js +1 -0
  51. package/dist/lib/functions_base.js.map +1 -1
  52. package/dist/lib/request_process_function_base.d.ts +2 -0
  53. package/dist/lib/request_process_function_base.js +1 -2
  54. package/dist/lib/request_process_function_base.js.map +1 -1
  55. package/dist/lib/schedule_process_function_base.js +2 -2
  56. package/dist/lib/schedule_process_function_base.js.map +1 -1
  57. package/package.json +1 -1
@@ -206,344 +206,465 @@ require("../exntension/string.extension");
206
206
  * Specify the URL to redirect to after authentication.
207
207
  * 認証後のリダイレクト先URLを指定します。
208
208
  */
209
- module.exports = (regions, options, data) => {
210
- var _a;
211
- return functions.https.onCall({
212
- region: regions,
213
- timeoutSeconds: options.timeoutSeconds,
214
- memory: options.memory,
215
- minInstances: options.minInstances,
216
- concurrency: options.concurrency,
217
- maxInstances: (_a = options.maxInstances) !== null && _a !== void 0 ? _a : undefined,
218
- }, (query) => __awaiter(void 0, void 0, void 0, function* () {
219
- var _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _0, _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;
220
- try {
221
- const apiKey = (_b = process.env.PURCHASE_STRIPE_SECRETKEY) !== null && _b !== void 0 ? _b : "";
222
- const stripeUserPath = (_c = process.env.PURCHASE_STRIPE_USERPATH) !== null && _c !== void 0 ? _c : "plugins/stripe/user";
223
- const stripePurchasePath = (_d = process.env.PURCHASE_STRIPE_PURCHASEPATH) !== null && _d !== void 0 ? _d : "purchase";
224
- const stripePaymentPath = (_e = process.env.PURCHASE_STRIPE_PAYMENTPATH) !== null && _e !== void 0 ? _e : "payment";
225
- const stripeEmailProvider = (_f = process.env.PURCHASE_STRIPE_EMAILPROVIDER) !== null && _f !== void 0 ? _f : "gmail";
226
- const firestoreInstance = admin.firestore();
227
- const stripeClient = new stripe.Stripe(apiKey, {
228
- apiVersion: "2022-11-15",
229
- });
230
- switch (query.data.mode) {
231
- case "create_account": {
232
- const userId = query.data.userId;
233
- const locale = query.data.locale;
234
- const refreshUrl = query.data.refreshUrl;
235
- const returnUrl = query.data.returnUrl;
236
- if (!locale) {
237
- throw new functions.https.HttpsError("invalid-argument", "The locale is empty.");
238
- }
239
- if (!userId) {
240
- throw new functions.https.HttpsError("invalid-argument", "The user id is empty.");
241
- }
242
- const country = locale.split("_")[1];
243
- const doc = yield firestoreInstance.doc(`${stripeUserPath}/${userId}`).get();
244
- const data = doc.data();
245
- if (!data || !data["account"]) {
246
- const account = yield stripeClient.accounts.create({
247
- type: "express",
248
- country: country !== null && country !== void 0 ? country : "JP",
249
- });
250
- const update = {};
251
- update["@uid"] = userId;
252
- update["@time"] = new Date();
253
- update["user"] = userId;
254
- update["account"] = account.id;
255
- yield firestoreInstance.doc(`${stripeUserPath}/${userId}`).set(update, {
256
- merge: true,
257
- });
258
- const endpoint = yield stripeClient.accountLinks.create({
259
- type: "account_onboarding",
260
- account: account.id,
261
- refresh_url: refreshUrl,
262
- return_url: returnUrl,
263
- });
264
- return {
265
- next: "registration",
266
- endpoint: endpoint.url,
267
- accountId: account.id,
268
- };
269
- }
270
- else {
271
- if (data["capability"] && data["capability"]["transfers"]) {
272
- return {
273
- next: "none",
274
- };
275
- }
276
- const res = yield stripeClient.accounts.retrieve(data["account"]);
277
- if (res["capabilities"] && res["capabilities"]["transfers"] === "active") {
278
- const update = {};
279
- update["capability"] = {
280
- transfers: true,
281
- };
282
- yield doc.ref.set(update, {
283
- merge: true,
284
- });
285
- return {
286
- next: "none",
287
- };
288
- }
289
- else {
290
- const endpoint = yield stripeClient.accountLinks.create({
291
- type: "account_onboarding",
292
- account: data["account"],
293
- refresh_url: refreshUrl,
294
- return_url: returnUrl,
295
- });
296
- return {
297
- next: "registration",
298
- endpoint: endpoint.url,
299
- accountId: data["account"],
300
- };
301
- }
302
- }
209
+ module.exports = (regions, options, data) => functions.https.onCall({
210
+ region: regions,
211
+ timeoutSeconds: options.timeoutSeconds,
212
+ memory: options.memory,
213
+ minInstances: options.minInstances,
214
+ concurrency: options.concurrency,
215
+ maxInstances: options.maxInstances,
216
+ }, (query) => __awaiter(void 0, void 0, void 0, function* () {
217
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _0, _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;
218
+ try {
219
+ const apiKey = (_a = process.env.PURCHASE_STRIPE_SECRETKEY) !== null && _a !== void 0 ? _a : "";
220
+ const stripeUserPath = (_b = process.env.PURCHASE_STRIPE_USERPATH) !== null && _b !== void 0 ? _b : "plugins/stripe/user";
221
+ const stripePurchasePath = (_c = process.env.PURCHASE_STRIPE_PURCHASEPATH) !== null && _c !== void 0 ? _c : "purchase";
222
+ const stripePaymentPath = (_d = process.env.PURCHASE_STRIPE_PAYMENTPATH) !== null && _d !== void 0 ? _d : "payment";
223
+ const stripeEmailProvider = (_e = process.env.PURCHASE_STRIPE_EMAILPROVIDER) !== null && _e !== void 0 ? _e : "gmail";
224
+ const firestoreInstance = admin.firestore();
225
+ const stripeClient = new stripe.Stripe(apiKey, {
226
+ apiVersion: "2022-11-15",
227
+ });
228
+ switch (query.data.mode) {
229
+ case "create_account": {
230
+ const userId = query.data.userId;
231
+ const locale = query.data.locale;
232
+ const refreshUrl = query.data.refreshUrl;
233
+ const returnUrl = query.data.returnUrl;
234
+ if (!locale) {
235
+ throw new functions.https.HttpsError("invalid-argument", "The locale is empty.");
303
236
  }
304
- case "delete_account": {
305
- const userId = query.data.userId;
306
- if (!userId) {
307
- throw new functions.https.HttpsError("invalid-argument", "The user id is empty.");
308
- }
309
- const doc = yield firestoreInstance.doc(`${stripeUserPath}/${userId}`).get();
310
- const data = doc.data();
311
- if (!data || !data["account"]) {
312
- throw new functions.https.HttpsError("not-found", "Account id is not found.");
313
- }
314
- yield stripeClient.accounts.del(data["account"]);
315
- const update = {};
316
- update["account"] = admin.firestore.FieldValue.delete();
317
- update["capability"] = admin.firestore.FieldValue.arrayRemove({
318
- "transfers": true
237
+ if (!userId) {
238
+ throw new functions.https.HttpsError("invalid-argument", "The user id is empty.");
239
+ }
240
+ const country = locale.split("_")[1];
241
+ const doc = yield firestoreInstance.doc(`${stripeUserPath}/${userId}`).get();
242
+ const data = doc.data();
243
+ if (!data || !data["account"]) {
244
+ const account = yield stripeClient.accounts.create({
245
+ type: "express",
246
+ country: country !== null && country !== void 0 ? country : "JP",
319
247
  });
320
- yield doc.ref.set(update, {
248
+ const update = {};
249
+ update["@uid"] = userId;
250
+ update["@time"] = new Date();
251
+ update["user"] = userId;
252
+ update["account"] = account.id;
253
+ yield firestoreInstance.doc(`${stripeUserPath}/${userId}`).set(update, {
321
254
  merge: true,
322
255
  });
256
+ const endpoint = yield stripeClient.accountLinks.create({
257
+ type: "account_onboarding",
258
+ account: account.id,
259
+ refresh_url: refreshUrl,
260
+ return_url: returnUrl,
261
+ });
323
262
  return {
324
- success: true,
263
+ next: "registration",
264
+ endpoint: endpoint.url,
265
+ accountId: account.id,
325
266
  };
326
267
  }
327
- case "get_account": {
328
- const userId = query.data.userId;
329
- if (!userId) {
330
- throw new functions.https.HttpsError("invalid-argument", "The user id is empty.");
331
- }
332
- const doc = yield firestoreInstance.doc(`${stripeUserPath}/${userId}`).get();
333
- const data = doc.data();
334
- if (!data || !data["account"]) {
335
- throw new functions.https.HttpsError("not-found", "Account id is not found.");
268
+ else {
269
+ if (data["capability"] && data["capability"]["transfers"]) {
270
+ return {
271
+ next: "none",
272
+ };
336
273
  }
337
274
  const res = yield stripeClient.accounts.retrieve(data["account"]);
338
- return res;
339
- }
340
- case "dashboard_account": {
341
- const userId = query.data.userId;
342
- if (!userId) {
343
- throw new functions.https.HttpsError("invalid-argument", "The user id is empty.");
344
- }
345
- const doc = yield firestoreInstance.doc(`${stripeUserPath}/${userId}`).get();
346
- const data = doc.data();
347
- if (!data || !data["account"]) {
348
- throw new functions.https.HttpsError("not-found", "Account id is not found.");
349
- }
350
- const res = yield stripeClient.accounts.createLoginLink(data["account"]);
351
- return {
352
- endpoint: res["url"],
353
- };
354
- }
355
- case "create_customer_and_payment": {
356
- const userId = query.data.userId;
357
- const successUrl = query.data.successUrl;
358
- const cancelUrl = query.data.cancelUrl;
359
- const authInstance = admin.auth();
360
- if (!userId) {
361
- throw new functions.https.HttpsError("invalid-argument", "The user id is empty.");
362
- }
363
- const user = yield authInstance.getUser(userId);
364
- if (!user) {
365
- throw new functions.https.HttpsError("not-found", "The user is not found.");
366
- }
367
- const doc = yield firestoreInstance.doc(`${stripeUserPath}/${userId}`).get();
368
- const data = doc.data();
369
- if (!data || !data["customer"]) {
370
- const customer = yield stripeClient.customers.create({
371
- metadata: {
372
- "user_id": userId,
373
- },
374
- email: (_g = user.email) !== null && _g !== void 0 ? _g : (!data ? null : data["email"]),
375
- });
275
+ if (res["capabilities"] && res["capabilities"]["transfers"] === "active") {
376
276
  const update = {};
377
- update["@uid"] = userId;
378
- update["@time"] = new Date();
379
- update["user"] = userId;
380
- update["customer"] = customer.id;
381
- yield firestoreInstance.doc(`${stripeUserPath}/${userId}`).set(update, {
277
+ update["capability"] = {
278
+ transfers: true,
279
+ };
280
+ yield doc.ref.set(update, {
382
281
  merge: true,
383
282
  });
384
- const session = yield stripeClient.checkout.sessions.create({
385
- payment_method_types: ["card"],
386
- mode: "setup",
387
- customer: customer.id,
388
- success_url: successUrl,
389
- cancel_url: cancelUrl,
390
- metadata: {
391
- "user_id": userId,
392
- },
393
- });
394
283
  return {
395
- endpoint: session.url,
396
- customerId: customer.id,
284
+ next: "none",
397
285
  };
398
286
  }
399
287
  else {
400
- const session = yield stripeClient.checkout.sessions.create({
401
- payment_method_types: ["card"],
402
- mode: "setup",
403
- customer: data["customer"],
404
- success_url: successUrl,
405
- cancel_url: cancelUrl,
288
+ const endpoint = yield stripeClient.accountLinks.create({
289
+ type: "account_onboarding",
290
+ account: data["account"],
291
+ refresh_url: refreshUrl,
292
+ return_url: returnUrl,
406
293
  });
407
294
  return {
408
- endpoint: session.url,
409
- customerId: data["customer"],
295
+ next: "registration",
296
+ endpoint: endpoint.url,
297
+ accountId: data["account"],
410
298
  };
411
299
  }
412
300
  }
413
- case "set_customer_default_payment": {
414
- const userId = query.data.userId;
415
- const paymentId = query.data.paymentId;
416
- if (!paymentId) {
417
- throw new functions.https.HttpsError("invalid-argument", "The payment id is empty.");
418
- }
419
- if (!userId) {
420
- throw new functions.https.HttpsError("invalid-argument", "The user id is empty.");
421
- }
422
- const doc = yield firestoreInstance.doc(`${stripeUserPath}/${userId}`).get();
423
- const data = doc.data();
424
- if (!data || !data["customer"]) {
425
- throw new functions.https.HttpsError("not-found", "The customer is empty.");
426
- }
427
- const payment = yield firestoreInstance.doc(`${stripeUserPath}/${userId}/${stripePaymentPath}/${paymentId}`).get();
428
- const paymentData = payment.data();
429
- if (!paymentData || !paymentData["id"]) {
430
- throw new functions.https.HttpsError("not-found", "The payment method is empty.");
431
- }
432
- yield stripeClient.customers.update(data["customer"], {
433
- invoice_settings: {
434
- default_payment_method: paymentData["id"],
301
+ }
302
+ case "delete_account": {
303
+ const userId = query.data.userId;
304
+ if (!userId) {
305
+ throw new functions.https.HttpsError("invalid-argument", "The user id is empty.");
306
+ }
307
+ const doc = yield firestoreInstance.doc(`${stripeUserPath}/${userId}`).get();
308
+ const data = doc.data();
309
+ if (!data || !data["account"]) {
310
+ throw new functions.https.HttpsError("not-found", "Account id is not found.");
311
+ }
312
+ yield stripeClient.accounts.del(data["account"]);
313
+ const update = {};
314
+ update["account"] = admin.firestore.FieldValue.delete();
315
+ update["capability"] = admin.firestore.FieldValue.arrayRemove({
316
+ "transfers": true
317
+ });
318
+ yield doc.ref.set(update, {
319
+ merge: true,
320
+ });
321
+ return {
322
+ success: true,
323
+ };
324
+ }
325
+ case "get_account": {
326
+ const userId = query.data.userId;
327
+ if (!userId) {
328
+ throw new functions.https.HttpsError("invalid-argument", "The user id is empty.");
329
+ }
330
+ const doc = yield firestoreInstance.doc(`${stripeUserPath}/${userId}`).get();
331
+ const data = doc.data();
332
+ if (!data || !data["account"]) {
333
+ throw new functions.https.HttpsError("not-found", "Account id is not found.");
334
+ }
335
+ const res = yield stripeClient.accounts.retrieve(data["account"]);
336
+ return res;
337
+ }
338
+ case "dashboard_account": {
339
+ const userId = query.data.userId;
340
+ if (!userId) {
341
+ throw new functions.https.HttpsError("invalid-argument", "The user id is empty.");
342
+ }
343
+ const doc = yield firestoreInstance.doc(`${stripeUserPath}/${userId}`).get();
344
+ const data = doc.data();
345
+ if (!data || !data["account"]) {
346
+ throw new functions.https.HttpsError("not-found", "Account id is not found.");
347
+ }
348
+ const res = yield stripeClient.accounts.createLoginLink(data["account"]);
349
+ return {
350
+ endpoint: res["url"],
351
+ };
352
+ }
353
+ case "create_customer_and_payment": {
354
+ const userId = query.data.userId;
355
+ const successUrl = query.data.successUrl;
356
+ const cancelUrl = query.data.cancelUrl;
357
+ const authInstance = admin.auth();
358
+ if (!userId) {
359
+ throw new functions.https.HttpsError("invalid-argument", "The user id is empty.");
360
+ }
361
+ const user = yield authInstance.getUser(userId);
362
+ if (!user) {
363
+ throw new functions.https.HttpsError("not-found", "The user is not found.");
364
+ }
365
+ const doc = yield firestoreInstance.doc(`${stripeUserPath}/${userId}`).get();
366
+ const data = doc.data();
367
+ if (!data || !data["customer"]) {
368
+ const customer = yield stripeClient.customers.create({
369
+ metadata: {
370
+ "user_id": userId,
371
+ },
372
+ email: (_f = user.email) !== null && _f !== void 0 ? _f : (!data ? null : data["email"]),
373
+ });
374
+ const update = {};
375
+ update["@uid"] = userId;
376
+ update["@time"] = new Date();
377
+ update["user"] = userId;
378
+ update["customer"] = customer.id;
379
+ yield firestoreInstance.doc(`${stripeUserPath}/${userId}`).set(update, {
380
+ merge: true,
381
+ });
382
+ const session = yield stripeClient.checkout.sessions.create({
383
+ payment_method_types: ["card"],
384
+ mode: "setup",
385
+ customer: customer.id,
386
+ success_url: successUrl,
387
+ cancel_url: cancelUrl,
388
+ metadata: {
389
+ "user_id": userId,
435
390
  },
436
391
  });
437
- if (data["defaultPayment"] !== paymentData["id"]) {
438
- const update = {};
439
- update["defaultPayment"] = paymentData["id"];
440
- yield doc.ref.set(update, {
441
- merge: true,
442
- });
443
- }
444
392
  return {
445
- success: true,
393
+ endpoint: session.url,
394
+ customerId: customer.id,
446
395
  };
447
396
  }
448
- case "delete_payment": {
449
- const userId = query.data.userId;
450
- const paymentId = query.data.paymentId;
451
- if (!paymentId) {
452
- throw new functions.https.HttpsError("invalid-argument", "The payment id is empty.");
453
- }
454
- if (!userId) {
455
- throw new functions.https.HttpsError("invalid-argument", "The user id is empty.");
456
- }
457
- const doc = yield firestoreInstance.doc(`${stripeUserPath}/${userId}`).get();
458
- const data = doc.data();
459
- if (!data || !data["customer"]) {
460
- throw new functions.https.HttpsError("not-found", "The customer is empty.");
461
- }
462
- const payment = yield firestoreInstance.doc(`${stripeUserPath}/${userId}/${stripePaymentPath}/${paymentId}`).get();
463
- const paymentData = payment.data();
464
- if (!paymentData || !paymentData["id"]) {
465
- throw new functions.https.HttpsError("not-found", "The payment method is empty.");
466
- }
467
- yield stripeClient.paymentMethods.detach(paymentData["id"]);
468
- if (data["defaultPayment"] === paymentData["id"]) {
469
- const update = {};
470
- update["defaultPayment"] = admin.firestore.FieldValue.delete();
471
- yield doc.ref.set(update, {
472
- merge: true,
473
- });
474
- }
397
+ else {
398
+ const session = yield stripeClient.checkout.sessions.create({
399
+ payment_method_types: ["card"],
400
+ mode: "setup",
401
+ customer: data["customer"],
402
+ success_url: successUrl,
403
+ cancel_url: cancelUrl,
404
+ });
475
405
  return {
476
- success: true,
406
+ endpoint: session.url,
407
+ customerId: data["customer"],
477
408
  };
478
409
  }
479
- case "delete_customer": {
480
- const userId = query.data.userId;
481
- if (!userId) {
482
- throw new functions.https.HttpsError("invalid-argument", "The user id is empty.");
483
- }
484
- const doc = yield firestoreInstance.doc(`${stripeUserPath}/${userId}`).get();
485
- const data = doc.data();
486
- if (!data || !data["customer"]) {
487
- throw new functions.https.HttpsError("not-found", "Customer id is not found.");
488
- }
489
- yield stripeClient.customers.del(data["customer"]);
410
+ }
411
+ case "set_customer_default_payment": {
412
+ const userId = query.data.userId;
413
+ const paymentId = query.data.paymentId;
414
+ if (!paymentId) {
415
+ throw new functions.https.HttpsError("invalid-argument", "The payment id is empty.");
416
+ }
417
+ if (!userId) {
418
+ throw new functions.https.HttpsError("invalid-argument", "The user id is empty.");
419
+ }
420
+ const doc = yield firestoreInstance.doc(`${stripeUserPath}/${userId}`).get();
421
+ const data = doc.data();
422
+ if (!data || !data["customer"]) {
423
+ throw new functions.https.HttpsError("not-found", "The customer is empty.");
424
+ }
425
+ const payment = yield firestoreInstance.doc(`${stripeUserPath}/${userId}/${stripePaymentPath}/${paymentId}`).get();
426
+ const paymentData = payment.data();
427
+ if (!paymentData || !paymentData["id"]) {
428
+ throw new functions.https.HttpsError("not-found", "The payment method is empty.");
429
+ }
430
+ yield stripeClient.customers.update(data["customer"], {
431
+ invoice_settings: {
432
+ default_payment_method: paymentData["id"],
433
+ },
434
+ });
435
+ if (data["defaultPayment"] !== paymentData["id"]) {
490
436
  const update = {};
491
- update["customer"] = admin.firestore.FieldValue.delete();
437
+ update["defaultPayment"] = paymentData["id"];
492
438
  yield doc.ref.set(update, {
493
439
  merge: true,
494
440
  });
495
- return {
496
- success: true,
497
- };
498
441
  }
499
- case "authorization": {
500
- const authInstance = admin.auth();
501
- const amount = parseFloat(query.data.amount);
502
- const currency = (_h = query.data.currency) !== null && _h !== void 0 ? _h : "jpy";
503
- const returnUrl = query.data.returnUrl;
504
- const online = query.data.online == "true";
505
- const emailFrom = query.data.from;
506
- const emailTitle = query.data.title;
507
- const emailContent = query.data.content;
508
- const userId = query.data.userId;
509
- if (!userId) {
510
- throw new functions.https.HttpsError("invalid-argument", "The user id is empty.");
511
- }
512
- const userDoc = yield firestoreInstance.doc(`${stripeUserPath}/${userId}`).get();
513
- const userData = userDoc.data();
514
- if (!userData || !userData["customer"]) {
515
- throw new functions.https.HttpsError("not-found", "The customer id is not found.");
516
- }
517
- let defaultPayment = userData["defaultPayment"];
442
+ return {
443
+ success: true,
444
+ };
445
+ }
446
+ case "delete_payment": {
447
+ const userId = query.data.userId;
448
+ const paymentId = query.data.paymentId;
449
+ if (!paymentId) {
450
+ throw new functions.https.HttpsError("invalid-argument", "The payment id is empty.");
451
+ }
452
+ if (!userId) {
453
+ throw new functions.https.HttpsError("invalid-argument", "The user id is empty.");
454
+ }
455
+ const doc = yield firestoreInstance.doc(`${stripeUserPath}/${userId}`).get();
456
+ const data = doc.data();
457
+ if (!data || !data["customer"]) {
458
+ throw new functions.https.HttpsError("not-found", "The customer is empty.");
459
+ }
460
+ const payment = yield firestoreInstance.doc(`${stripeUserPath}/${userId}/${stripePaymentPath}/${paymentId}`).get();
461
+ const paymentData = payment.data();
462
+ if (!paymentData || !paymentData["id"]) {
463
+ throw new functions.https.HttpsError("not-found", "The payment method is empty.");
464
+ }
465
+ yield stripeClient.paymentMethods.detach(paymentData["id"]);
466
+ if (data["defaultPayment"] === paymentData["id"]) {
467
+ const update = {};
468
+ update["defaultPayment"] = admin.firestore.FieldValue.delete();
469
+ yield doc.ref.set(update, {
470
+ merge: true,
471
+ });
472
+ }
473
+ return {
474
+ success: true,
475
+ };
476
+ }
477
+ case "delete_customer": {
478
+ const userId = query.data.userId;
479
+ if (!userId) {
480
+ throw new functions.https.HttpsError("invalid-argument", "The user id is empty.");
481
+ }
482
+ const doc = yield firestoreInstance.doc(`${stripeUserPath}/${userId}`).get();
483
+ const data = doc.data();
484
+ if (!data || !data["customer"]) {
485
+ throw new functions.https.HttpsError("not-found", "Customer id is not found.");
486
+ }
487
+ yield stripeClient.customers.del(data["customer"]);
488
+ const update = {};
489
+ update["customer"] = admin.firestore.FieldValue.delete();
490
+ yield doc.ref.set(update, {
491
+ merge: true,
492
+ });
493
+ return {
494
+ success: true,
495
+ };
496
+ }
497
+ case "authorization": {
498
+ const authInstance = admin.auth();
499
+ const amount = parseFloat(query.data.amount);
500
+ const currency = (_g = query.data.currency) !== null && _g !== void 0 ? _g : "jpy";
501
+ const returnUrl = query.data.returnUrl;
502
+ const online = query.data.online == "true";
503
+ const emailFrom = query.data.from;
504
+ const emailTitle = query.data.title;
505
+ const emailContent = query.data.content;
506
+ const userId = query.data.userId;
507
+ if (!userId) {
508
+ throw new functions.https.HttpsError("invalid-argument", "The user id is empty.");
509
+ }
510
+ const userDoc = yield firestoreInstance.doc(`${stripeUserPath}/${userId}`).get();
511
+ const userData = userDoc.data();
512
+ if (!userData || !userData["customer"]) {
513
+ throw new functions.https.HttpsError("not-found", "The customer id is not found.");
514
+ }
515
+ let defaultPayment = userData["defaultPayment"];
516
+ if (!defaultPayment) {
517
+ const customer = yield stripeClient.customers.retrieve(userData["customer"]);
518
+ defaultPayment = customer.invoice_settings.default_payment_method;
518
519
  if (!defaultPayment) {
519
- const customer = yield stripeClient.customers.retrieve(userData["customer"]);
520
- defaultPayment = customer.invoice_settings.default_payment_method;
521
- if (!defaultPayment) {
522
- const payments = yield firestoreInstance.collection(`${stripeUserPath}/${userId}/${stripePaymentPath}`).get();
523
- if (payments.size <= 0) {
524
- throw new functions.https.HttpsError("not-found", "The payment method is not found.");
525
- }
526
- defaultPayment = payments.docs[0].data()["id"];
520
+ const payments = yield firestoreInstance.collection(`${stripeUserPath}/${userId}/${stripePaymentPath}`).get();
521
+ if (payments.size <= 0) {
522
+ throw new functions.https.HttpsError("not-found", "The payment method is not found.");
527
523
  }
528
- const update = {};
529
- update["defaultPayment"] = defaultPayment;
530
- yield userDoc.ref.set(update, {
531
- merge: true,
532
- });
524
+ defaultPayment = payments.docs[0].data()["id"];
533
525
  }
534
- const user = yield authInstance.getUser(userId);
535
- if (!user) {
536
- throw new functions.https.HttpsError("not-found", "The user is not found.");
526
+ const update = {};
527
+ update["defaultPayment"] = defaultPayment;
528
+ yield userDoc.ref.set(update, {
529
+ merge: true,
530
+ });
531
+ }
532
+ const user = yield authInstance.getUser(userId);
533
+ if (!user) {
534
+ throw new functions.https.HttpsError("not-found", "The user is not found.");
535
+ }
536
+ let email = user.email;
537
+ if (!email) {
538
+ const paymentMethod = yield stripeClient.paymentMethods.retrieve(defaultPayment);
539
+ if (paymentMethod && paymentMethod["billing_details"] && paymentMethod["billing_details"]["email"]) {
540
+ email = paymentMethod["billing_details"]["email"];
537
541
  }
538
- let email = user.email;
539
542
  if (!email) {
540
- const paymentMethod = yield stripeClient.paymentMethods.retrieve(defaultPayment);
541
- if (paymentMethod && paymentMethod["billing_details"] && paymentMethod["billing_details"]["email"]) {
542
- email = paymentMethod["billing_details"]["email"];
543
+ throw new functions.https.HttpsError("not-found", "The user's email is not found.");
544
+ }
545
+ }
546
+ const paymentIntent = yield stripeClient.paymentIntents.create({
547
+ payment_method_types: ["card"],
548
+ amount: amount,
549
+ confirm: false,
550
+ capture_method: "manual",
551
+ payment_method: defaultPayment,
552
+ description: "",
553
+ customer: userData["customer"],
554
+ receipt_email: email,
555
+ currency: currency !== null && currency !== void 0 ? currency : "usd",
556
+ setup_future_usage: "off_session",
557
+ });
558
+ if (!paymentIntent) {
559
+ throw new functions.https.HttpsError("data-loss", "The payment is failed.");
560
+ }
561
+ const confirmedPaymentIntent = yield stripeClient.paymentIntents.confirm(paymentIntent.id, {
562
+ return_url: returnUrl,
563
+ });
564
+ const nextActionUrl = (_k = (_j = (_h = confirmedPaymentIntent.next_action) === null || _h === void 0 ? void 0 : _h.redirect_to_url) === null || _j === void 0 ? void 0 : _j.url) !== null && _k !== void 0 ? _k : "";
565
+ if (nextActionUrl && !online) {
566
+ if (emailFrom && email && emailTitle && emailContent) {
567
+ switch (stripeEmailProvider) {
568
+ case "gmail": {
569
+ yield gmail.send({
570
+ from: emailFrom,
571
+ to: email,
572
+ title: emailTitle,
573
+ content: emailContent.replace("{url}", nextActionUrl),
574
+ });
575
+ break;
576
+ }
577
+ case "sendgrid": {
578
+ yield sendgrid.send({
579
+ from: emailFrom,
580
+ to: email,
581
+ title: emailTitle,
582
+ content: emailContent.replace("{url}", nextActionUrl),
583
+ });
584
+ break;
585
+ }
543
586
  }
544
- if (!email) {
545
- throw new functions.https.HttpsError("not-found", "The user's email is not found.");
587
+ }
588
+ else {
589
+ throw new functions.https.HttpsError("unavailable", "3D Secure authentication is required, but the user is offline and no email settings have been configured.");
590
+ }
591
+ }
592
+ return {
593
+ url: online ? nextActionUrl : "",
594
+ returnUrl: online ? (_o = (_m = (_l = confirmedPaymentIntent.next_action) === null || _l === void 0 ? void 0 : _l.redirect_to_url) === null || _m === void 0 ? void 0 : _m.return_url) !== null && _o !== void 0 ? _o : "" : "",
595
+ authorizedId: paymentIntent.id,
596
+ };
597
+ }
598
+ case "confirm_authorization": {
599
+ const authorizedId = query.data.authorizedId;
600
+ if (!authorizedId) {
601
+ throw new functions.https.HttpsError("invalid-argument", "The authorized id is empty.");
602
+ }
603
+ yield stripeClient.paymentIntents.cancel(authorizedId);
604
+ return {
605
+ success: true,
606
+ };
607
+ }
608
+ case "create_purchase": {
609
+ const authInstance = admin.auth();
610
+ const amount = parseFloat(query.data.amount);
611
+ const revenue = parseFloat((_p = query.data.revenueRatio) !== null && _p !== void 0 ? _p : 0);
612
+ const currency = (_q = query.data.currency) !== null && _q !== void 0 ? _q : "jpy";
613
+ const userId = query.data.userId;
614
+ const targetUserId = query.data.targetUserId;
615
+ const orderId = query.data.orderId;
616
+ const description = query.data.description;
617
+ const emailFrom = query.data.emailFrom;
618
+ const emailTitle = query.data.emailTitle;
619
+ const emailContent = query.data.emailContent;
620
+ const locale = query.data.locale;
621
+ if (!orderId) {
622
+ throw new functions.https.HttpsError("invalid-argument", "The order id is empty.");
623
+ }
624
+ if (!userId) {
625
+ throw new functions.https.HttpsError("invalid-argument", "The user id is empty.");
626
+ }
627
+ const userDoc = yield firestoreInstance.doc(`${stripeUserPath}/${userId}`).get();
628
+ const userData = userDoc.data();
629
+ if (!userData || !userData["customer"]) {
630
+ throw new functions.https.HttpsError("not-found", "The customer id is not found.");
631
+ }
632
+ let defaultPayment = userData["defaultPayment"];
633
+ if (!defaultPayment) {
634
+ const customer = yield stripeClient.customers.retrieve(userData["customer"]);
635
+ defaultPayment = customer.invoice_settings.default_payment_method;
636
+ if (!defaultPayment) {
637
+ const payments = yield firestoreInstance.collection(`${stripeUserPath}/${userId}/${stripePaymentPath}`).get();
638
+ if (payments.size <= 0) {
639
+ throw new functions.https.HttpsError("not-found", "The payment method is not found.");
546
640
  }
641
+ defaultPayment = payments.docs[0].data()["id"];
642
+ }
643
+ const update = {};
644
+ update["defaultPayment"] = defaultPayment;
645
+ yield userDoc.ref.set(update, {
646
+ merge: true,
647
+ });
648
+ }
649
+ const user = yield authInstance.getUser(userId);
650
+ if (!user) {
651
+ throw new functions.https.HttpsError("not-found", "The user is not found.");
652
+ }
653
+ let email = user.email;
654
+ if (!email) {
655
+ const paymentMethod = yield stripeClient.paymentMethods.retrieve(defaultPayment);
656
+ if (paymentMethod && paymentMethod["billing_details"] && paymentMethod["billing_details"]["email"]) {
657
+ email = paymentMethod["billing_details"]["email"];
658
+ }
659
+ if (!email) {
660
+ throw new functions.https.HttpsError("not-found", "The user's email is not found.");
661
+ }
662
+ }
663
+ if (targetUserId) {
664
+ const targetDoc = yield firestoreInstance.doc(`${stripeUserPath}/${targetUserId}`).get();
665
+ const targetData = targetDoc.data();
666
+ if (!targetData || !targetData["account"]) {
667
+ throw new functions.https.HttpsError("not-found", "The target data is not found.");
547
668
  }
548
669
  const paymentIntent = yield stripeClient.paymentIntents.create({
549
670
  payment_method_types: ["card"],
@@ -551,355 +672,161 @@ module.exports = (regions, options, data) => {
551
672
  confirm: false,
552
673
  capture_method: "manual",
553
674
  payment_method: defaultPayment,
554
- description: "",
675
+ description: description,
555
676
  customer: userData["customer"],
677
+ metadata: {
678
+ "order_id": orderId,
679
+ },
556
680
  receipt_email: email,
557
- currency: currency !== null && currency !== void 0 ? currency : "usd",
681
+ currency: currency,
558
682
  setup_future_usage: "off_session",
683
+ application_fee_amount: amount * revenue,
684
+ transfer_data: {
685
+ destination: targetData["account"],
686
+ },
559
687
  });
560
688
  if (!paymentIntent) {
561
689
  throw new functions.https.HttpsError("data-loss", "The payment is failed.");
562
690
  }
563
- const confirmedPaymentIntent = yield stripeClient.paymentIntents.confirm(paymentIntent.id, {
564
- return_url: returnUrl,
691
+ const update = {};
692
+ update["@uid"] = orderId;
693
+ update["orderId"] = orderId;
694
+ update["purchaseId"] = paymentIntent.id;
695
+ update["paymentMethodId"] = defaultPayment;
696
+ update["confirm"] = false;
697
+ update["verify"] = false;
698
+ update["capture"] = false;
699
+ update["success"] = false;
700
+ update["user"] = userId;
701
+ update["target"] = targetUserId;
702
+ update["nextAction"] = {
703
+ url: (_t = (_s = (_r = paymentIntent.next_action) === null || _r === void 0 ? void 0 : _r.redirect_to_url) === null || _s === void 0 ? void 0 : _s.url) !== null && _t !== void 0 ? _t : "",
704
+ returnUrl: (_w = (_v = (_u = paymentIntent.next_action) === null || _u === void 0 ? void 0 : _u.redirect_to_url) === null || _v === void 0 ? void 0 : _v.return_url) !== null && _w !== void 0 ? _w : "",
705
+ };
706
+ update["targetAccount"] = targetData["account"];
707
+ update["customer"] = userData["customer"];
708
+ update["amount"] = paymentIntent.amount;
709
+ update["application"] = paymentIntent.application;
710
+ update["applicationFeeAmount"] = paymentIntent.application_fee_amount;
711
+ update["transferAmount"] = (_y = (_x = paymentIntent.transfer_data) === null || _x === void 0 ? void 0 : _x.amount) !== null && _y !== void 0 ? _y : 0;
712
+ update["transferDistination"] = (_0 = (_z = paymentIntent.transfer_data) === null || _z === void 0 ? void 0 : _z.destination) !== null && _0 !== void 0 ? _0 : "";
713
+ update["currency"] = paymentIntent.currency;
714
+ update["clientSecret"] = paymentIntent.client_secret;
715
+ update["createdTime"] = new Date(paymentIntent.created * 1000);
716
+ update["updatedTime"] = new Date();
717
+ update["emailFrom"] = emailFrom;
718
+ update["emailTo"] = email;
719
+ update["emailTitle"] = emailTitle;
720
+ update["emailContent"] = emailContent;
721
+ update["locale"] = locale;
722
+ yield firestoreInstance.doc(`${stripeUserPath}/${userId}/${stripePurchasePath}/${orderId}`).set(update, {
723
+ merge: true,
565
724
  });
566
- const nextActionUrl = (_l = (_k = (_j = confirmedPaymentIntent.next_action) === null || _j === void 0 ? void 0 : _j.redirect_to_url) === null || _k === void 0 ? void 0 : _k.url) !== null && _l !== void 0 ? _l : "";
567
- if (nextActionUrl && !online) {
568
- if (emailFrom && email && emailTitle && emailContent) {
569
- switch (stripeEmailProvider) {
570
- case "gmail": {
571
- yield gmail.send({
572
- from: emailFrom,
573
- to: email,
574
- title: emailTitle,
575
- content: emailContent.replace("{url}", nextActionUrl),
576
- });
577
- break;
578
- }
579
- case "sendgrid": {
580
- yield sendgrid.send({
581
- from: emailFrom,
582
- to: email,
583
- title: emailTitle,
584
- content: emailContent.replace("{url}", nextActionUrl),
585
- });
586
- break;
587
- }
588
- }
589
- }
590
- else {
591
- throw new functions.https.HttpsError("unavailable", "3D Secure authentication is required, but the user is offline and no email settings have been configured.");
592
- }
593
- }
594
725
  return {
595
- url: online ? nextActionUrl : "",
596
- returnUrl: online ? (_p = (_o = (_m = confirmedPaymentIntent.next_action) === null || _m === void 0 ? void 0 : _m.redirect_to_url) === null || _o === void 0 ? void 0 : _o.return_url) !== null && _p !== void 0 ? _p : "" : "",
597
- authorizedId: paymentIntent.id,
726
+ purchaseId: paymentIntent.id,
598
727
  };
599
728
  }
600
- case "confirm_authorization": {
601
- const authorizedId = query.data.authorizedId;
602
- if (!authorizedId) {
603
- throw new functions.https.HttpsError("invalid-argument", "The authorized id is empty.");
729
+ else {
730
+ const paymentIntent = yield stripeClient.paymentIntents.create({
731
+ payment_method_types: ["card"],
732
+ amount: amount,
733
+ confirm: false,
734
+ capture_method: "manual",
735
+ payment_method: defaultPayment,
736
+ description: description,
737
+ customer: userData["customer"],
738
+ metadata: {
739
+ "order_id": orderId,
740
+ },
741
+ receipt_email: email,
742
+ currency: currency,
743
+ setup_future_usage: "off_session",
744
+ });
745
+ if (!paymentIntent) {
746
+ throw new functions.https.HttpsError("data-loss", "The payment is failed.");
604
747
  }
605
- yield stripeClient.paymentIntents.cancel(authorizedId);
748
+ const update = {};
749
+ update["@uid"] = orderId;
750
+ update["orderId"] = orderId;
751
+ update["purchaseId"] = paymentIntent.id;
752
+ update["paymentMethodId"] = defaultPayment;
753
+ update["confirm"] = false;
754
+ update["verify"] = false;
755
+ update["capture"] = false;
756
+ update["success"] = false;
757
+ update["user"] = userId;
758
+ update["nextAction"] = {
759
+ url: (_3 = (_2 = (_1 = paymentIntent.next_action) === null || _1 === void 0 ? void 0 : _1.redirect_to_url) === null || _2 === void 0 ? void 0 : _2.url) !== null && _3 !== void 0 ? _3 : "",
760
+ returnUrl: (_6 = (_5 = (_4 = paymentIntent.next_action) === null || _4 === void 0 ? void 0 : _4.redirect_to_url) === null || _5 === void 0 ? void 0 : _5.return_url) !== null && _6 !== void 0 ? _6 : "",
761
+ };
762
+ update["customer"] = userData["customer"];
763
+ update["amount"] = paymentIntent.amount;
764
+ update["application"] = paymentIntent.application;
765
+ update["applicationFeeAmount"] = paymentIntent.application_fee_amount;
766
+ update["transferAmount"] = (_8 = (_7 = paymentIntent.transfer_data) === null || _7 === void 0 ? void 0 : _7.amount) !== null && _8 !== void 0 ? _8 : 0;
767
+ update["transferDistination"] = (_10 = (_9 = paymentIntent.transfer_data) === null || _9 === void 0 ? void 0 : _9.destination) !== null && _10 !== void 0 ? _10 : "";
768
+ update["currency"] = paymentIntent.currency;
769
+ update["clientSecret"] = paymentIntent.client_secret;
770
+ update["createdTime"] = new Date(paymentIntent.created * 1000);
771
+ update["updatedTime"] = new Date();
772
+ update["emailFrom"] = emailFrom;
773
+ update["emailTo"] = email;
774
+ update["emailTitle"] = emailTitle;
775
+ update["emailContent"] = emailContent;
776
+ update["locale"] = locale;
777
+ yield firestoreInstance.doc(`${stripeUserPath}/${userId}/${stripePurchasePath}/${orderId}`).set(update, {
778
+ merge: true,
779
+ });
606
780
  return {
607
- success: true,
781
+ purchaseId: paymentIntent.id,
608
782
  };
609
783
  }
610
- case "create_purchase": {
611
- const authInstance = admin.auth();
612
- const amount = parseFloat(query.data.amount);
613
- const revenue = parseFloat((_q = query.data.revenueRatio) !== null && _q !== void 0 ? _q : 0);
614
- const currency = (_r = query.data.currency) !== null && _r !== void 0 ? _r : "jpy";
615
- const userId = query.data.userId;
616
- const targetUserId = query.data.targetUserId;
617
- const orderId = query.data.orderId;
618
- const description = query.data.description;
619
- const emailFrom = query.data.emailFrom;
620
- const emailTitle = query.data.emailTitle;
621
- const emailContent = query.data.emailContent;
622
- const locale = query.data.locale;
623
- if (!orderId) {
624
- throw new functions.https.HttpsError("invalid-argument", "The order id is empty.");
625
- }
626
- if (!userId) {
627
- throw new functions.https.HttpsError("invalid-argument", "The user id is empty.");
628
- }
629
- const userDoc = yield firestoreInstance.doc(`${stripeUserPath}/${userId}`).get();
630
- const userData = userDoc.data();
631
- if (!userData || !userData["customer"]) {
632
- throw new functions.https.HttpsError("not-found", "The customer id is not found.");
633
- }
634
- let defaultPayment = userData["defaultPayment"];
635
- if (!defaultPayment) {
636
- const customer = yield stripeClient.customers.retrieve(userData["customer"]);
637
- defaultPayment = customer.invoice_settings.default_payment_method;
638
- if (!defaultPayment) {
639
- const payments = yield firestoreInstance.collection(`${stripeUserPath}/${userId}/${stripePaymentPath}`).get();
640
- if (payments.size <= 0) {
641
- throw new functions.https.HttpsError("not-found", "The payment method is not found.");
642
- }
643
- defaultPayment = payments.docs[0].data()["id"];
644
- }
645
- const update = {};
646
- update["defaultPayment"] = defaultPayment;
647
- yield userDoc.ref.set(update, {
648
- merge: true,
649
- });
650
- }
651
- const user = yield authInstance.getUser(userId);
652
- if (!user) {
653
- throw new functions.https.HttpsError("not-found", "The user is not found.");
654
- }
655
- let email = user.email;
656
- if (!email) {
657
- const paymentMethod = yield stripeClient.paymentMethods.retrieve(defaultPayment);
658
- if (paymentMethod && paymentMethod["billing_details"] && paymentMethod["billing_details"]["email"]) {
659
- email = paymentMethod["billing_details"]["email"];
660
- }
661
- if (!email) {
662
- throw new functions.https.HttpsError("not-found", "The user's email is not found.");
663
- }
664
- }
665
- if (targetUserId) {
666
- const targetDoc = yield firestoreInstance.doc(`${stripeUserPath}/${targetUserId}`).get();
667
- const targetData = targetDoc.data();
668
- if (!targetData || !targetData["account"]) {
669
- throw new functions.https.HttpsError("not-found", "The target data is not found.");
670
- }
671
- const paymentIntent = yield stripeClient.paymentIntents.create({
672
- payment_method_types: ["card"],
673
- amount: amount,
674
- confirm: false,
675
- capture_method: "manual",
676
- payment_method: defaultPayment,
677
- description: description,
678
- customer: userData["customer"],
679
- metadata: {
680
- "order_id": orderId,
681
- },
682
- receipt_email: email,
683
- currency: currency,
684
- setup_future_usage: "off_session",
685
- application_fee_amount: amount * revenue,
686
- transfer_data: {
687
- destination: targetData["account"],
688
- },
689
- });
690
- if (!paymentIntent) {
691
- throw new functions.https.HttpsError("data-loss", "The payment is failed.");
692
- }
693
- const update = {};
694
- update["@uid"] = orderId;
695
- update["orderId"] = orderId;
696
- update["purchaseId"] = paymentIntent.id;
697
- update["paymentMethodId"] = defaultPayment;
698
- update["confirm"] = false;
699
- update["verify"] = false;
700
- update["capture"] = false;
701
- update["success"] = false;
702
- update["user"] = userId;
703
- update["target"] = targetUserId;
704
- update["nextAction"] = {
705
- url: (_u = (_t = (_s = paymentIntent.next_action) === null || _s === void 0 ? void 0 : _s.redirect_to_url) === null || _t === void 0 ? void 0 : _t.url) !== null && _u !== void 0 ? _u : "",
706
- returnUrl: (_x = (_w = (_v = paymentIntent.next_action) === null || _v === void 0 ? void 0 : _v.redirect_to_url) === null || _w === void 0 ? void 0 : _w.return_url) !== null && _x !== void 0 ? _x : "",
707
- };
708
- update["targetAccount"] = targetData["account"];
709
- update["customer"] = userData["customer"];
710
- update["amount"] = paymentIntent.amount;
711
- update["application"] = paymentIntent.application;
712
- update["applicationFeeAmount"] = paymentIntent.application_fee_amount;
713
- update["transferAmount"] = (_z = (_y = paymentIntent.transfer_data) === null || _y === void 0 ? void 0 : _y.amount) !== null && _z !== void 0 ? _z : 0;
714
- update["transferDistination"] = (_1 = (_0 = paymentIntent.transfer_data) === null || _0 === void 0 ? void 0 : _0.destination) !== null && _1 !== void 0 ? _1 : "";
715
- update["currency"] = paymentIntent.currency;
716
- update["clientSecret"] = paymentIntent.client_secret;
717
- update["createdTime"] = new Date(paymentIntent.created * 1000);
718
- update["updatedTime"] = new Date();
719
- update["emailFrom"] = emailFrom;
720
- update["emailTo"] = email;
721
- update["emailTitle"] = emailTitle;
722
- update["emailContent"] = emailContent;
723
- update["locale"] = locale;
724
- yield firestoreInstance.doc(`${stripeUserPath}/${userId}/${stripePurchasePath}/${orderId}`).set(update, {
725
- merge: true,
726
- });
727
- return {
728
- purchaseId: paymentIntent.id,
729
- };
730
- }
731
- else {
732
- const paymentIntent = yield stripeClient.paymentIntents.create({
733
- payment_method_types: ["card"],
734
- amount: amount,
735
- confirm: false,
736
- capture_method: "manual",
737
- payment_method: defaultPayment,
738
- description: description,
739
- customer: userData["customer"],
740
- metadata: {
741
- "order_id": orderId,
742
- },
743
- receipt_email: email,
744
- currency: currency,
745
- setup_future_usage: "off_session",
746
- });
747
- if (!paymentIntent) {
748
- throw new functions.https.HttpsError("data-loss", "The payment is failed.");
749
- }
750
- const update = {};
751
- update["@uid"] = orderId;
752
- update["orderId"] = orderId;
753
- update["purchaseId"] = paymentIntent.id;
754
- update["paymentMethodId"] = defaultPayment;
755
- update["confirm"] = false;
756
- update["verify"] = false;
757
- update["capture"] = false;
758
- update["success"] = false;
759
- update["user"] = userId;
760
- update["nextAction"] = {
761
- url: (_4 = (_3 = (_2 = paymentIntent.next_action) === null || _2 === void 0 ? void 0 : _2.redirect_to_url) === null || _3 === void 0 ? void 0 : _3.url) !== null && _4 !== void 0 ? _4 : "",
762
- returnUrl: (_7 = (_6 = (_5 = paymentIntent.next_action) === null || _5 === void 0 ? void 0 : _5.redirect_to_url) === null || _6 === void 0 ? void 0 : _6.return_url) !== null && _7 !== void 0 ? _7 : "",
763
- };
764
- update["customer"] = userData["customer"];
765
- update["amount"] = paymentIntent.amount;
766
- update["application"] = paymentIntent.application;
767
- update["applicationFeeAmount"] = paymentIntent.application_fee_amount;
768
- update["transferAmount"] = (_9 = (_8 = paymentIntent.transfer_data) === null || _8 === void 0 ? void 0 : _8.amount) !== null && _9 !== void 0 ? _9 : 0;
769
- update["transferDistination"] = (_11 = (_10 = paymentIntent.transfer_data) === null || _10 === void 0 ? void 0 : _10.destination) !== null && _11 !== void 0 ? _11 : "";
770
- update["currency"] = paymentIntent.currency;
771
- update["clientSecret"] = paymentIntent.client_secret;
772
- update["createdTime"] = new Date(paymentIntent.created * 1000);
773
- update["updatedTime"] = new Date();
774
- update["emailFrom"] = emailFrom;
775
- update["emailTo"] = email;
776
- update["emailTitle"] = emailTitle;
777
- update["emailContent"] = emailContent;
778
- update["locale"] = locale;
779
- yield firestoreInstance.doc(`${stripeUserPath}/${userId}/${stripePurchasePath}/${orderId}`).set(update, {
780
- merge: true,
781
- });
782
- return {
783
- purchaseId: paymentIntent.id,
784
- };
785
- }
784
+ }
785
+ case "confirm_purchase": {
786
+ const userId = query.data.userId;
787
+ const orderId = query.data.orderId;
788
+ const successUrl = query.data.successUrl;
789
+ const failureUrl = query.data.failureUrl;
790
+ let returnUrl = query.data.returnUrl;
791
+ const online = query.data.online == "true";
792
+ if (!orderId) {
793
+ throw new functions.https.HttpsError("invalid-argument", "The order id is empty.");
786
794
  }
787
- case "confirm_purchase": {
788
- const userId = query.data.userId;
789
- const orderId = query.data.orderId;
790
- const successUrl = query.data.successUrl;
791
- const failureUrl = query.data.failureUrl;
792
- let returnUrl = query.data.returnUrl;
793
- const online = query.data.online == "true";
794
- if (!orderId) {
795
- throw new functions.https.HttpsError("invalid-argument", "The order id is empty.");
796
- }
797
- if (!userId) {
798
- throw new functions.https.HttpsError("invalid-argument", "The user id is empty.");
799
- }
800
- if (!online) {
801
- returnUrl = returnUrl + "?token=" + JSON.stringify({
802
- userId: userId,
803
- orderId: orderId,
804
- successUrl: successUrl,
805
- failureUrl: failureUrl,
806
- }).encrypt({
807
- key: apiKey.slice(0, 32),
808
- ivKey: apiKey.slice(-16),
809
- });
810
- }
811
- const doc = yield firestoreInstance.doc(`${stripeUserPath}/${userId}/${stripePurchasePath}/${orderId}`).get();
812
- const data = doc.data();
813
- if (!data || !data["purchaseId"]) {
814
- throw new functions.https.HttpsError("not-found", "The purchase data is invalid.");
815
- }
816
- if (data["error"]) {
817
- throw new functions.https.HttpsError("aborted", "The purchase data has some errors");
818
- }
819
- if (data["cancel"]) {
820
- throw new functions.https.HttpsError("cancelled", "The purchase data is already canceled.");
821
- }
822
- if (data["confirm"]) {
823
- if (data["verify"]) {
824
- throw new functions.https.HttpsError("ok", "The purchase data is already confirmed.");
825
- }
826
- try {
827
- const paymentIntent = yield stripeClient.paymentIntents.retrieve(data["purchaseId"]);
828
- const nextActionUrl = (_14 = (_13 = (_12 = paymentIntent.next_action) === null || _12 === void 0 ? void 0 : _12.redirect_to_url) === null || _13 === void 0 ? void 0 : _13.url) !== null && _14 !== void 0 ? _14 : "";
829
- const update = {};
830
- if (nextActionUrl) {
831
- if (!online) {
832
- if (data["emailFrom"] && data["emailTo"] && data["emailTitle"] && data["emailContent"]) {
833
- switch (stripeEmailProvider) {
834
- case "gmail": {
835
- yield gmail.send({
836
- from: data["emailFrom"],
837
- to: data["emailTo"],
838
- title: data["emailTitle"],
839
- content: data["emailContent"].replace("{url}", nextActionUrl),
840
- });
841
- break;
842
- }
843
- case "sendgrid": {
844
- yield sendgrid.send({
845
- from: data["emailFrom"],
846
- to: data["emailTo"],
847
- title: data["emailTitle"],
848
- content: data["emailContent"].replace("{url}", nextActionUrl),
849
- });
850
- break;
851
- }
852
- }
853
- }
854
- else {
855
- update["error"] = true;
856
- update["errorMessage"] = "3D Secure authentication is required, but the user is offline and no email settings have been configured.";
857
- }
858
- }
859
- update["nextAction"] = {
860
- url: nextActionUrl,
861
- returnUrl: (_17 = (_16 = (_15 = paymentIntent.next_action) === null || _15 === void 0 ? void 0 : _15.redirect_to_url) === null || _16 === void 0 ? void 0 : _16.return_url) !== null && _17 !== void 0 ? _17 : "",
862
- };
863
- yield doc.ref.set(update, {
864
- merge: true,
865
- });
866
- return {
867
- url: online ? nextActionUrl : "",
868
- returnUrl: online ? (_20 = (_19 = (_18 = paymentIntent.next_action) === null || _18 === void 0 ? void 0 : _18.redirect_to_url) === null || _19 === void 0 ? void 0 : _19.return_url) !== null && _20 !== void 0 ? _20 : "" : "",
869
- purchaseId: data["purchaseId"],
870
- };
871
- }
872
- else {
873
- update["verify"] = true;
874
- update["nextAction"] = admin.firestore.FieldValue.delete();
875
- yield doc.ref.set(update, {
876
- merge: true,
877
- });
878
- return {
879
- url: "",
880
- returnUrl: "",
881
- purchaseId: data["purchaseId"],
882
- };
883
- }
884
- }
885
- catch (err) {
886
- const update = {};
887
- update["error"] = true;
888
- update["errorMessage"] = "The Purchase confirmation failed. Please replace the billing information and Refresh.";
889
- yield doc.ref.set(update, {
890
- merge: true,
891
- });
892
- throw err;
893
- }
795
+ if (!userId) {
796
+ throw new functions.https.HttpsError("invalid-argument", "The user id is empty.");
797
+ }
798
+ if (!online) {
799
+ returnUrl = returnUrl + "?token=" + JSON.stringify({
800
+ userId: userId,
801
+ orderId: orderId,
802
+ successUrl: successUrl,
803
+ failureUrl: failureUrl,
804
+ }).encrypt({
805
+ key: apiKey.slice(0, 32),
806
+ ivKey: apiKey.slice(-16),
807
+ });
808
+ }
809
+ const doc = yield firestoreInstance.doc(`${stripeUserPath}/${userId}/${stripePurchasePath}/${orderId}`).get();
810
+ const data = doc.data();
811
+ if (!data || !data["purchaseId"]) {
812
+ throw new functions.https.HttpsError("not-found", "The purchase data is invalid.");
813
+ }
814
+ if (data["error"]) {
815
+ throw new functions.https.HttpsError("aborted", "The purchase data has some errors");
816
+ }
817
+ if (data["cancel"]) {
818
+ throw new functions.https.HttpsError("cancelled", "The purchase data is already canceled.");
819
+ }
820
+ if (data["confirm"]) {
821
+ if (data["verify"]) {
822
+ throw new functions.https.HttpsError("ok", "The purchase data is already confirmed.");
894
823
  }
895
- else {
896
- try {
897
- const paymentIntent = yield stripeClient.paymentIntents.confirm(data["purchaseId"], {
898
- return_url: returnUrl,
899
- });
900
- const nextActionUrl = (_23 = (_22 = (_21 = paymentIntent.next_action) === null || _21 === void 0 ? void 0 : _21.redirect_to_url) === null || _22 === void 0 ? void 0 : _22.url) !== null && _23 !== void 0 ? _23 : "";
901
- const update = {};
902
- if (nextActionUrl && !online) {
824
+ try {
825
+ const paymentIntent = yield stripeClient.paymentIntents.retrieve(data["purchaseId"]);
826
+ const nextActionUrl = (_13 = (_12 = (_11 = paymentIntent.next_action) === null || _11 === void 0 ? void 0 : _11.redirect_to_url) === null || _12 === void 0 ? void 0 : _12.url) !== null && _13 !== void 0 ? _13 : "";
827
+ const update = {};
828
+ if (nextActionUrl) {
829
+ if (!online) {
903
830
  if (data["emailFrom"] && data["emailTo"] && data["emailTitle"] && data["emailContent"]) {
904
831
  switch (stripeEmailProvider) {
905
832
  case "gmail": {
@@ -929,288 +856,358 @@ module.exports = (regions, options, data) => {
929
856
  }
930
857
  update["nextAction"] = {
931
858
  url: nextActionUrl,
932
- returnUrl: (_26 = (_25 = (_24 = paymentIntent.next_action) === null || _24 === void 0 ? void 0 : _24.redirect_to_url) === null || _25 === void 0 ? void 0 : _25.return_url) !== null && _26 !== void 0 ? _26 : "",
859
+ returnUrl: (_16 = (_15 = (_14 = paymentIntent.next_action) === null || _14 === void 0 ? void 0 : _14.redirect_to_url) === null || _15 === void 0 ? void 0 : _15.return_url) !== null && _16 !== void 0 ? _16 : "",
933
860
  };
934
861
  yield doc.ref.set(update, {
935
862
  merge: true,
936
863
  });
937
864
  return {
938
865
  url: online ? nextActionUrl : "",
939
- returnUrl: online ? (_29 = (_28 = (_27 = paymentIntent.next_action) === null || _27 === void 0 ? void 0 : _27.redirect_to_url) === null || _28 === void 0 ? void 0 : _28.return_url) !== null && _29 !== void 0 ? _29 : "" : "",
866
+ returnUrl: online ? (_19 = (_18 = (_17 = paymentIntent.next_action) === null || _17 === void 0 ? void 0 : _17.redirect_to_url) === null || _18 === void 0 ? void 0 : _18.return_url) !== null && _19 !== void 0 ? _19 : "" : "",
940
867
  purchaseId: data["purchaseId"],
941
868
  };
942
869
  }
943
- catch (err) {
944
- const update = {};
945
- update["error"] = true;
946
- update["errorMessage"] = "The Purchase confirmation failed. Please replace the billing information and Refresh.";
870
+ else {
871
+ update["verify"] = true;
872
+ update["nextAction"] = admin.firestore.FieldValue.delete();
947
873
  yield doc.ref.set(update, {
948
874
  merge: true,
949
875
  });
950
- throw err;
951
- }
952
- }
953
- }
954
- case "capture_purchase": {
955
- const userId = query.data.userId;
956
- const orderId = query.data.orderId;
957
- const amount = parseFloat((_30 = query.data.amount) !== null && _30 !== void 0 ? _30 : 0.0);
958
- if (!orderId) {
959
- throw new functions.https.HttpsError("invalid-argument", "The order id is empty.");
960
- }
961
- if (!userId) {
962
- throw new functions.https.HttpsError("invalid-argument", "The user id is empty.");
963
- }
964
- const doc = yield firestoreInstance.doc(`${stripeUserPath}/${userId}/${stripePurchasePath}/${orderId}`).get();
965
- const data = doc.data();
966
- if (!data || !data["purchaseId"]) {
967
- throw new functions.https.HttpsError("not-found", "The purchase data is invalid.");
968
- }
969
- if (data["error"]) {
970
- throw new functions.https.HttpsError("aborted", "The purchase data has some errors");
971
- }
972
- if (data["cancel"]) {
973
- throw new functions.https.HttpsError("cancelled", "This purchase data has already been cancelled.");
974
- }
975
- if (!data["confirm"] || !data["verify"]) {
976
- throw new functions.https.HttpsError("failed-precondition", "The purchase data is not confirmed.");
977
- }
978
- if (data["capture"]) {
979
- throw new functions.https.HttpsError("ok", "The purchase data is already captured.");
980
- }
981
- if (data["amount"] < amount) {
982
- throw new functions.https.HttpsError("invalid-argument", "You cannot capture an amount higher than the billing amount already saved.");
983
- }
984
- try {
985
- const paymentIntent = yield (amount > 0 ? stripeClient.paymentIntents.capture(data["purchaseId"], {
986
- amount_to_capture: amount,
987
- }) : stripeClient.paymentIntents.capture(data["purchaseId"]));
988
- if (paymentIntent.status !== "succeeded") {
989
- throw new functions.https.HttpsError("aborted", "The Payment capture failed.");
876
+ return {
877
+ url: "",
878
+ returnUrl: "",
879
+ purchaseId: data["purchaseId"],
880
+ };
990
881
  }
991
- return {
992
- purchaseId: data["purchaseId"],
993
- };
994
882
  }
995
883
  catch (err) {
996
884
  const update = {};
997
885
  update["error"] = true;
998
- update["errorMessage"] = "The Purchase capture failed. Please replace the billing information and Refresh.";
886
+ update["errorMessage"] = "The Purchase confirmation failed. Please replace the billing information and Refresh.";
999
887
  yield doc.ref.set(update, {
1000
888
  merge: true,
1001
889
  });
1002
890
  throw err;
1003
891
  }
1004
892
  }
1005
- case "refresh_purchase": {
1006
- const orderId = query.data.orderId;
1007
- const userId = query.data.userId;
1008
- if (!orderId) {
1009
- throw new functions.https.HttpsError("invalid-argument", "The order id is empty.");
1010
- }
1011
- if (!userId) {
1012
- throw new functions.https.HttpsError("invalid-argument", "The user id is empty.");
1013
- }
1014
- const doc = yield firestoreInstance.doc(`${stripeUserPath}/${userId}/${stripePurchasePath}/${orderId}`).get();
1015
- const data = doc.data();
1016
- if (!data || !data["purchaseId"]) {
1017
- throw new functions.https.HttpsError("not-found", "The purchase data is invalid.");
1018
- }
1019
- if (data["success"]) {
1020
- throw new functions.https.HttpsError("already-exists", "The payment has already been succeed.");
1021
- }
1022
- if (!data["error"]) {
893
+ else {
894
+ try {
895
+ const paymentIntent = yield stripeClient.paymentIntents.confirm(data["purchaseId"], {
896
+ return_url: returnUrl,
897
+ });
898
+ const nextActionUrl = (_22 = (_21 = (_20 = paymentIntent.next_action) === null || _20 === void 0 ? void 0 : _20.redirect_to_url) === null || _21 === void 0 ? void 0 : _21.url) !== null && _22 !== void 0 ? _22 : "";
899
+ const update = {};
900
+ if (nextActionUrl && !online) {
901
+ if (data["emailFrom"] && data["emailTo"] && data["emailTitle"] && data["emailContent"]) {
902
+ switch (stripeEmailProvider) {
903
+ case "gmail": {
904
+ yield gmail.send({
905
+ from: data["emailFrom"],
906
+ to: data["emailTo"],
907
+ title: data["emailTitle"],
908
+ content: data["emailContent"].replace("{url}", nextActionUrl),
909
+ });
910
+ break;
911
+ }
912
+ case "sendgrid": {
913
+ yield sendgrid.send({
914
+ from: data["emailFrom"],
915
+ to: data["emailTo"],
916
+ title: data["emailTitle"],
917
+ content: data["emailContent"].replace("{url}", nextActionUrl),
918
+ });
919
+ break;
920
+ }
921
+ }
922
+ }
923
+ else {
924
+ update["error"] = true;
925
+ update["errorMessage"] = "3D Secure authentication is required, but the user is offline and no email settings have been configured.";
926
+ }
927
+ }
928
+ update["nextAction"] = {
929
+ url: nextActionUrl,
930
+ returnUrl: (_25 = (_24 = (_23 = paymentIntent.next_action) === null || _23 === void 0 ? void 0 : _23.redirect_to_url) === null || _24 === void 0 ? void 0 : _24.return_url) !== null && _25 !== void 0 ? _25 : "",
931
+ };
932
+ yield doc.ref.set(update, {
933
+ merge: true,
934
+ });
1023
935
  return {
1024
- success: true,
936
+ url: online ? nextActionUrl : "",
937
+ returnUrl: online ? (_28 = (_27 = (_26 = paymentIntent.next_action) === null || _26 === void 0 ? void 0 : _26.redirect_to_url) === null || _27 === void 0 ? void 0 : _27.return_url) !== null && _28 !== void 0 ? _28 : "" : "",
938
+ purchaseId: data["purchaseId"],
1025
939
  };
1026
940
  }
1027
- const userDoc = yield firestoreInstance.doc(`${stripeUserPath}/${userId}`).get();
1028
- const userData = userDoc.data();
1029
- if (!userData || !userData["customer"]) {
1030
- throw new functions.https.HttpsError("not-found", "The customer id is not found.");
1031
- }
1032
- let defaultPayment = userData["defaultPayment"];
1033
- if (!defaultPayment) {
1034
- const customer = yield stripeClient.customers.retrieve(userData["customer"]);
1035
- defaultPayment = customer.invoice_settings.default_payment_method;
1036
- if (!defaultPayment) {
1037
- const payments = yield firestoreInstance.collection(`${stripeUserPath}/${userId}/${stripePaymentPath}`).get();
1038
- if (payments.size <= 0) {
1039
- throw new functions.https.HttpsError("not-found", "The payment method is not found.");
1040
- }
1041
- defaultPayment = payments.docs[0].data()["id"];
1042
- }
941
+ catch (err) {
1043
942
  const update = {};
1044
- update["defaultPayment"] = defaultPayment;
1045
- yield userDoc.ref.set(update, {
943
+ update["error"] = true;
944
+ update["errorMessage"] = "The Purchase confirmation failed. Please replace the billing information and Refresh.";
945
+ yield doc.ref.set(update, {
1046
946
  merge: true,
1047
947
  });
948
+ throw err;
1048
949
  }
1049
- if (defaultPayment === data["payment_method"]) {
1050
- throw new functions.https.HttpsError("failed-precondition", "There was no change in the Payment method.");
950
+ }
951
+ }
952
+ case "capture_purchase": {
953
+ const userId = query.data.userId;
954
+ const orderId = query.data.orderId;
955
+ const amount = parseFloat((_29 = query.data.amount) !== null && _29 !== void 0 ? _29 : 0.0);
956
+ if (!orderId) {
957
+ throw new functions.https.HttpsError("invalid-argument", "The order id is empty.");
958
+ }
959
+ if (!userId) {
960
+ throw new functions.https.HttpsError("invalid-argument", "The user id is empty.");
961
+ }
962
+ const doc = yield firestoreInstance.doc(`${stripeUserPath}/${userId}/${stripePurchasePath}/${orderId}`).get();
963
+ const data = doc.data();
964
+ if (!data || !data["purchaseId"]) {
965
+ throw new functions.https.HttpsError("not-found", "The purchase data is invalid.");
966
+ }
967
+ if (data["error"]) {
968
+ throw new functions.https.HttpsError("aborted", "The purchase data has some errors");
969
+ }
970
+ if (data["cancel"]) {
971
+ throw new functions.https.HttpsError("cancelled", "This purchase data has already been cancelled.");
972
+ }
973
+ if (!data["confirm"] || !data["verify"]) {
974
+ throw new functions.https.HttpsError("failed-precondition", "The purchase data is not confirmed.");
975
+ }
976
+ if (data["capture"]) {
977
+ throw new functions.https.HttpsError("ok", "The purchase data is already captured.");
978
+ }
979
+ if (data["amount"] < amount) {
980
+ throw new functions.https.HttpsError("invalid-argument", "You cannot capture an amount higher than the billing amount already saved.");
981
+ }
982
+ try {
983
+ const paymentIntent = yield (amount > 0 ? stripeClient.paymentIntents.capture(data["purchaseId"], {
984
+ amount_to_capture: amount,
985
+ }) : stripeClient.paymentIntents.capture(data["purchaseId"]));
986
+ if (paymentIntent.status !== "succeeded") {
987
+ throw new functions.https.HttpsError("aborted", "The Payment capture failed.");
1051
988
  }
1052
- yield stripeClient.paymentIntents.update(data["purchaseId"], {
1053
- payment_method: defaultPayment,
1054
- });
989
+ return {
990
+ purchaseId: data["purchaseId"],
991
+ };
992
+ }
993
+ catch (err) {
1055
994
  const update = {};
1056
- update["paymentMethodId"] = defaultPayment;
1057
- update["error"] = admin.firestore.FieldValue.delete();
1058
- update["errorMessage"] = admin.firestore.FieldValue.delete();
995
+ update["error"] = true;
996
+ update["errorMessage"] = "The Purchase capture failed. Please replace the billing information and Refresh.";
1059
997
  yield doc.ref.set(update, {
1060
998
  merge: true,
1061
999
  });
1000
+ throw err;
1001
+ }
1002
+ }
1003
+ case "refresh_purchase": {
1004
+ const orderId = query.data.orderId;
1005
+ const userId = query.data.userId;
1006
+ if (!orderId) {
1007
+ throw new functions.https.HttpsError("invalid-argument", "The order id is empty.");
1008
+ }
1009
+ if (!userId) {
1010
+ throw new functions.https.HttpsError("invalid-argument", "The user id is empty.");
1011
+ }
1012
+ const doc = yield firestoreInstance.doc(`${stripeUserPath}/${userId}/${stripePurchasePath}/${orderId}`).get();
1013
+ const data = doc.data();
1014
+ if (!data || !data["purchaseId"]) {
1015
+ throw new functions.https.HttpsError("not-found", "The purchase data is invalid.");
1016
+ }
1017
+ if (data["success"]) {
1018
+ throw new functions.https.HttpsError("already-exists", "The payment has already been succeed.");
1019
+ }
1020
+ if (!data["error"]) {
1062
1021
  return {
1063
1022
  success: true,
1064
1023
  };
1065
1024
  }
1066
- case "cancel_purchase": {
1067
- const orderId = query.data.orderId;
1068
- const userId = query.data.userId;
1069
- if (!orderId) {
1070
- throw new functions.https.HttpsError("invalid-argument", "The order id is empty.");
1071
- }
1072
- if (!userId) {
1073
- throw new functions.https.HttpsError("invalid-argument", "The user id is empty.");
1074
- }
1075
- const doc = yield firestoreInstance.doc(`${stripeUserPath}/${userId}/${stripePurchasePath}/${orderId}`).get();
1076
- const data = doc.data();
1077
- if (!data || !data["purchaseId"]) {
1078
- throw new functions.https.HttpsError("not-found", "The purchase data is invalid.");
1079
- }
1080
- if (data["cancel"]) {
1081
- throw new functions.https.HttpsError("ok", "The purchase data is already canceled.");
1082
- }
1083
- if (data["capture"] || data["success"]) {
1084
- throw new functions.https.HttpsError("failed-precondition", "The payment has already been completed.");
1025
+ const userDoc = yield firestoreInstance.doc(`${stripeUserPath}/${userId}`).get();
1026
+ const userData = userDoc.data();
1027
+ if (!userData || !userData["customer"]) {
1028
+ throw new functions.https.HttpsError("not-found", "The customer id is not found.");
1029
+ }
1030
+ let defaultPayment = userData["defaultPayment"];
1031
+ if (!defaultPayment) {
1032
+ const customer = yield stripeClient.customers.retrieve(userData["customer"]);
1033
+ defaultPayment = customer.invoice_settings.default_payment_method;
1034
+ if (!defaultPayment) {
1035
+ const payments = yield firestoreInstance.collection(`${stripeUserPath}/${userId}/${stripePaymentPath}`).get();
1036
+ if (payments.size <= 0) {
1037
+ throw new functions.https.HttpsError("not-found", "The payment method is not found.");
1038
+ }
1039
+ defaultPayment = payments.docs[0].data()["id"];
1085
1040
  }
1086
- yield stripeClient.paymentIntents.cancel(data["purchaseId"]);
1087
1041
  const update = {};
1088
- update["cancel"] = true;
1089
- update["error"] = admin.firestore.FieldValue.delete();
1090
- update["errorMessage"] = admin.firestore.FieldValue.delete();
1091
- yield doc.ref.set(update, {
1042
+ update["defaultPayment"] = defaultPayment;
1043
+ yield userDoc.ref.set(update, {
1092
1044
  merge: true,
1093
1045
  });
1094
- return {
1095
- success: true,
1096
- };
1097
1046
  }
1098
- case "refund_purchase": {
1099
- const orderId = query.data.orderId;
1100
- const userId = query.data.userId;
1101
- const amount = parseFloat((_31 = query.data.amount) !== null && _31 !== void 0 ? _31 : 0.0);
1102
- if (!orderId) {
1103
- throw new functions.https.HttpsError("invalid-argument", "The order id is empty.");
1104
- }
1105
- if (!userId) {
1106
- throw new functions.https.HttpsError("invalid-argument", "The user id is empty.");
1107
- }
1108
- const doc = yield firestoreInstance.doc(`${stripeUserPath}/${userId}/${stripePurchasePath}/${orderId}`).get();
1109
- const data = doc.data();
1110
- if (!data || !data["purchaseId"]) {
1111
- throw new functions.https.HttpsError("not-found", "The purchase data is invalid.");
1112
- }
1113
- if (!data["capture"] || !data["success"]) {
1114
- throw new functions.https.HttpsError("failed-precondition", "The payment is not yet in your jurisdiction.");
1115
- }
1116
- if (data["amount"] < amount) {
1117
- throw new functions.https.HttpsError("invalid-argument", "The amount to be refunded exceeds the original amount.");
1118
- }
1119
- try {
1120
- if (amount > 0) {
1121
- yield stripeClient.refunds.create({
1122
- payment_intent: data["purchaseId"],
1123
- amount: amount,
1124
- });
1125
- }
1126
- else {
1127
- yield stripeClient.refunds.create({
1128
- payment_intent: data["purchaseId"],
1129
- });
1130
- }
1131
- const update = {};
1132
- update["refund"] = true;
1133
- update["cancel"] = true;
1134
- yield doc.ref.set(update, {
1135
- merge: true,
1047
+ if (defaultPayment === data["payment_method"]) {
1048
+ throw new functions.https.HttpsError("failed-precondition", "There was no change in the Payment method.");
1049
+ }
1050
+ yield stripeClient.paymentIntents.update(data["purchaseId"], {
1051
+ payment_method: defaultPayment,
1052
+ });
1053
+ const update = {};
1054
+ update["paymentMethodId"] = defaultPayment;
1055
+ update["error"] = admin.firestore.FieldValue.delete();
1056
+ update["errorMessage"] = admin.firestore.FieldValue.delete();
1057
+ yield doc.ref.set(update, {
1058
+ merge: true,
1059
+ });
1060
+ return {
1061
+ success: true,
1062
+ };
1063
+ }
1064
+ case "cancel_purchase": {
1065
+ const orderId = query.data.orderId;
1066
+ const userId = query.data.userId;
1067
+ if (!orderId) {
1068
+ throw new functions.https.HttpsError("invalid-argument", "The order id is empty.");
1069
+ }
1070
+ if (!userId) {
1071
+ throw new functions.https.HttpsError("invalid-argument", "The user id is empty.");
1072
+ }
1073
+ const doc = yield firestoreInstance.doc(`${stripeUserPath}/${userId}/${stripePurchasePath}/${orderId}`).get();
1074
+ const data = doc.data();
1075
+ if (!data || !data["purchaseId"]) {
1076
+ throw new functions.https.HttpsError("not-found", "The purchase data is invalid.");
1077
+ }
1078
+ if (data["cancel"]) {
1079
+ throw new functions.https.HttpsError("ok", "The purchase data is already canceled.");
1080
+ }
1081
+ if (data["capture"] || data["success"]) {
1082
+ throw new functions.https.HttpsError("failed-precondition", "The payment has already been completed.");
1083
+ }
1084
+ yield stripeClient.paymentIntents.cancel(data["purchaseId"]);
1085
+ const update = {};
1086
+ update["cancel"] = true;
1087
+ update["error"] = admin.firestore.FieldValue.delete();
1088
+ update["errorMessage"] = admin.firestore.FieldValue.delete();
1089
+ yield doc.ref.set(update, {
1090
+ merge: true,
1091
+ });
1092
+ return {
1093
+ success: true,
1094
+ };
1095
+ }
1096
+ case "refund_purchase": {
1097
+ const orderId = query.data.orderId;
1098
+ const userId = query.data.userId;
1099
+ const amount = parseFloat((_30 = query.data.amount) !== null && _30 !== void 0 ? _30 : 0.0);
1100
+ if (!orderId) {
1101
+ throw new functions.https.HttpsError("invalid-argument", "The order id is empty.");
1102
+ }
1103
+ if (!userId) {
1104
+ throw new functions.https.HttpsError("invalid-argument", "The user id is empty.");
1105
+ }
1106
+ const doc = yield firestoreInstance.doc(`${stripeUserPath}/${userId}/${stripePurchasePath}/${orderId}`).get();
1107
+ const data = doc.data();
1108
+ if (!data || !data["purchaseId"]) {
1109
+ throw new functions.https.HttpsError("not-found", "The purchase data is invalid.");
1110
+ }
1111
+ if (!data["capture"] || !data["success"]) {
1112
+ throw new functions.https.HttpsError("failed-precondition", "The payment is not yet in your jurisdiction.");
1113
+ }
1114
+ if (data["amount"] < amount) {
1115
+ throw new functions.https.HttpsError("invalid-argument", "The amount to be refunded exceeds the original amount.");
1116
+ }
1117
+ try {
1118
+ if (amount > 0) {
1119
+ yield stripeClient.refunds.create({
1120
+ payment_intent: data["purchaseId"],
1121
+ amount: amount,
1136
1122
  });
1137
- return {
1138
- success: true,
1139
- };
1140
1123
  }
1141
- catch (err) {
1142
- const update = {};
1143
- update["error"] = true;
1144
- update["errorMessage"] = "The Purchase confirmation failed. Please replace the billing information and Refresh.";
1145
- yield doc.ref.set(update, {
1146
- merge: true,
1124
+ else {
1125
+ yield stripeClient.refunds.create({
1126
+ payment_intent: data["purchaseId"],
1147
1127
  });
1148
- throw err;
1149
1128
  }
1150
- }
1151
- case "create_subscription": {
1152
- const productId = query.data.productId;
1153
- const orderId = query.data.orderId;
1154
- const userId = query.data.userId;
1155
- const count = (_32 = query.data.count) !== null && _32 !== void 0 ? _32 : 1;
1156
- const successUrl = query.data.successUrl;
1157
- const cancelUrl = query.data.cancelUrl;
1158
- if (!orderId) {
1159
- throw new functions.https.HttpsError("invalid-argument", "The order id is empty.");
1160
- }
1161
- if (!userId) {
1162
- throw new functions.https.HttpsError("invalid-argument", "The user id is empty.");
1163
- }
1164
- if (!productId) {
1165
- throw new functions.https.HttpsError("invalid-argument", "The product id is empty.");
1166
- }
1167
- const res = yield stripeClient.checkout.sessions.create({
1168
- billing_address_collection: "auto",
1169
- subscription_data: {
1170
- metadata: {
1171
- "userId": userId,
1172
- "orderId": orderId,
1173
- },
1174
- },
1175
- line_items: [
1176
- {
1177
- price: productId,
1178
- quantity: count,
1179
- },
1180
- ],
1181
- mode: "subscription",
1182
- success_url: successUrl,
1183
- cancel_url: cancelUrl,
1129
+ const update = {};
1130
+ update["refund"] = true;
1131
+ update["cancel"] = true;
1132
+ yield doc.ref.set(update, {
1133
+ merge: true,
1184
1134
  });
1185
1135
  return {
1186
- endpoint: res["url"],
1136
+ success: true,
1187
1137
  };
1188
1138
  }
1189
- case "delete_subscription": {
1190
- const orderId = query.data.orderId;
1191
- if (!orderId) {
1192
- throw new functions.https.HttpsError("invalid-argument", "The order id is empty.");
1193
- }
1194
- const doc = yield firestoreInstance.doc(`${stripePurchasePath}/${orderId}`).get();
1195
- if (!doc.exists || !doc.get("subscription")) {
1196
- throw new functions.https.HttpsError("not-found", "The orderId data is not found");
1197
- }
1198
- const res = yield stripeClient.subscriptions.update(doc.get("subscription"), {
1199
- cancel_at_period_end: true,
1139
+ catch (err) {
1140
+ const update = {};
1141
+ update["error"] = true;
1142
+ update["errorMessage"] = "The Purchase confirmation failed. Please replace the billing information and Refresh.";
1143
+ yield doc.ref.set(update, {
1144
+ merge: true,
1200
1145
  });
1201
- return {
1202
- success: res["cancel_at_period_end"],
1203
- };
1146
+ throw err;
1204
1147
  }
1205
- default: {
1206
- throw new functions.https.HttpsError("not-found", "There is no mode:" + query.data.mode);
1148
+ }
1149
+ case "create_subscription": {
1150
+ const productId = query.data.productId;
1151
+ const orderId = query.data.orderId;
1152
+ const userId = query.data.userId;
1153
+ const count = (_31 = query.data.count) !== null && _31 !== void 0 ? _31 : 1;
1154
+ const successUrl = query.data.successUrl;
1155
+ const cancelUrl = query.data.cancelUrl;
1156
+ if (!orderId) {
1157
+ throw new functions.https.HttpsError("invalid-argument", "The order id is empty.");
1207
1158
  }
1159
+ if (!userId) {
1160
+ throw new functions.https.HttpsError("invalid-argument", "The user id is empty.");
1161
+ }
1162
+ if (!productId) {
1163
+ throw new functions.https.HttpsError("invalid-argument", "The product id is empty.");
1164
+ }
1165
+ const res = yield stripeClient.checkout.sessions.create({
1166
+ billing_address_collection: "auto",
1167
+ subscription_data: {
1168
+ metadata: {
1169
+ "userId": userId,
1170
+ "orderId": orderId,
1171
+ },
1172
+ },
1173
+ line_items: [
1174
+ {
1175
+ price: productId,
1176
+ quantity: count,
1177
+ },
1178
+ ],
1179
+ mode: "subscription",
1180
+ success_url: successUrl,
1181
+ cancel_url: cancelUrl,
1182
+ });
1183
+ return {
1184
+ endpoint: res["url"],
1185
+ };
1186
+ }
1187
+ case "delete_subscription": {
1188
+ const orderId = query.data.orderId;
1189
+ if (!orderId) {
1190
+ throw new functions.https.HttpsError("invalid-argument", "The order id is empty.");
1191
+ }
1192
+ const doc = yield firestoreInstance.doc(`${stripePurchasePath}/${orderId}`).get();
1193
+ if (!doc.exists || !doc.get("subscription")) {
1194
+ throw new functions.https.HttpsError("not-found", "The orderId data is not found");
1195
+ }
1196
+ const res = yield stripeClient.subscriptions.update(doc.get("subscription"), {
1197
+ cancel_at_period_end: true,
1198
+ });
1199
+ return {
1200
+ success: res["cancel_at_period_end"],
1201
+ };
1202
+ }
1203
+ default: {
1204
+ throw new functions.https.HttpsError("not-found", "There is no mode:" + query.data.mode);
1208
1205
  }
1209
1206
  }
1210
- catch (err) {
1211
- console.error(err);
1212
- throw err;
1213
- }
1214
- }));
1215
- };
1207
+ }
1208
+ catch (err) {
1209
+ console.error(err);
1210
+ throw err;
1211
+ }
1212
+ }));
1216
1213
  //# sourceMappingURL=stripe.js.map