vonpay-medusa 1.0.2 → 1.0.4

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.
@@ -134,6 +134,10 @@ const REASON_COPY = {
134
134
  label: "Late offer charge — refund failed",
135
135
  what: "The buyer was charged for an offer whose item was NOT added to the order — the bank approved it after the offer had ended, the item could not be added, or an earlier declined attempt was approved after all — so the plugin tried to refund that charge in full, but the refund did not go through (refused, or not settled within 48 hours). Refund the payment in Vonpay by the order id. Do not add the item."
136
136
  },
137
+ upsell_refund_unclear: {
138
+ label: "Late offer charge — refund unclear",
139
+ what: "The buyer was charged for an offer whose item was NOT added to the order, and the plugin's automatic refund got an unclear answer: Vonpay reported an error, then recorded that refund as failed, but the money may have gone back anyway. The plugin will not send another refund. First check the payment in Vonpay by the order id: refund it there ONLY if no refund went through. Do not add the item."
140
+ },
137
141
  upsell_refund_pending: {
138
142
  label: "Late offer charge — refund in progress",
139
143
  what: "The buyer's bank approved an offer after the offer had ended, so nothing was added and the plugin is refunding the charge in full. It keeps retrying. If this row stays for a day, refund the payment in Vonpay by the order id."
@@ -1164,17 +1168,17 @@ const routeModule = {
1164
1168
  const menuItemModule = {
1165
1169
  menuItems: [
1166
1170
  {
1167
- label: config.label,
1168
- icon: config.icon,
1169
- path: "/vonpay-subscriptions",
1171
+ label: config$1.label,
1172
+ icon: config$1.icon,
1173
+ path: "/vonpay-holds",
1170
1174
  nested: "/orders",
1171
1175
  rank: void 0,
1172
1176
  translationNs: void 0
1173
1177
  },
1174
1178
  {
1175
- label: config$1.label,
1176
- icon: config$1.icon,
1177
- path: "/vonpay-holds",
1179
+ label: config.label,
1180
+ icon: config.icon,
1181
+ path: "/vonpay-subscriptions",
1178
1182
  nested: "/orders",
1179
1183
  rank: void 0,
1180
1184
  translationNs: void 0
@@ -131,6 +131,10 @@ const REASON_COPY = {
131
131
  label: "Late offer charge — refund failed",
132
132
  what: "The buyer was charged for an offer whose item was NOT added to the order — the bank approved it after the offer had ended, the item could not be added, or an earlier declined attempt was approved after all — so the plugin tried to refund that charge in full, but the refund did not go through (refused, or not settled within 48 hours). Refund the payment in Vonpay by the order id. Do not add the item."
133
133
  },
134
+ upsell_refund_unclear: {
135
+ label: "Late offer charge — refund unclear",
136
+ what: "The buyer was charged for an offer whose item was NOT added to the order, and the plugin's automatic refund got an unclear answer: Vonpay reported an error, then recorded that refund as failed, but the money may have gone back anyway. The plugin will not send another refund. First check the payment in Vonpay by the order id: refund it there ONLY if no refund went through. Do not add the item."
137
+ },
134
138
  upsell_refund_pending: {
135
139
  label: "Late offer charge — refund in progress",
136
140
  what: "The buyer's bank approved an offer after the offer had ended, so nothing was added and the plugin is refunding the charge in full. It keeps retrying. If this row stays for a day, refund the payment in Vonpay by the order id."
@@ -1161,17 +1165,17 @@ const routeModule = {
1161
1165
  const menuItemModule = {
1162
1166
  menuItems: [
1163
1167
  {
1164
- label: config.label,
1165
- icon: config.icon,
1166
- path: "/vonpay-subscriptions",
1168
+ label: config$1.label,
1169
+ icon: config$1.icon,
1170
+ path: "/vonpay-holds",
1167
1171
  nested: "/orders",
1168
1172
  rank: void 0,
1169
1173
  translationNs: void 0
1170
1174
  },
1171
1175
  {
1172
- label: config$1.label,
1173
- icon: config$1.icon,
1174
- path: "/vonpay-holds",
1176
+ label: config.label,
1177
+ icon: config.icon,
1178
+ path: "/vonpay-subscriptions",
1175
1179
  nested: "/orders",
1176
1180
  rank: void 0,
1177
1181
  translationNs: void 0
@@ -180,7 +180,7 @@ function upsellsFromCollection(c, now = Date.now()) {
180
180
  vp_session_id: null,
181
181
  medusa_payment_session_id: null,
182
182
  payment_collection_id: c.id,
183
- reason: p.stuck === "amount_mismatch" ? "amount_mismatch" : "upsell_refund_failed",
183
+ reason: p.stuck === "amount_mismatch" ? "amount_mismatch" : p.stuck === "refund_unclear" ? "upsell_refund_unclear" : "upsell_refund_failed",
184
184
  source: "upsell",
185
185
  held_at: isoOrNull(p.at),
186
186
  order_id: medusaId(r.order_id),
@@ -952,6 +952,34 @@ class VonpayProviderService extends utils_1.AbstractPaymentProvider {
952
952
  if (!Number.isInteger(step) || step < 0)
953
953
  return "retry";
954
954
  const ids = { vp_payment_intent_id: pi, step };
955
+ const ours = `vpm_upsell_late_rf_${pi}`;
956
+ if (step > 0) {
957
+ try {
958
+ const list = await this.vonpay((c) => c.refunds.list({ paymentIntent: pi }, { limit: 100 }));
959
+ const rows = Array.isArray(list.data) ? list.data : [];
960
+ const done = typeof list.amountRefunded === "number" ? list.amountRefunded : NaN;
961
+ if (!Number.isFinite(done))
962
+ return "unread";
963
+ const mine = (r) => typeof r.idempotencyKey === "string" && r.idempotencyKey.startsWith(ours);
964
+ if (rows.some((r) => mine(r) && REFUND_CONFIRMED.has(String(r.status)))) {
965
+ this.log("info", "refund_transport", { ...ids, outcome: "already_refunded" });
966
+ return "refunded";
967
+ }
968
+ if (done > 0) {
969
+ this.log("warn", "refund_transport", { ...ids, outcome: "refunded_elsewhere" });
970
+ return "failed";
971
+ }
972
+ if (list.refundable === false) {
973
+ this.log("info", "refund_transport", { ...ids, outcome: "not_refundable_yet" });
974
+ return "unsettled";
975
+ }
976
+ }
977
+ catch (err) {
978
+ const reading = readRefundError(err);
979
+ this.log("warn", "refund_transport", { ...ids, outcome: "list_unreadable", ...errorFields(err) });
980
+ return reading.kind === "unknown" ? "unread" : "failed";
981
+ }
982
+ }
955
983
  const key = `vpm_upsell_late_rf_${pi}${step === 0 ? "" : `_s${step}`}`;
956
984
  try {
957
985
  const refund = await this.vonpay((c) => c.refunds.create({ paymentIntent: pi, amount: amountMinor, currency }, { idempotencyKey: key }));
@@ -962,7 +990,7 @@ class VonpayProviderService extends utils_1.AbstractPaymentProvider {
962
990
  if (REFUND_DEFINITELY_NOT_MADE.has(status)) {
963
991
  if (replay) {
964
992
  this.log("info", "refund_transport", { ...ids, outcome: "key_spent" });
965
- return "unsettled";
993
+ return "spent";
966
994
  }
967
995
  return "failed";
968
996
  }
@@ -1934,7 +1962,7 @@ class VonpayProviderService extends utils_1.AbstractPaymentProvider {
1934
1962
  return { sent: true, delivered: out.delivered === true, response_status: typeof out.responseStatus === "number" ? out.responseStatus : null };
1935
1963
  }
1936
1964
  catch (err) {
1937
- if (err instanceof checkout_node_1.VonPayError && err.status === 502)
1965
+ if (err instanceof checkout_node_1.VonPayError && (err.code === "webhook_test_delivery_failed" || err.status === 502))
1938
1966
  return { sent: true, delivered: false, response_status: null, unreachable: true };
1939
1967
  return { sent: false, why: "failed" };
1940
1968
  }
@@ -3403,7 +3431,8 @@ class VonpayProviderService extends utils_1.AbstractPaymentProvider {
3403
3431
  };
3404
3432
  let updated;
3405
3433
  try {
3406
- updated = await this.vonpay((c) => c.sessions.update(vpSessionId, { amount: amountMinor, currency }));
3434
+ const meta = await descriptor();
3435
+ updated = await this.vonpay((c) => c.sessions.update(vpSessionId, { amount: amountMinor, currency, ...(Object.keys(meta).length > 0 ? { metadata: meta } : {}) }));
3407
3436
  }
3408
3437
  catch (err) {
3409
3438
  if (!(err instanceof checkout_node_1.SessionNotModifiableError))
@@ -95,6 +95,7 @@ const HOLD_REASONS = [
95
95
  "upsell_hold_unsettled",
96
96
  "upsell_bank_check_open",
97
97
  "upsell_refund_failed",
98
+ "upsell_refund_unclear",
98
99
  "upsell_refund_pending",
99
100
  "upsell_refunded_late",
100
101
  ];
@@ -547,6 +548,7 @@ exports.UPSELL_HOLD_REASONS = new Set([
547
548
  "upsell_hold_not_released",
548
549
  "upsell_take_unconfirmed",
549
550
  "upsell_refund_failed",
551
+ "upsell_refund_unclear",
550
552
  ]);
551
553
  exports.SEALED_HOLD_SESSION = /^[A-Za-z0-9_-]{16}\.[A-Za-z0-9_-]{24,400}$/;
552
554
  exports.UPSELL_WALLET_ONLY_STATES = new Set(["tap", "authorized", "taking", "released"]);
@@ -611,6 +613,8 @@ function isUpsellRecord(v) {
611
613
  }
612
614
  if (r.rechecked === true && (wallet || !["declined", "skipped", "refunding", "refunded"].includes(r.state)))
613
615
  return false;
616
+ if (r.refund_unseen_step !== undefined && (r.state !== "refunding" || !Number.isInteger(r.refund_unseen_step) || r.refund_unseen_step < 0))
617
+ return false;
614
618
  if (r.prior_intents !== undefined) {
615
619
  const list = r.prior_intents;
616
620
  if (wallet || !Array.isArray(list) || list.length < 1 || list.length > exports.UPSELL_MAX_ATTEMPTS - 1)
@@ -621,7 +625,9 @@ function isUpsellRecord(v) {
621
625
  return false;
622
626
  if (typeof x.currency !== "string" || !CURRENCY.test(x.currency) || typeof x.at !== "string" || !Number.isFinite(Date.parse(x.at)))
623
627
  return false;
624
- if (!(x.stuck === undefined || x.stuck === "refund_failed" || x.stuck === "amount_mismatch"))
628
+ if (!(x.stuck === undefined || x.stuck === "refund_failed" || x.stuck === "amount_mismatch" || x.stuck === "refund_unclear"))
629
+ return false;
630
+ if (!(x.unseen_step === undefined || (Number.isInteger(x.unseen_step) && x.unseen_step >= 0)))
625
631
  return false;
626
632
  }
627
633
  }
@@ -503,7 +503,7 @@ async function latestOutcome(host, input, orderId, latest) {
503
503
  case "released":
504
504
  return { outcome: "released", why: latest.release_reason ?? "abandoned", retryable: (0, session_data_1.upsellMayRetry)(latest) };
505
505
  case "held":
506
- return latest.hold_reason === "upsell_refund_failed" ? { outcome: "refunded", amount_minor: latest.amount_minor, currency: latest.currency, pending: true } : { outcome: "unknown" };
506
+ return latest.hold_reason === "upsell_refund_failed" || latest.hold_reason === "upsell_refund_unclear" ? { outcome: "refunded", amount_minor: latest.amount_minor, currency: latest.currency, pending: true } : { outcome: "unknown" };
507
507
  case "stopped":
508
508
  return { outcome: "declined", retryable: false, decline_kind: "bank_check_unfinished" };
509
509
  case "refunding":
@@ -908,6 +908,8 @@ async function advance(ctx, from, next) {
908
908
  for (const k of Object.keys(value))
909
909
  if (value[k] === undefined)
910
910
  delete value[k];
911
+ if (value.state !== "refunding")
912
+ delete value.refund_unseen_step;
911
913
  if (!(0, session_data_1.isUpsellRecord)(value)) {
912
914
  ctx.host.log("error", "upsell_record_failed", { ...ctx.ids, state: next.state, why: "invalid_record", vp_payment_intent_id: from.vp_payment_intent_id });
913
915
  return undefined;
@@ -1019,24 +1021,53 @@ async function refundLate(ctx, r0, extra = {}) {
1019
1021
  await advance(ctx, r, { state: "held", hold_reason: "upsell_paid_unrecorded", decline_kind: null, rechecked: undefined });
1020
1022
  return { outcome: "unknown" };
1021
1023
  }
1022
- const res = await host.refundLate(r.vp_payment_intent_id, r.amount_minor, r.currency, lateRefundStep(host.now(), r0.state === "refunding" ? r0.at : null));
1024
+ if (!refundFitsLock(ctx)) {
1025
+ host.log("warn", "upsell_late_refund", { ...ids, result: "lock_time" });
1026
+ return answer(false);
1027
+ }
1028
+ const step = r.refund_unseen_step ?? lateRefundStep(host.now(), r0.state === "refunding" ? r0.at : null);
1029
+ const res = await host.refundLate(r.vp_payment_intent_id, r.amount_minor, r.currency, step);
1023
1030
  if (res === "refunded") {
1024
1031
  host.log("info", "upsell_late_refund", { ...ids, result: "refunded" });
1025
1032
  return answer(!!(await advance(ctx, r, { state: "refunded" })));
1026
1033
  }
1027
- const waitedOut = res === "unsettled" && r0.state === "refunding" && host.now() - Date.parse(r0.at) >= exports.UPSELL_UNSETTLED_REFUND_MS;
1034
+ if (res === "spent" && r.refund_unseen_step !== undefined) {
1035
+ host.log("error", "upsell_late_refund", { ...ids, result: "unclear", step });
1036
+ await advance(ctx, r, { state: "held", hold_reason: "upsell_refund_unclear", decline_kind: null, rechecked: undefined, refund_unseen_step: undefined });
1037
+ return answer(false);
1038
+ }
1039
+ const waiting = res === "unsettled" || res === "spent";
1040
+ const waitedOut = waiting && r0.state === "refunding" && host.now() - Date.parse(r0.at) >= exports.UPSELL_UNSETTLED_REFUND_MS;
1028
1041
  if (res === "failed" || waitedOut) {
1029
1042
  host.log("error", "upsell_late_refund", { ...ids, result: res === "failed" ? "failed" : "not_settled" });
1030
- await advance(ctx, r, { state: "held", hold_reason: "upsell_refund_failed", decline_kind: null, rechecked: undefined });
1043
+ await advance(ctx, r, { state: "held", hold_reason: r.refund_unseen_step !== undefined ? "upsell_refund_unclear" : "upsell_refund_failed", decline_kind: null, rechecked: undefined, refund_unseen_step: undefined });
1044
+ }
1045
+ else if (waiting) {
1046
+ host.log("info", "upsell_late_refund", { ...ids, result: "not_settled_yet" });
1047
+ }
1048
+ else if (res === "unread") {
1049
+ host.log(stuck ? "error" : "warn", "upsell_late_refund", { ...ids, result: "list_unreadable", step });
1031
1050
  }
1032
1051
  else {
1033
- if (res === "unsettled")
1034
- host.log("info", "upsell_late_refund", { ...ids, result: "not_settled_yet" });
1035
- else
1036
- host.log(stuck ? "error" : "warn", "upsell_late_refund", { ...ids, result: stuck ? "still_pending" : "retry" });
1052
+ if (r.refund_unseen_step === undefined)
1053
+ await writeSameAt(ctx, r, { refund_unseen_step: step });
1054
+ host.log(stuck ? "error" : "warn", "upsell_late_refund", { ...ids, result: stuck ? "still_pending" : "retry", step });
1037
1055
  }
1038
1056
  return answer(false);
1039
1057
  }
1058
+ function refundFitsLock(ctx) {
1059
+ const t = ctx.host.timing();
1060
+ return ctx.lockRemainingMs() >= 2 * t.vonpayMs + t.sendMarginMs;
1061
+ }
1062
+ async function writeSameAt(ctx, r, patch) {
1063
+ const value = { ...r, ...patch };
1064
+ for (const k of Object.keys(value))
1065
+ if (value[k] === undefined)
1066
+ delete value[k];
1067
+ if (!(0, session_data_1.isUpsellRecord)(value))
1068
+ return r;
1069
+ return (await ctx.host.writeUpsell(ctx.collectionId, value, { expect: "at", at: r.at })) ? value : r;
1070
+ }
1040
1071
  async function stopOpenCheck(ctx, r) {
1041
1072
  if (!(await cancelOwnEdit(ctx, r)))
1042
1073
  return "waiting";
@@ -1052,7 +1083,7 @@ async function readStoppedIntent(ctx, r) {
1052
1083
  return { kind: "mismatch", declineKind: null, pi };
1053
1084
  return { kind: "charged", declineKind: null, pi };
1054
1085
  }
1055
- if (pi.status === "failed" || pi.status === "voided") {
1086
+ if (pi.status === "failed" || pi.status === "voided" || pi.status === "cancelled") {
1056
1087
  const code = pi.declineCode;
1057
1088
  return { kind: "ended", declineKind: code === "authentication_not_completed" ? "bank_check_unfinished" : null, pi };
1058
1089
  }
@@ -1083,7 +1114,7 @@ async function recheckPrior(ctx, r) {
1083
1114
  next.push(p);
1084
1115
  continue;
1085
1116
  }
1086
- if (pi.status === "failed" || pi.status === "voided") {
1117
+ if (pi.status === "failed" || pi.status === "voided" || pi.status === "cancelled") {
1087
1118
  host.log("info", "upsell_rechecked", { ...ids, result: "ended" });
1088
1119
  changed = true;
1089
1120
  continue;
@@ -1097,21 +1128,42 @@ async function recheckPrior(ctx, r) {
1097
1128
  stuck("amount_mismatch");
1098
1129
  continue;
1099
1130
  }
1131
+ if (!refundFitsLock(ctx)) {
1132
+ host.log("warn", "upsell_late_refund", { ...ids, result: "lock_time" });
1133
+ next.push(p);
1134
+ continue;
1135
+ }
1100
1136
  host.log("warn", "upsell_charged_after_stop", ids);
1101
- const res = await host.refundLate(p.id, p.amount_minor, p.currency, lateRefundStep(host.now(), p.at));
1102
- const waitedOut = res === "unsettled" && age >= exports.UPSELL_UNSETTLED_REFUND_MS;
1137
+ const step = p.unseen_step ?? lateRefundStep(host.now(), p.at);
1138
+ const res = await host.refundLate(p.id, p.amount_minor, p.currency, step);
1139
+ const waiting = res === "unsettled" || (res === "spent" && p.unseen_step === undefined);
1140
+ const waitedOut = waiting && age >= exports.UPSELL_UNSETTLED_REFUND_MS;
1103
1141
  if (res === "refunded") {
1104
1142
  host.log("info", "upsell_late_refund", { ...ids, result: "refunded" });
1105
1143
  changed = true;
1106
1144
  }
1145
+ else if (res === "spent" && p.unseen_step !== undefined) {
1146
+ host.log("error", "upsell_late_refund", { ...ids, result: "unclear", step });
1147
+ stuck("refund_unclear");
1148
+ }
1107
1149
  else if (res === "failed" || waitedOut) {
1108
1150
  host.log("error", "upsell_late_refund", { ...ids, result: res === "failed" ? "failed" : "not_settled" });
1109
- stuck("refund_failed");
1151
+ stuck(p.unseen_step !== undefined ? "refund_unclear" : "refund_failed");
1110
1152
  }
1111
- else {
1112
- host.log(res === "unsettled" ? "info" : "warn", "upsell_late_refund", { ...ids, result: res === "unsettled" ? "not_settled_yet" : "retry" });
1153
+ else if (waiting) {
1154
+ host.log("info", "upsell_late_refund", { ...ids, result: "not_settled_yet" });
1155
+ next.push(p);
1156
+ }
1157
+ else if (res === "unread") {
1158
+ host.log("warn", "upsell_late_refund", { ...ids, result: "list_unreadable", step });
1113
1159
  next.push(p);
1114
1160
  }
1161
+ else {
1162
+ host.log("warn", "upsell_late_refund", { ...ids, result: "retry", step });
1163
+ if (p.unseen_step === undefined)
1164
+ changed = true;
1165
+ next.push({ ...p, unseen_step: step });
1166
+ }
1115
1167
  }
1116
1168
  if (!changed)
1117
1169
  return r;
package/README.md CHANGED
@@ -504,6 +504,18 @@ charges carry no address (the setup check WARNs; the store logs `shopper_ip_sig_
504
504
  it cannot believe). **Upgrading from 1.0.1:** 1.0.1 sent the address unsigned; from 1.0.2 it is used only once
505
505
  `VONPAY_SHOPPER_IP_SECRET` is set on both sides. The address is never logged or stored by the plugin.
506
506
 
507
+ **A repeated return from the bank still gets the offer (1.0.4).** The offer page needs a pass the storefront
508
+ gets while the cart is still open. From 1.0.4 the card step also gets it when the shopper presses Pay, before
509
+ they can leave for their bank's check, so a return that is repeated (a lost answer, a reload) still finds the
510
+ offer. **Upgrading a storefront set up before 1.0.4:** add this to `src/lib/vonpay/actions.ts` (the setup
511
+ command leaves an existing file as it is); without it the checkout works exactly as before.
512
+
513
+ ```ts
514
+ export async function prepareVonpayOffer() {
515
+ return vonpay.prepareVonpayOffer()
516
+ }
517
+ ```
518
+
507
519
  Guest shoppers get offers too, by default: the checkout names them by the email they type, and their
508
520
  card is kept for that purchase's offers only, then removed once the offer ends. A guest's card is never
509
521
  added to an existing customer's account because the guest typed that customer's email. `guests: false`
@@ -50,6 +50,11 @@ export async function startVonpayPayment() {
50
50
  return vonpay.startVonpayPayment()
51
51
  }
52
52
 
53
+ // The offer pass, fetched at Pay (before the shopper can leave for the bank) and kept in an httpOnly cookie.
54
+ export async function prepareVonpayOffer() {
55
+ return vonpay.prepareVonpayOffer()
56
+ }
57
+
53
58
  // "My saved cards": the signed-in customer's cards. Remove takes the card id; the store's server checks
54
59
  // the card is this customer's before anything is removed.
55
60
  export async function listVonpaySavedCards() {
@@ -476,7 +481,7 @@ function setupStorefront(root, opts = {}) {
476
481
  note(step, "failed", err && err.message ? err.message : String(err))
477
482
  }
478
483
  }
479
- const write = (file, content, step) =>
484
+ const write = (file, content, step, hint) =>
480
485
  guarded(step, () => {
481
486
  const rel = path.relative(root, file)
482
487
  if (!insideRoot(file)) return note(step, "manual", `${rel} resolves outside this project (a symlinked folder) — create it yourself`)
@@ -486,8 +491,10 @@ function setupStorefront(root, opts = {}) {
486
491
  } catch {}
487
492
  if (isLink) return note(step, "manual", `${rel} is a symlink — left alone`)
488
493
  if (fs.existsSync(file) && !force) {
489
- const same = fs.readFileSync(file, "utf8") === content
490
- return note(step, same ? "present" : "manual", same ? rel : `${rel} exists and differs — left as is (re-run with --force to replace it)`)
494
+ const existing = fs.readFileSync(file, "utf8")
495
+ const same = existing === content
496
+ const extra = !same && hint ? hint(existing) : null
497
+ return note(step, same ? "present" : "manual", same ? rel : `${rel} exists and differs — left as is (re-run with --force to replace it)${extra ? `; ${extra}` : ""}`)
491
498
  }
492
499
  if (!dryRun) {
493
500
  fs.mkdirSync(path.dirname(file), { recursive: true })
@@ -523,7 +530,11 @@ function setupStorefront(root, opts = {}) {
523
530
  if (!fs.existsSync(path.join(root, f))) throw new Error(`${f} not found — this command expects Medusa's Next.js starter layout (src/lib/config.ts exporting \`sdk\`, src/lib/data/cookies.ts and cart.ts)`)
524
531
  }
525
532
 
526
- write(path.join(root, "src/lib/vonpay/actions.ts"), actionsFile(), "server actions (src/lib/vonpay/actions.ts)")
533
+ write(path.join(root, "src/lib/vonpay/actions.ts"), actionsFile(), "server actions (src/lib/vonpay/actions.ts)", (existing) =>
534
+ existing.includes("prepareVonpayOffer")
535
+ ? null
536
+ : "it has no prepareVonpayOffer (1.0.4): add `export async function prepareVonpayOffer() { return vonpay.prepareVonpayOffer() }` so a repeated return from the bank still gets the offer (package README, upsells)"
537
+ )
527
538
  const thumbnail = fs.existsSync(path.join(root, "src/modules/products/components/thumbnail/index.tsx")) ? "@modules/products/components/thumbnail" : null
528
539
  write(path.join(root, "src/lib/vonpay/index.tsx"), componentsFile(detectUiImport(root, pkg), thumbnail), "card step + return page (src/lib/vonpay/index.tsx)")
529
540
  const checkoutGroup = path.join(root, "src/app/[countryCode]/(checkout)")
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "vonpay-medusa",
3
- "version": "1.0.2",
3
+ "version": "1.0.4",
4
4
  "description": "Vonpay payment provider for Medusa v2",
5
5
  "author": "Von Payments",
6
6
  "license": "MIT",
@@ -60,6 +60,8 @@
60
60
  "typecheck": "tsc --noEmit && tsc --noEmit -p tsconfig.test.json && tsc --noEmit -p tests/contract/tsconfig.json && tsc --noEmit -p src/admin/tsconfig.json && tsc --noEmit -p tests/integration/tsconfig.json && tsc --noEmit -p tests/admin/tsconfig.json",
61
61
  "check:money": "node scripts/ci/check-money-arithmetic.mjs src && node scripts/ci/check-money-arithmetic.mjs --self-test",
62
62
  "check:release-install": "node scripts/ci/check-release-install.mjs && node scripts/ci/check-release-install.mjs --self-test",
63
+ "check:ci-scope": "node scripts/ci/check-ci-scope.mjs && node scripts/ci/check-ci-scope.mjs --self-test",
64
+ "check:bridge-alert": "node scripts/ci/bridge-alert.mjs --self-test",
63
65
  "check:harness-isolation": "node scripts/ci/check-harness-isolation.mjs src apps && node scripts/ci/check-harness-isolation.mjs --self-test",
64
66
  "check:pack": "node scripts/ci/check-pack.mjs && node scripts/ci/check-pack.mjs --self-test",
65
67
  "check:pan-canary": "node scripts/ci/check-pan-canary.mjs && node scripts/ci/check-pan-canary.mjs --self-test",
@@ -183,7 +185,7 @@
183
185
  }
184
186
  },
185
187
  "dependencies": {
186
- "@vonpay/checkout-node": "^3.11.0",
188
+ "@vonpay/checkout-node": "^4.2.0",
187
189
  "bignumber.js": "^9.3.1"
188
190
  },
189
191
  "bin": {
@@ -4,7 +4,8 @@ import { type ReactNode, createContext, useContext } from "react"
4
4
  import type { VonpayStorefrontServer } from "./server"
5
5
  import { DEFAULT_UI, type VonpayUi } from "./ui"
6
6
 
7
- export type VonpayActions = Pick<VonpayStorefrontServer, "completeVonpayCheckout" | "refreshVonpayPayment" | "reportStuckVonpayPayment" | "startVonpayPayment">
7
+ export type VonpayActions = Pick<VonpayStorefrontServer, "completeVonpayCheckout" | "refreshVonpayPayment" | "reportStuckVonpayPayment" | "startVonpayPayment"> &
8
+ Partial<Pick<VonpayStorefrontServer, "prepareVonpayOffer">>
8
9
 
9
10
  interface VonpayContextValue {
10
11
  actions: VonpayActions
@@ -2,7 +2,7 @@ import list from "./vora-csp.json"
2
2
  import { VORA_JS_URL, type VonpayBrowserConfig } from "./config"
3
3
 
4
4
  export const VORA_CSP_VERSION = list.version
5
- export const VORA_CSP_SHA384 = "sha384-iqprMTN9Eh03U8wTGDw6iSGVdot0G7Se0lYYslVuZkUZmn9BC0TOgXB+zb5TpqaP"
5
+ export const VORA_CSP_SHA384 = "sha384-i1//4S+DUC1heRzIqlkwPggQhcxx/zzDp3RbtJrfKW721JphljXobflGiqV5VL99"
6
6
 
7
7
  export const VONPAY_DEFAULT_API_ORIGIN = "https://checkout.vonpay.com"
8
8
 
@@ -0,0 +1,10 @@
1
+ export function offerPassCartId(token: string): string | null {
2
+ const parts = token.split(".")
3
+ if (parts.length !== 3 || parts[0] !== "v2" || !/^[A-Za-z0-9_-]+$/.test(parts[1])) return null
4
+ try {
5
+ const claims = JSON.parse(Buffer.from(parts[1], "base64url").toString("utf8")) as { cart_id?: unknown } | null
6
+ return typeof claims?.cart_id === "string" && claims.cart_id.length > 0 ? claims.cart_id : null
7
+ } catch {
8
+ return null
9
+ }
10
+ }
@@ -0,0 +1,21 @@
1
+ import { sleep } from "./sleep"
2
+
3
+ export const OFFER_PREPARE_WAIT_MS = 3_500
4
+
5
+ export function startOfferPrepare(actions: object): () => Promise<void> {
6
+ let prepare: unknown
7
+ try {
8
+ prepare = (actions as { prepareVonpayOffer?: unknown }).prepareVonpayOffer
9
+ } catch {
10
+ prepare = undefined
11
+ }
12
+ if (typeof prepare !== "function") return () => Promise.resolve()
13
+ let started: Promise<unknown>
14
+ try {
15
+ started = Promise.resolve((prepare as () => unknown)()).catch(() => undefined)
16
+ } catch {
17
+ started = Promise.resolve()
18
+ }
19
+ const done = started.then(() => undefined)
20
+ return () => Promise.race([done, sleep(OFFER_PREPARE_WAIT_MS)])
21
+ }
@@ -6,6 +6,7 @@ import { type CompletionResult, type VonpaySessionView, buyerReferenceOf, vonpay
6
6
  import { STUCK_REPORT_GLOBAL_MAX, STUCK_REPORT_WINDOW_MS, stuckReportLimiter } from "./report-limit"
7
7
  import { SAVED_CARDS_COPY, SAVED_CARD_ID, readSavedCards, type VonpayRemoveCardResult, type VonpaySavedCardsResult } from "./saved-cards"
8
8
  import { SHOPPER_IP_SECRET_MIN, SHOPPER_IP_SIG_HEADER, signShopperIp } from "./shopper-ip"
9
+ import { offerPassCartId } from "./offer-pass"
9
10
  import { sleep } from "./sleep"
10
11
  import { withDeadline } from "./deadline"
11
12
  import { readOfferAnswer, readOutcome, readWalletSession, type VonpayOffer, type VonpayOfferOutcome, type VonpayWalletSession } from "./upsell"
@@ -29,6 +30,7 @@ export interface VonpayStorefrontServer {
29
30
  refreshVonpayPayment(): Promise<{ vpSessionId: string | null; status: string } | null>
30
31
  reportStuckVonpayPayment(): Promise<{ reference: string | null }>
31
32
  startVonpayPayment(): Promise<{ started: boolean }>
33
+ prepareVonpayOffer(): Promise<{ prepared: boolean }>
32
34
  listSavedCards(): Promise<VonpaySavedCardsResult>
33
35
  removeSavedCard(id: string): Promise<VonpayRemoveCardResult>
34
36
  upsellOffer(orderId: string): Promise<VonpayOffer | null>
@@ -41,6 +43,7 @@ export interface VonpayStorefrontServer {
41
43
  }
42
44
 
43
45
  export const OFFER_PASS_COOKIE = "_vonpay_offer_pass"
46
+ export { offerPassCartId }
44
47
  const passCookieName = () => (process.env.NODE_ENV === "production" ? `__Host-${OFFER_PASS_COOKIE}` : OFFER_PASS_COOKIE)
45
48
  export const OFFER_PASS_MAX_AGE_S = 90 * 60
46
49
  export const OFFER_PASS_REQUEST_MS = 3_000
@@ -61,7 +64,7 @@ async function completeVonpayCheckout(): Promise<CompletionResult> {
61
64
 
62
65
  const headers = { ...(await getAuthHeaders()) }
63
66
 
64
- const pass = await requestOfferPass(cartId, headers)
67
+ const pass = (await requestOfferPass(cartId, headers)) ?? (await keptOfferPass(cartId))
65
68
  if (!pass) await endUpsellOffer()
66
69
 
67
70
  let response: HttpTypes.StoreCompleteCartResponse
@@ -159,6 +162,19 @@ async function readSavedStatus(cartId: string, headers: Record<string, string>):
159
162
  }
160
163
  }
161
164
 
165
+ async function prepareVonpayOffer(): Promise<{ prepared: boolean }> {
166
+ try {
167
+ const cartId = await getCartId()
168
+ if (!cartId) return { prepared: false }
169
+ const pass = await requestOfferPass(cartId, { ...(await getAuthHeaders()) })
170
+ if (pass) await setOfferPass(pass)
171
+ else if (!(await keptOfferPass(cartId))) await endUpsellOffer()
172
+ return { prepared: pass !== null }
173
+ } catch {
174
+ return { prepared: false }
175
+ }
176
+ }
177
+
162
178
  async function startVonpayPayment(): Promise<{ started: boolean }> {
163
179
  const cartId = await getCartId()
164
180
  if (!cartId) return { started: false }
@@ -216,6 +232,16 @@ async function readSavedStatus(cartId: string, headers: Record<string, string>):
216
232
  }
217
233
  }
218
234
 
235
+ async function keptOfferPass(cartId: string): Promise<string | null> {
236
+ let token: string | undefined
237
+ try {
238
+ token = (await cookies()).get(passCookieName())?.value
239
+ } catch {
240
+ return null
241
+ }
242
+ return token && offerPassCartId(token) === cartId ? token : null
243
+ }
244
+
219
245
  async function setOfferPass(token: string): Promise<void> {
220
246
  try {
221
247
  ;(await cookies()).set(passCookieName(), token, { httpOnly: true, sameSite: "lax", secure: process.env.NODE_ENV === "production", path: "/", maxAge: OFFER_PASS_MAX_AGE_S })
@@ -363,6 +389,7 @@ async function readSavedStatus(cartId: string, headers: Record<string, string>):
363
389
  refreshVonpayPayment,
364
390
  reportStuckVonpayPayment,
365
391
  startVonpayPayment,
392
+ prepareVonpayOffer,
366
393
  listSavedCards,
367
394
  removeSavedCard,
368
395
  upsellOffer,
@@ -37,6 +37,7 @@ import {
37
37
  takeDeclineNote,
38
38
  } from "./reload-once"
39
39
  import type { SaveUnavailable } from "./vonpay-payment-view"
40
+ import { startOfferPrepare } from "./offer-prepare"
40
41
  import { sleep } from "./sleep"
41
42
  import { useContactStore } from "./use-contact-store"
42
43
  import VonpayPaymentView from "./vonpay-payment-view"
@@ -494,10 +495,12 @@ function CardPayment({
494
495
  }
495
496
  inFlight.current = true
496
497
  setWalletNote(undefined)
497
- void confirm().finally(() => {
498
- inFlight.current = false
499
- })
500
- }, [confirm])
498
+ void startOfferPrepare(actions)()
499
+ .then(() => confirm())
500
+ .finally(() => {
501
+ inFlight.current = false
502
+ })
503
+ }, [confirm, actions])
501
504
  const afterAction = useCallback(() => {
502
505
  if (!walletTapPending.current) return
503
506
  walletTapPending.current = false
@@ -509,7 +512,7 @@ function CardPayment({
509
512
  if (action.kind === "redirect" && !inFlight.current) {
510
513
  inFlight.current = true
511
514
  setPhase("redirecting")
512
- window.location.assign(action.url)
515
+ void startOfferPrepare(actions)().then(() => window.location.assign(action.url))
513
516
  return
514
517
  }
515
518
  askServerForWallet()
@@ -555,6 +558,7 @@ function CardPayment({
555
558
  const collection = collectionRef.current
556
559
  if (!collection) return false
557
560
  if (saveUnavailableNow.current || (saveRequiredNow.current && !termsActiveNow.current && saveTickedNow.current === false)) return false
561
+ const offerReady = startOfferPrepare(actions)
558
562
  setPhase("submitting")
559
563
  let result: VoraSubmitResult | undefined
560
564
  try {
@@ -577,14 +581,16 @@ function CardPayment({
577
581
  return false
578
582
  case "redirect":
579
583
  setPhase("redirecting")
584
+ await offerReady()
580
585
  window.location.assign(action.url)
581
586
  return true
582
587
  case "declined_ask_server":
583
588
  case "complete":
589
+ await offerReady()
584
590
  await confirm()
585
591
  return false
586
592
  }
587
- }, [confirm])
593
+ }, [confirm, actions])
588
594
 
589
595
  const startNewPayment = useCallback(async () => {
590
596
  setPhase("loading")
@@ -1,8 +1,8 @@
1
1
  {
2
- "version": "1.39.1",
2
+ "version": "1.44.1",
3
3
  "modes": {
4
4
  "test": {
5
- "version": "1.39.1",
5
+ "version": "1.44.1",
6
6
  "mode": "test",
7
7
  "directives": {
8
8
  "script-src": [
@@ -18,9 +18,11 @@
18
18
  "https://embed.sandbox.portal.vonpay.com",
19
19
  "https://applepay.cdn-apple.com",
20
20
  "https://pay.sandbox.google.com",
21
+ "https://checkout.vonpay.com",
22
+ "https://hooks.stripe.com",
23
+ "'self'",
21
24
  "https://js.stripe.com",
22
25
  "https://*.js.stripe.com",
23
- "https://hooks.stripe.com",
24
26
  "https://link.com",
25
27
  "https://*.link.com"
26
28
  ],
@@ -134,6 +136,36 @@
134
136
  "feature": "google-pay",
135
137
  "why": "Google Pay JS adds a <style> element for its button."
136
138
  },
139
+ {
140
+ "directive": "frame-src",
141
+ "source": "https://embed.sandbox.vonpay.gr4vy.app",
142
+ "feature": "wallet-modal",
143
+ "why": "The bank check for a wallet payment, in a modal on your page."
144
+ },
145
+ {
146
+ "directive": "frame-src",
147
+ "source": "https://checkout.vonpay.com",
148
+ "feature": "wallet-modal",
149
+ "why": "The page that reports the wallet bank check's result back to vora.js."
150
+ },
151
+ {
152
+ "directive": "frame-src",
153
+ "source": "https://embed.sandbox.vonpay.gr4vy.app",
154
+ "feature": "bank-check",
155
+ "why": "The card-update bank check pop-up."
156
+ },
157
+ {
158
+ "directive": "frame-src",
159
+ "source": "https://hooks.stripe.com",
160
+ "feature": "bank-check",
161
+ "why": "The same, on Stripe."
162
+ },
163
+ {
164
+ "directive": "frame-src",
165
+ "source": "'self'",
166
+ "feature": "bank-check",
167
+ "why": "Your return page."
168
+ },
137
169
  {
138
170
  "directive": "script-src",
139
171
  "source": "https://js.stripe.com",
@@ -200,10 +232,18 @@
200
232
  "feature": "stripe-link",
201
233
  "why": "Link artwork."
202
234
  }
235
+ ],
236
+ "ifNoUnsafeInline": [
237
+ {
238
+ "directive": "style-src",
239
+ "source": "'sha256-OuajJxe804doBGkJvwnBjnP1cpvNWFjHltumC6RbkcA='",
240
+ "feature": "default-look",
241
+ "why": "A one-line style element (@layer vora-defaults;) that puts the built-in default look below your own CSS layers. Without it the look still works, but your layered CSS (Tailwind v4 and similar) does not override it."
242
+ }
203
243
  ]
204
244
  },
205
245
  "live": {
206
- "version": "1.39.1",
246
+ "version": "1.44.1",
207
247
  "mode": "live",
208
248
  "directives": {
209
249
  "script-src": [
@@ -219,9 +259,11 @@
219
259
  "https://embed.portal.vonpay.com",
220
260
  "https://applepay.cdn-apple.com",
221
261
  "https://pay.google.com",
262
+ "https://checkout.vonpay.com",
263
+ "https://hooks.stripe.com",
264
+ "'self'",
222
265
  "https://js.stripe.com",
223
266
  "https://*.js.stripe.com",
224
- "https://hooks.stripe.com",
225
267
  "https://link.com",
226
268
  "https://*.link.com"
227
269
  ],
@@ -335,6 +377,36 @@
335
377
  "feature": "google-pay",
336
378
  "why": "Google Pay JS adds a <style> element for its button."
337
379
  },
380
+ {
381
+ "directive": "frame-src",
382
+ "source": "https://embed.vonpay.gr4vy.app",
383
+ "feature": "wallet-modal",
384
+ "why": "The bank check for a wallet payment, in a modal on your page."
385
+ },
386
+ {
387
+ "directive": "frame-src",
388
+ "source": "https://checkout.vonpay.com",
389
+ "feature": "wallet-modal",
390
+ "why": "The page that reports the wallet bank check's result back to vora.js."
391
+ },
392
+ {
393
+ "directive": "frame-src",
394
+ "source": "https://embed.vonpay.gr4vy.app",
395
+ "feature": "bank-check",
396
+ "why": "The card-update bank check pop-up."
397
+ },
398
+ {
399
+ "directive": "frame-src",
400
+ "source": "https://hooks.stripe.com",
401
+ "feature": "bank-check",
402
+ "why": "The same, on Stripe."
403
+ },
404
+ {
405
+ "directive": "frame-src",
406
+ "source": "'self'",
407
+ "feature": "bank-check",
408
+ "why": "Your return page."
409
+ },
338
410
  {
339
411
  "directive": "script-src",
340
412
  "source": "https://js.stripe.com",
@@ -401,6 +473,14 @@
401
473
  "feature": "stripe-link",
402
474
  "why": "Link artwork."
403
475
  }
476
+ ],
477
+ "ifNoUnsafeInline": [
478
+ {
479
+ "directive": "style-src",
480
+ "source": "'sha256-OuajJxe804doBGkJvwnBjnP1cpvNWFjHltumC6RbkcA='",
481
+ "feature": "default-look",
482
+ "why": "A one-line style element (@layer vora-defaults;) that puts the built-in default look below your own CSS layers. Without it the look still works, but your layered CSS (Tailwind v4 and similar) does not override it."
483
+ }
404
484
  ]
405
485
  }
406
486
  }