@infosoftas/s4-orders-js-sdk 0.1.21 → 0.2.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 (72) hide show
  1. package/.editorconfig +0 -0
  2. package/.release-it.json +0 -0
  3. package/README.md +572 -471
  4. package/build/postcss-scope-tailwind.cjs +0 -0
  5. package/components.json +0 -0
  6. package/package.json +62 -58
  7. package/src/App.completion.test.tsx +677 -0
  8. package/src/App.css +0 -14
  9. package/src/App.paymentReturn.test.tsx +341 -0
  10. package/src/App.tsx +722 -639
  11. package/src/ErrorBoundary.tsx +0 -0
  12. package/src/api/InvoiceApi.ts +0 -0
  13. package/src/api/OrdersApi.ts +74 -59
  14. package/src/api/SubscribeApi.ts +0 -0
  15. package/src/bundle.ts +0 -0
  16. package/src/components/Alert/Alert.tsx +0 -0
  17. package/src/components/Button/Button.tsx +0 -0
  18. package/src/components/EHFForm/EHFForm.tsx +250 -253
  19. package/src/components/FormFields/AddressField.tsx +0 -0
  20. package/src/components/FormFields/EmailField.tsx +0 -0
  21. package/src/components/FormFields/FormFields.helper.ts +0 -0
  22. package/src/components/FormFields/FormFieldsMapper.ts +0 -0
  23. package/src/components/FormFields/InputField.tsx +0 -0
  24. package/src/components/FormFields/NameField.tsx +0 -0
  25. package/src/components/FormFields/PhoneField.tsx +0 -0
  26. package/src/components/FormFields/TermsCheckbox.tsx +0 -0
  27. package/src/components/FormFields/ToggleFiled.tsx +0 -0
  28. package/src/components/FormFields/fieldValidators.ts +0 -0
  29. package/src/components/OIOForm/OIOForm.tsx +304 -307
  30. package/src/components/OrderDenialModal/OrderDenialModal.tsx +0 -0
  31. package/src/components/OrderForm/ContactDetailsSection.tsx +0 -0
  32. package/src/components/OrderForm/OrderForm.tsx +417 -420
  33. package/src/components/OrderForm/PaymentMethodContent.tsx +0 -0
  34. package/src/components/OrderForm/PaymentMethodSection.tsx +0 -0
  35. package/src/components/OrderForm/SubmitConfirmationDialog.tsx +0 -0
  36. package/src/components/OrderForm/orderFormState.ts +0 -0
  37. package/src/components/OrderForm/useSlotElement.tsx +0 -0
  38. package/src/components/ui/alert-dialog.tsx +0 -0
  39. package/src/components/ui/alert.tsx +0 -0
  40. package/src/components/ui/button.tsx +0 -0
  41. package/src/components/ui/card.tsx +0 -0
  42. package/src/components/ui/checkbox.tsx +0 -0
  43. package/src/components/ui/field.tsx +0 -0
  44. package/src/components/ui/input.tsx +0 -0
  45. package/src/components/ui/label.tsx +0 -0
  46. package/src/components/ui/radio-group.tsx +0 -0
  47. package/src/components/ui/separator.tsx +0 -0
  48. package/src/components/ui/skeleton.tsx +0 -0
  49. package/src/components/ui/spinner.tsx +0 -0
  50. package/src/components/ui/switch.tsx +0 -0
  51. package/src/components/ui/textarea.tsx +0 -0
  52. package/src/constants/index.ts +0 -0
  53. package/src/custom.d.ts +0 -0
  54. package/src/enums/api.ts +0 -0
  55. package/src/enums/general.ts +42 -40
  56. package/src/hooks/useOrderForm.tsx +400 -403
  57. package/src/hooks/usePaymentReturn.tsx +139 -0
  58. package/src/hooks/useQueryParams.ts +0 -0
  59. package/src/index.tsx +0 -0
  60. package/src/lib/utils.ts +0 -0
  61. package/src/types/api.ts +0 -0
  62. package/src/types/general.ts +153 -136
  63. package/src/types/order.ts +91 -70
  64. package/src/utils/fetcher.ts +131 -113
  65. package/src/utils/helper.ts +0 -0
  66. package/src/utils/order.helper.test.ts +81 -0
  67. package/src/utils/order.helper.ts +285 -272
  68. package/src/utils/waitForOrderCompletion.ts +125 -0
  69. package/tsconfig.json +39 -38
  70. package/src/components/MainIframe/MainIframe.tsx +0 -42
  71. package/src/hooks/useIframe.tsx +0 -59
  72. package/src/hooks/useMessageEvent.tsx +0 -194
package/README.md CHANGED
@@ -1,471 +1,572 @@
1
- # INFO-Subscription JS/TS Order SDK
2
-
3
- This repository contains code for the Orders SDK usable to add orders for Tenants within INFO-Subscription.
4
-
5
- ## Installation
6
-
7
- Install the package with:
8
-
9
- ```sh
10
- npm install @infosoftas/s4-orders-js-sdk
11
- ```
12
-
13
- ## Available Scripts
14
-
15
- In the project directory, you can run:
16
-
17
- ### `npm run build`
18
-
19
- Builds the app for production to the `dist` folder.\
20
- It correctly bundles React in production mode and optimizes the build for the best performance.
21
-
22
- The build is minified and the filenames include the hashes.\
23
- Your app is ready to be deployed!
24
-
25
- ## Usage
26
-
27
- The package needs to be configured with configuration object:
28
-
29
- <!-- prettier-ignore -->
30
- ```ts
31
-
32
- enum PaymentMethodEnum {
33
- Vipps = 'Vipps',
34
- MobilePay = 'MobilePay',
35
- SwedbankPay = 'SwedbankPay',
36
- Mollie = 'Mollie',
37
- Invoice = 'Invoice',
38
- Email = 'Email',
39
- EHF = 'EHF',
40
- OIO = 'OIO',
41
- }
42
-
43
- type OrderFormFieldType = {
44
- name: string;
45
- required?: boolean;
46
- readOnly?: boolean;
47
- label?: string;
48
- };
49
-
50
- type PaymentMethodSettingsType = {
51
- [key in PaymentMethodEnum]?: {
52
- generateSubscriberContact?: boolean;
53
- accountId?: string;
54
- orderFormFields?: OrderFormFieldType[];
55
- paymentInvoiceFields?: OrderFormFieldType[] | never[] | null;
56
- };
57
- }
58
-
59
- type OrderFormInputsType = {
60
- name?: string;
61
- email?: string;
62
- phoneNumber?: string;
63
- paymentMethod?: PaymentMethodEnum;
64
- country?: string;
65
- city?: string;
66
- address?: string;
67
- zip?: string;
68
- };
69
-
70
- enum UserActionEnum {
71
- SELECT_FORM = 'selectForm',
72
- SELECT_PAYMENT_METHOD = 'selectPaymentMethod',
73
- RETURN_TO_MAIN = 'returnToMain',
74
- }
75
-
76
- type ConfigType = {
77
- domElementId: string;
78
- moduleTitle?: string;
79
- submitStartCallback?: (subscriberId: string) => void;
80
- userActionCallback?: (action: UserActionEnum, args: object | null | undefined) => void;
81
- setContactCallback?: (contactInfo: ContactRequestType) => void;
82
- cancelVippsCallback?: () => void;
83
- apiKey?: string;
84
- apiUrl?: string;
85
- templatePackageId: string;
86
- subscriberId: string;
87
- userId: string;
88
- identityProviderId: string;
89
- organizationId: string;
90
- redirectUrl?: string;
91
- showIframe?: boolean;
92
- /**
93
- * The full list of payment methods displayed in the UI, each with a display label and value.
94
- * Controls what the user sees in the payment method selector.
95
- * @example [{ label: 'Credit Card', value: 'SwedbankPay' }, { label: 'Invoice', value: 'Invoice' }]
96
- */
97
- availablePaymentMethods?: {
98
- label: string;
99
- value: PaymentMethodEnum;
100
- description?: string;
101
- icons?: { src: string; alt?: string; className?: string }[];
102
- }[];
103
- /**
104
- * Whitelist of payment methods the subscriber is permitted to use.
105
- * If a method is in availablePaymentMethods but not here, it will be shown but blocked.
106
- * @example ['SwedbankPay', 'Invoice']
107
- */
108
- allowedPaymentMethods?: PaymentMethodEnum[];
109
- /**
110
- * Per-payment-method form field configuration.
111
- * Controls which input fields are shown in the order form for each payment method.
112
- * Use accountId on SwedbankPay to set your Swedbank Pay account ID.
113
- */
114
- paymentMethodsOptions?: PaymentMethodSettingsType;
115
- requireTermsAcceptance?: boolean;
116
- language?: string;
117
- merchantAgreementUrl?: string;
118
- invoiceAddressSelection?: {
119
- enabled?: boolean;
120
- label?: string;
121
- fields?: OrderFormFieldType[];
122
- };
123
- settings?: {
124
- successText?: string;
125
- failureText?: string;
126
- submitButtonText?: string;
127
- backButtonText?: string;
128
- verifyButtonText?: string;
129
- organizationNumberLabel?: string;
130
- cvrLabel?: string;
131
- glnLabel?: string;
132
- orderDefaultValues?: OrderFormInputsType;
133
- paymentMethodLabel?: string;
134
- contactDetailsLabel?: string;
135
- /**
136
- * Ids of existing elements on the host page. When set, the matching
137
- * order form section is rendered into that element instead of inline.
138
- */
139
- paymentMethodElementId?: string;
140
- contactDetailsElementId?: string;
141
- errorReqMsg?: string;
142
- errorInvalidEmailMsg?: string;
143
- errorInvalidPhoneMsg?: string;
144
- errorTermsMsg?: string;
145
- errorValidationTitleMsg?: string;
146
- errorValidationDenialOrderBlockingMsg?: string;
147
- errorValidationBlockingOffersMsg?: string;
148
- paymentMethodNotAllowedMsg?: string;
149
- invoiceLookupNotFoundText?: string;
150
- orderDenialOfferBaseText?: string;
151
- orderDenialOfferWithFallbackText?: string;
152
- orderDenialAmountText?: string;
153
- fetchDenialFallbackOffer?: (organizationId: string) => Promise<OrderDenialFallbackOfferType | undefined>;
154
- termsAndConditionsText?: string | ReactNode;
155
- /**
156
- * When set, submitting the order opens a confirmation dialog first.
157
- * The order is only sent once the user confirms.
158
- */
159
- submitConfirmation?: {
160
- title: string;
161
- description?: string;
162
- confirmText: string;
163
- cancelText: string;
164
- };
165
- };
166
- }
167
- ```
168
-
169
- Usage example OrderPlace react component:
170
-
171
- <!-- prettier-ignore -->
172
- ```tsx
173
-
174
- enum OrderModuleFiledNameEnum {
175
- name = 'name',
176
- email = 'email',
177
- phoneNumber = 'phoneNumber',
178
- address = 'address',
179
- country = 'country',
180
- city = 'city',
181
- zip = 'zip',
182
- careOf = 'careOf',
183
- organizationNumber = 'organizationNumber',
184
- buyerReference = 'buyerReference',
185
- orderReference = 'orderReference',
186
- invoiceName = 'invoiceName',
187
- invoiceAddress = 'invoiceAddress',
188
- invoiceCity = 'invoiceCity',
189
- invoiceZip = 'invoiceZip',
190
- invoiceCountry = 'invoiceCountry',
191
- invoicePhone = 'invoicePhoneNumber',
192
- invoiceEmail = 'invoiceEmail',
193
- invoiceCareOf = 'invoiceCareOf',
194
- invoiceBuyerReference ='invoiceBuyerReference',
195
- }
196
-
197
- export const prepareConfig = ({
198
- submitStartCallback,
199
- apiKey,
200
- apiUrl,
201
- userId,
202
- subscriberId,
203
- templatePackageId,
204
- identityProviderId,
205
- organizationId,
206
- selfServiceUrl,
207
- userEmail,
208
- name,
209
- city,
210
- country,
211
- postalCode,
212
- streetAddress,
213
- }: Props) => {
214
-
215
- const config = {
216
- submitStartCallback,
217
- userActionCallback: (action, args) => {
218
- console.log(action);
219
- console.table(args);
220
- },
221
- moduleTitle: '',
222
- domElementId: ORDER_PLACE_ID,
223
- redirectUrl: window.location.href,
224
- merchantAgreementUrl: selfServiceUrl,
225
- showIframe: true,
226
- apiKey,
227
- apiUrl,
228
- userId,
229
- subscriberId,
230
- templatePackageId,
231
- identityProviderId,
232
- organizationId,
233
- language: 'en-US',
234
- availablePaymentMethods: [
235
- { label: "Vipps", value: "Vipps" },
236
- { label: "MobilePay", value: "MobilePay" },
237
- { label: "Credit Card/Debit Card", value: "SwedbankPay" },
238
- { label: "Mollie", value: "Mollie" },
239
- { label: 'Invoice', translateKey: 'Invoice', value: 'Invoice' },
240
- { label: 'Email', translateKey: 'Email', value: 'Email' },
241
- { label: 'EHF', translateKey: 'EHF', value: 'EHF' },
242
- { label: 'OIO', translateKey: 'OIO', value: 'OIO' },
243
- ],
244
- paymentMethodsOptions: {
245
- Vipps: {
246
- generateSubscriberContact: true,
247
- orderFormFields: [],
248
- },
249
- SwedbankPay: {
250
- orderFormFields: [
251
- {
252
- name: OrderModuleFiledNameEnum.name,
253
- label: 'Name',
254
- required: false,
255
- },
256
- {
257
- name: OrderModuleFiledNameEnum.phoneNumber,
258
- label: 'Phone',
259
- readOnly: false,
260
- required: false,
261
- },
262
- {
263
- name: OrderModuleFiledNameEnum.email,
264
- label: 'Email',
265
- required: true,
266
- readOnly: !!userEmail,
267
- },
268
- ],
269
- },
270
- Mollie: {
271
- accountId: 'your-mollie-account-id',
272
- orderFormFields: [
273
- {
274
- name: OrderModuleFiledNameEnum.name,
275
- label: 'Name',
276
- required: false,
277
- },
278
- {
279
- name: OrderModuleFiledNameEnum.email,
280
- label: 'Email',
281
- required: true,
282
- readOnly: !!userEmail,
283
- },
284
- ],
285
- },
286
- Invoice: {
287
- orderFormFields: [
288
- {
289
- name: OrderModuleFiledNameEnum.address,
290
- label: 'Address',
291
- required: false,
292
- readOnly: false,
293
- },
294
- ],
295
- },
296
- Email: {
297
- orderFormFields: [
298
- {
299
- name: OrderModuleFiledNameEnum.address,
300
- label: 'Address',
301
- required: false,
302
- readOnly: false,
303
- },
304
- ],
305
- paymentInvoiceFields: [
306
- {
307
- name: OrderModuleFiledNameEnum.invoiceEmail,
308
- label: 'Email',
309
- required: true,
310
- readOnly: false,
311
- },
312
- ],
313
- },
314
- EHF: {
315
- orderFormFields: [
316
- {
317
- name: OrderModuleFiledNameEnum.address,
318
- label: 'Address',
319
- required: false,
320
- readOnly: false,
321
- },
322
- ],
323
- },
324
- OIO: {
325
- orderFormFields: [
326
- {
327
- name: OrderModuleFiledNameEnum.address,
328
- label: 'Address',
329
- required: false,
330
- readOnly: false,
331
- },
332
- ],
333
- },
334
- },
335
- invoiceAddressSelection: {
336
- enabled: true,
337
- label: 'Invoice Address',
338
- fields: [
339
- {
340
- name: OrderModuleFiledNameEnum.invoiceAddress,
341
- label: 'Address',
342
- required: false,
343
- readOnly: false,
344
- },
345
- ],
346
- },
347
- settings: {
348
- submitButtonText: 'Continue',
349
- backButtonText: 'Back',
350
- verifyButtonText: 'Verify',
351
- organizationNumberLabel: 'Organization Number',
352
- glnLabel: 'GLN/EAN',
353
- cvrLabel: 'CVR',
354
- paymentMethodLabel: 'Select Payment Method',
355
- errorReqMsg: 'This field is required!',
356
- errorInvalidEmailMsg: 'Invalid email address!',
357
- errorInvalidPhoneMsg: 'Invalid phone number!',
358
- errorValidationTitleMsg: 'One or more validation errors occurred.',
359
- errorValidationDenialOrderBlockingMsg: 'The order/subscription will not be created because the subscriber has a denial order blocking all.',
360
- errorValidationBlockingOffersMsg: 'The order/subscription will not be created because the subscriber has a denial order blocking offers.',
361
- paymentMethodNotAllowedMsg: 'This payment method not allowed!',
362
- invoiceLookupNotFoundText: 'There was no recipient found for the given information',
363
- successText: 'Success message',
364
- failureText: 'Failed message',
365
- orderDefaultValues: {
366
- name,
367
- email: userEmail || '',
368
- phoneNumber: '',
369
- city,
370
- country,
371
- zip: postalCode,
372
- address: streetAddress,
373
- paymentMethod: undefined,
374
- },
375
- },
376
- };
377
-
378
- return config as ConfigType;
379
- };
380
-
381
-
382
- import { FC, useEffect, useRef, useCallback } from 'react';
383
- import { useSearchParams } from 'react-router-dom';
384
- import { orderComponent } from '@infosoftas/s4-orders-js-sdk/src/index';
385
-
386
- import { prepareConfig } from 'Utils/moduleConfig';
387
- import { encodeJwt } from 'Utils/helper';
388
-
389
- const ORDER_PLACE_ID = 'sdk-order';
390
-
391
- const OrderPlace: FC = ({journey, userEmail, sub, emails, userId, name, city, country, postalCode, streetAddress}) => {
392
- const moduleMount = useRef(false);
393
- const [searchParams, setSearchParams] = useSearchParams();
394
-
395
- const submitStartCallback = useCallback(
396
- (subscriberId: string) => {
397
- const hashTokenValue = {
398
- extension_SubscriberId: subscriberId,
399
- emails: emails,
400
- sub: sub,
401
- };
402
-
403
- searchParams?.set('hashToken', encodeJwt(hashTokenValue) as string);
404
- setSearchParams(searchParams);
405
- },
406
- [emails, sub, searchParams, setSearchParams]
407
- );
408
-
409
- useEffect(() => {
410
- if (!moduleMount.current && idTokenClaims) {
411
- moduleMount.current = true;
412
- const config = prepareConfig({
413
- apiKey: API_KEY,
414
- apiUrl: API_URL,
415
- userId: userId || '',
416
- subscriberId: userEmail || '',
417
- identityProviderId: IDENTITY_PROVIDER_ID,
418
- templatePackageId: TEMPLATE_PACKAGE_ID,
419
- selfServiceUrl: SELF_SERVICE_URL,
420
- organizationId: ORGANIZATION_ID,
421
- userEmail: userEmail || '',
422
- name: name,
423
- city: city,
424
- country: country,
425
- postalCode: postalCode,
426
- streetAddress: streetAddress,
427
- journey: journey,
428
- submitStartCallback: submitStartCallback,
429
- });
430
- orderComponent?.remove();
431
- orderComponent?.init(config);
432
- }
433
- }, [userEmail, userId, name, city, country, postalCode, streetAddress, journey, submitStartCallback]);
434
-
435
- return (
436
- <div
437
- id={ORDER_PLACE_ID}
438
- className="w-100 order-wrapper"
439
- data-testid="order-place-id"
440
- />
441
- );
442
- };
443
-
444
- export default OrderPlace;
445
- ```
446
-
447
- <!-- prettier-ignore -->
448
- | Option | Default | Description |
449
- | --------------------- | :----------------------------------------------------------------------------: | -------------------------: |
450
- | moduleTitle | '' | module title |
451
- | apiKey | '' | order api key |
452
- | apiUrl | '' | order api url |
453
- | templatePackageId | '' | template package id |
454
- | subscriberId | '' | subscriber id |
455
- | identityProviderId | '' | identity provider id |
456
- | organizationId | '' | organization id |
457
- | redirectUrl | window.location.href | redirect url |
458
- | showIframe | false | show credit card in iframe |
459
- | userActionCallback | undefined | function for tracking user actions |
460
- | cancelVippsCallback | undefined | callback invoked when a Vipps/MobilePay payment is cancelled |
461
- | paymentMethodsOptions | orderFormFields: [{name: 'phoneNumber', required: false, readOnly: false, label: ''}] | default form fields |
462
- | availablePaymentMethods | [] | available payment methods to display |
463
- | allowedPaymentMethods | [] | list of payment methods the subscriber is allowed to use |
464
- | requireTermsAcceptance | false | when true, the user must accept terms and conditions before submitting |
465
- | language | 'en-US' | language |
466
- | merchantAgreementUrl | '' | vipps and MobilePay property |
467
- | settings.paymentMethodElementId / settings.contactDetailsElementId | undefined | ids of host page elements to render the payment method / contact detail sections into, instead of inline |
468
- | settings.submitConfirmation | undefined | `{ title, description?, confirmText, cancelText }` — shows a confirmation dialog before the order is submitted |
469
- | settings.contactDetailsLabel | undefined | heading for the contact details section |
470
- | settings.errorTermsMsg | undefined | validation message shown when terms are not accepted |
471
- | settings | {successText: 'Order completed successfully!', failureText: 'Something went wrong!', submitButtonText: 'Start', backButtonText: 'Back', verifyButtonText: 'Verify', organizationNumberLabel: 'Organization Number', cvrLabel: 'CVR', glnLabel: 'GLN', paymentMethodLabel: 'Select Payment Method', orderDefaultValues: 'Default order form values', errorReqMsg: '', errorInvalidEmailMsg: '', errorInvalidPhoneMsg: '', errorValidationTitleMsg: 'One or more validation errors occurred.', errorValidationDenialOrderBlockingMsg: '...', errorValidationBlockingOffersMsg: '...', paymentMethodNotAllowedMsg: 'This payment method not allowed!', invoiceLookupNotFoundText: 'There was no recipient found for the given information', termsAndConditionsText: '' } | label and text properties |
1
+ # INFO-Subscription JS/TS Order SDK
2
+
3
+ This repository contains code for the Orders SDK usable to add orders for Tenants within INFO-Subscription.
4
+
5
+ ## Installation
6
+
7
+ Install the package with:
8
+
9
+ ```sh
10
+ npm install @infosoftas/s4-orders-js-sdk
11
+ ```
12
+
13
+ ## Available Scripts
14
+
15
+ In the project directory, you can run:
16
+
17
+ ### `npm run build`
18
+
19
+ Builds the app for production to the `dist` folder.\
20
+ It correctly bundles React in production mode and optimizes the build for the best performance.
21
+
22
+ The build is minified and the filenames include the hashes.\
23
+ Your app is ready to be deployed!
24
+
25
+ ### `npm test`
26
+
27
+ Runs completion-flow regression tests.
28
+
29
+ ## Order completion
30
+
31
+ The Simple Orders API completion POST acknowledges receipt; it does not wait
32
+ for order processing. By default, the SDK then reads `GET /order/{id}` using
33
+ the configured `apiUrl` and API key. Deploy that endpoint before upgrading.
34
+
35
+ The SDK reads immediately, then waits 500 ms between completed reads, with at
36
+ most one request in flight. Polling stops after 10 seconds, including time
37
+ spent waiting for a response. Only status `Completed` displays `successText`,
38
+ invokes `orderCompletedCallback`, and emits the existing `orderFlowComplete`
39
+ message. That message retains `isCompleted` and `orderInfo`, and adds the
40
+ exact submitted `orderId`. `orderInfo` can be `null` after a payment redirect.
41
+ Completed order processing does not guarantee downstream subscription or
42
+ entitlement visibility.
43
+
44
+ While polling, the SDK shows `settings.orderProcessingText`. If the deadline
45
+ expires, it shows `settings.orderDelayedText`, defaulting to:
46
+
47
+ > Your order was received, but things are taking longer than expected.
48
+
49
+ It invokes `orderCompletionDelayedCallback` with reason `timeout`. This is
50
+ not an order failure: the SDK does not emit success, redirect, reopen the
51
+ order form, or resubmit the order. The host can use the callback to provide
52
+ its own follow-up experience.
53
+
54
+ Polling continues only while the order status is `Created` or `InProgress`.
55
+ Network errors, temporary 404s and server errors are retried within the
56
+ deadline. Rate limiting honors `Retry-After`; if that header is missing,
57
+ invalid or not exposed by CORS, no further reads occur before the deadline.
58
+ Other HTTP errors (including `401`, which means the token has expired and the
59
+ user must sign in again), malformed responses and any other status stop
60
+ verification and show the same received message with callback reason
61
+ `statusUnavailable`; they do not prove rejection.
62
+ `Cancelled` and `Rejected` instead show `failureText` and invoke
63
+ `orderCompletionFailedCallback` with the returned status, without reopening
64
+ submission. Removing the SDK or switching orders aborts outstanding reads.
65
+ An accepted completion POST is not repeated for the same order.
66
+
67
+ ### Payment returns
68
+
69
+ All online payment methods (Vipps, MobilePay, SwedbankPay and Mollie) use
70
+ full-page redirects to the provider. The provider returns to `redirectUrl`
71
+ (default: the current page), and the SDK reads the return from the URL
72
+ parameters (`action=complete`/`action=cancel` with `S4OrderId`, or Vipps'
73
+ `orderId` and `agreementId`). The SDK never completes or cancels an order
74
+ because of a browser `message` event. It only posts its own notifications
75
+ (`orderFlowComplete`, `orderFlowCancel`, `orderUpdateInfo`) to the host page.
76
+
77
+ ### Callbacks and external confirmation
78
+
79
+ All completion callbacks receive `{ orderId, orderInfo }`, where `orderId`
80
+ is always the ID submitted in the successful POST and `orderInfo` is nullable.
81
+ `orderAcceptedCallback` runs after that POST succeeds, before polling.
82
+ Delayed callbacks additionally receive `reason`; failed callbacks receive
83
+ `status`. Callback errors do not change the order outcome.
84
+
85
+ Set `completionMode: 'external'` to opt out of SDK polling:
86
+
87
+ ```ts
88
+ orderComponent.init({
89
+ // ...existing configuration
90
+ completionMode: 'external',
91
+ orderAcceptedCallback: ({ orderId, orderInfo }) => {
92
+ // The host now owns verification, success UI and any redirect.
93
+ },
94
+ });
95
+ ```
96
+
97
+ External mode shows `settings.orderReceivedText` (default: "Your order was
98
+ received.") and does not display success or emit `orderFlowComplete`.
99
+ Use an acceptance callback to hand off confirmation to the host. There is
100
+ no automatic success fallback when polling is disabled.
101
+
102
+ **Migration:** `orderFlowComplete` now means confirmed order completion, not
103
+ POST acceptance. Consumers must not treat payment-provider returns as success.
104
+ Trigger success UI, conversion tracking and
105
+ redirects only from confirmed completion. No consumer-side poller is needed
106
+ when using the default mode.
107
+
108
+ ## Usage
109
+
110
+ The package needs to be configured with configuration object:
111
+
112
+ <!-- prettier-ignore -->
113
+ ```ts
114
+
115
+ enum PaymentMethodEnum {
116
+ Vipps = 'Vipps',
117
+ MobilePay = 'MobilePay',
118
+ SwedbankPay = 'SwedbankPay',
119
+ Mollie = 'Mollie',
120
+ Invoice = 'Invoice',
121
+ Email = 'Email',
122
+ EHF = 'EHF',
123
+ OIO = 'OIO',
124
+ }
125
+
126
+ type OrderFormFieldType = {
127
+ name: string;
128
+ required?: boolean;
129
+ readOnly?: boolean;
130
+ label?: string;
131
+ };
132
+
133
+ type PaymentMethodSettingsType = {
134
+ [key in PaymentMethodEnum]?: {
135
+ generateSubscriberContact?: boolean;
136
+ accountId?: string;
137
+ orderFormFields?: OrderFormFieldType[];
138
+ paymentInvoiceFields?: OrderFormFieldType[] | never[] | null;
139
+ };
140
+ }
141
+
142
+ type OrderFormInputsType = {
143
+ name?: string;
144
+ email?: string;
145
+ phoneNumber?: string;
146
+ paymentMethod?: PaymentMethodEnum;
147
+ country?: string;
148
+ city?: string;
149
+ address?: string;
150
+ zip?: string;
151
+ };
152
+
153
+ enum UserActionEnum {
154
+ SELECT_FORM = 'selectForm',
155
+ SELECT_PAYMENT_METHOD = 'selectPaymentMethod',
156
+ RETURN_TO_MAIN = 'returnToMain',
157
+ }
158
+
159
+ type OrderCompletionEventType = {
160
+ orderId: string;
161
+ orderInfo: {
162
+ orderId: string;
163
+ subscriberId: string;
164
+ paymentMethod: string;
165
+ } | null;
166
+ };
167
+
168
+ type ConfigType = {
169
+ completionMode?: 'sdk' | 'external'; // Default: 'sdk'
170
+ orderAcceptedCallback?: (event: OrderCompletionEventType) => void;
171
+ orderCompletedCallback?: (event: OrderCompletionEventType) => void;
172
+ orderCompletionDelayedCallback?: (
173
+ event: OrderCompletionEventType & { reason: 'timeout' | 'statusUnavailable' }
174
+ ) => void;
175
+ orderCompletionFailedCallback?: (
176
+ event: OrderCompletionEventType & { status: 'Cancelled' | 'Rejected' }
177
+ ) => void;
178
+ domElementId: string;
179
+ moduleTitle?: string;
180
+ submitStartCallback?: (subscriberId: string) => void;
181
+ userActionCallback?: (action: UserActionEnum, args: object | null | undefined) => void;
182
+ setContactCallback?: (contactInfo: ContactRequestType) => void;
183
+ cancelVippsCallback?: () => void;
184
+ apiKey?: string;
185
+ apiUrl?: string;
186
+ templatePackageId: string;
187
+ subscriberId: string;
188
+ userId: string;
189
+ identityProviderId: string;
190
+ organizationId: string;
191
+ redirectUrl?: string;
192
+ /**
193
+ * The full list of payment methods displayed in the UI, each with a display label and value.
194
+ * Controls what the user sees in the payment method selector.
195
+ * @example [{ label: 'Credit Card', value: 'SwedbankPay' }, { label: 'Invoice', value: 'Invoice' }]
196
+ */
197
+ availablePaymentMethods?: {
198
+ label: string;
199
+ value: PaymentMethodEnum;
200
+ description?: string;
201
+ icons?: { src: string; alt?: string; className?: string }[];
202
+ }[];
203
+ /**
204
+ * Whitelist of payment methods the subscriber is permitted to use.
205
+ * If a method is in availablePaymentMethods but not here, it will be shown but blocked.
206
+ * @example ['SwedbankPay', 'Invoice']
207
+ */
208
+ allowedPaymentMethods?: PaymentMethodEnum[];
209
+ /**
210
+ * Per-payment-method form field configuration.
211
+ * Controls which input fields are shown in the order form for each payment method.
212
+ * Use accountId on SwedbankPay to set your Swedbank Pay account ID.
213
+ */
214
+ paymentMethodsOptions?: PaymentMethodSettingsType;
215
+ requireTermsAcceptance?: boolean;
216
+ language?: string;
217
+ merchantAgreementUrl?: string;
218
+ invoiceAddressSelection?: {
219
+ enabled?: boolean;
220
+ label?: string;
221
+ fields?: OrderFormFieldType[];
222
+ };
223
+ settings?: {
224
+ successText?: string;
225
+ orderProcessingText?: string;
226
+ orderReceivedText?: string;
227
+ orderDelayedText?: string;
228
+ failureText?: string;
229
+ submitButtonText?: string;
230
+ backButtonText?: string;
231
+ verifyButtonText?: string;
232
+ organizationNumberLabel?: string;
233
+ cvrLabel?: string;
234
+ glnLabel?: string;
235
+ orderDefaultValues?: OrderFormInputsType;
236
+ paymentMethodLabel?: string;
237
+ contactDetailsLabel?: string;
238
+ /**
239
+ * Ids of existing elements on the host page. When set, the matching
240
+ * order form section is rendered into that element instead of inline.
241
+ */
242
+ paymentMethodElementId?: string;
243
+ contactDetailsElementId?: string;
244
+ errorReqMsg?: string;
245
+ errorInvalidEmailMsg?: string;
246
+ errorInvalidPhoneMsg?: string;
247
+ errorTermsMsg?: string;
248
+ errorValidationTitleMsg?: string;
249
+ errorValidationDenialOrderBlockingMsg?: string;
250
+ errorValidationBlockingOffersMsg?: string;
251
+ paymentMethodNotAllowedMsg?: string;
252
+ invoiceLookupNotFoundText?: string;
253
+ orderDenialOfferBaseText?: string;
254
+ orderDenialOfferWithFallbackText?: string;
255
+ orderDenialAmountText?: string;
256
+ fetchDenialFallbackOffer?: (organizationId: string) => Promise<OrderDenialFallbackOfferType | undefined>;
257
+ termsAndConditionsText?: string | ReactNode;
258
+ /**
259
+ * When set, submitting the order opens a confirmation dialog first.
260
+ * The order is only sent once the user confirms.
261
+ */
262
+ submitConfirmation?: {
263
+ title: string;
264
+ description?: string;
265
+ confirmText: string;
266
+ cancelText: string;
267
+ };
268
+ };
269
+ }
270
+ ```
271
+
272
+ Usage example OrderPlace react component:
273
+
274
+ <!-- prettier-ignore -->
275
+ ```tsx
276
+
277
+ enum OrderModuleFiledNameEnum {
278
+ name = 'name',
279
+ email = 'email',
280
+ phoneNumber = 'phoneNumber',
281
+ address = 'address',
282
+ country = 'country',
283
+ city = 'city',
284
+ zip = 'zip',
285
+ careOf = 'careOf',
286
+ organizationNumber = 'organizationNumber',
287
+ buyerReference = 'buyerReference',
288
+ orderReference = 'orderReference',
289
+ invoiceName = 'invoiceName',
290
+ invoiceAddress = 'invoiceAddress',
291
+ invoiceCity = 'invoiceCity',
292
+ invoiceZip = 'invoiceZip',
293
+ invoiceCountry = 'invoiceCountry',
294
+ invoicePhone = 'invoicePhoneNumber',
295
+ invoiceEmail = 'invoiceEmail',
296
+ invoiceCareOf = 'invoiceCareOf',
297
+ invoiceBuyerReference ='invoiceBuyerReference',
298
+ }
299
+
300
+ export const prepareConfig = ({
301
+ submitStartCallback,
302
+ apiKey,
303
+ apiUrl,
304
+ userId,
305
+ subscriberId,
306
+ templatePackageId,
307
+ identityProviderId,
308
+ organizationId,
309
+ selfServiceUrl,
310
+ userEmail,
311
+ name,
312
+ city,
313
+ country,
314
+ postalCode,
315
+ streetAddress,
316
+ }: Props) => {
317
+
318
+ const config = {
319
+ submitStartCallback,
320
+ userActionCallback: (action, args) => {
321
+ console.log(action);
322
+ console.table(args);
323
+ },
324
+ moduleTitle: '',
325
+ domElementId: ORDER_PLACE_ID,
326
+ redirectUrl: window.location.href,
327
+ merchantAgreementUrl: selfServiceUrl,
328
+ apiKey,
329
+ apiUrl,
330
+ userId,
331
+ subscriberId,
332
+ templatePackageId,
333
+ identityProviderId,
334
+ organizationId,
335
+ language: 'en-US',
336
+ availablePaymentMethods: [
337
+ { label: "Vipps", value: "Vipps" },
338
+ { label: "MobilePay", value: "MobilePay" },
339
+ { label: "Credit Card/Debit Card", value: "SwedbankPay" },
340
+ { label: "Mollie", value: "Mollie" },
341
+ { label: 'Invoice', translateKey: 'Invoice', value: 'Invoice' },
342
+ { label: 'Email', translateKey: 'Email', value: 'Email' },
343
+ { label: 'EHF', translateKey: 'EHF', value: 'EHF' },
344
+ { label: 'OIO', translateKey: 'OIO', value: 'OIO' },
345
+ ],
346
+ paymentMethodsOptions: {
347
+ Vipps: {
348
+ generateSubscriberContact: true,
349
+ orderFormFields: [],
350
+ },
351
+ SwedbankPay: {
352
+ orderFormFields: [
353
+ {
354
+ name: OrderModuleFiledNameEnum.name,
355
+ label: 'Name',
356
+ required: false,
357
+ },
358
+ {
359
+ name: OrderModuleFiledNameEnum.phoneNumber,
360
+ label: 'Phone',
361
+ readOnly: false,
362
+ required: false,
363
+ },
364
+ {
365
+ name: OrderModuleFiledNameEnum.email,
366
+ label: 'Email',
367
+ required: true,
368
+ readOnly: !!userEmail,
369
+ },
370
+ ],
371
+ },
372
+ Mollie: {
373
+ accountId: 'your-mollie-account-id',
374
+ orderFormFields: [
375
+ {
376
+ name: OrderModuleFiledNameEnum.name,
377
+ label: 'Name',
378
+ required: false,
379
+ },
380
+ {
381
+ name: OrderModuleFiledNameEnum.email,
382
+ label: 'Email',
383
+ required: true,
384
+ readOnly: !!userEmail,
385
+ },
386
+ ],
387
+ },
388
+ Invoice: {
389
+ orderFormFields: [
390
+ {
391
+ name: OrderModuleFiledNameEnum.address,
392
+ label: 'Address',
393
+ required: false,
394
+ readOnly: false,
395
+ },
396
+ ],
397
+ },
398
+ Email: {
399
+ orderFormFields: [
400
+ {
401
+ name: OrderModuleFiledNameEnum.address,
402
+ label: 'Address',
403
+ required: false,
404
+ readOnly: false,
405
+ },
406
+ ],
407
+ paymentInvoiceFields: [
408
+ {
409
+ name: OrderModuleFiledNameEnum.invoiceEmail,
410
+ label: 'Email',
411
+ required: true,
412
+ readOnly: false,
413
+ },
414
+ ],
415
+ },
416
+ EHF: {
417
+ orderFormFields: [
418
+ {
419
+ name: OrderModuleFiledNameEnum.address,
420
+ label: 'Address',
421
+ required: false,
422
+ readOnly: false,
423
+ },
424
+ ],
425
+ },
426
+ OIO: {
427
+ orderFormFields: [
428
+ {
429
+ name: OrderModuleFiledNameEnum.address,
430
+ label: 'Address',
431
+ required: false,
432
+ readOnly: false,
433
+ },
434
+ ],
435
+ },
436
+ },
437
+ invoiceAddressSelection: {
438
+ enabled: true,
439
+ label: 'Invoice Address',
440
+ fields: [
441
+ {
442
+ name: OrderModuleFiledNameEnum.invoiceAddress,
443
+ label: 'Address',
444
+ required: false,
445
+ readOnly: false,
446
+ },
447
+ ],
448
+ },
449
+ settings: {
450
+ submitButtonText: 'Continue',
451
+ backButtonText: 'Back',
452
+ verifyButtonText: 'Verify',
453
+ organizationNumberLabel: 'Organization Number',
454
+ glnLabel: 'GLN/EAN',
455
+ cvrLabel: 'CVR',
456
+ paymentMethodLabel: 'Select Payment Method',
457
+ errorReqMsg: 'This field is required!',
458
+ errorInvalidEmailMsg: 'Invalid email address!',
459
+ errorInvalidPhoneMsg: 'Invalid phone number!',
460
+ errorValidationTitleMsg: 'One or more validation errors occurred.',
461
+ errorValidationDenialOrderBlockingMsg: 'The order/subscription will not be created because the subscriber has a denial order blocking all.',
462
+ errorValidationBlockingOffersMsg: 'The order/subscription will not be created because the subscriber has a denial order blocking offers.',
463
+ paymentMethodNotAllowedMsg: 'This payment method not allowed!',
464
+ invoiceLookupNotFoundText: 'There was no recipient found for the given information',
465
+ successText: 'Success message',
466
+ failureText: 'Failed message',
467
+ orderDefaultValues: {
468
+ name,
469
+ email: userEmail || '',
470
+ phoneNumber: '',
471
+ city,
472
+ country,
473
+ zip: postalCode,
474
+ address: streetAddress,
475
+ paymentMethod: undefined,
476
+ },
477
+ },
478
+ };
479
+
480
+ return config as ConfigType;
481
+ };
482
+
483
+
484
+ import { FC, useEffect, useRef, useCallback } from 'react';
485
+ import { useSearchParams } from 'react-router-dom';
486
+ import { orderComponent } from '@infosoftas/s4-orders-js-sdk/src/index';
487
+
488
+ import { prepareConfig } from 'Utils/moduleConfig';
489
+ import { encodeJwt } from 'Utils/helper';
490
+
491
+ const ORDER_PLACE_ID = 'sdk-order';
492
+
493
+ const OrderPlace: FC = ({journey, userEmail, sub, emails, userId, name, city, country, postalCode, streetAddress}) => {
494
+ const moduleMount = useRef(false);
495
+ const [searchParams, setSearchParams] = useSearchParams();
496
+
497
+ const submitStartCallback = useCallback(
498
+ (subscriberId: string) => {
499
+ const hashTokenValue = {
500
+ extension_SubscriberId: subscriberId,
501
+ emails: emails,
502
+ sub: sub,
503
+ };
504
+
505
+ searchParams?.set('hashToken', encodeJwt(hashTokenValue) as string);
506
+ setSearchParams(searchParams);
507
+ },
508
+ [emails, sub, searchParams, setSearchParams]
509
+ );
510
+
511
+ useEffect(() => {
512
+ if (!moduleMount.current && idTokenClaims) {
513
+ moduleMount.current = true;
514
+ const config = prepareConfig({
515
+ apiKey: API_KEY,
516
+ apiUrl: API_URL,
517
+ userId: userId || '',
518
+ subscriberId: userEmail || '',
519
+ identityProviderId: IDENTITY_PROVIDER_ID,
520
+ templatePackageId: TEMPLATE_PACKAGE_ID,
521
+ selfServiceUrl: SELF_SERVICE_URL,
522
+ organizationId: ORGANIZATION_ID,
523
+ userEmail: userEmail || '',
524
+ name: name,
525
+ city: city,
526
+ country: country,
527
+ postalCode: postalCode,
528
+ streetAddress: streetAddress,
529
+ journey: journey,
530
+ submitStartCallback: submitStartCallback,
531
+ });
532
+ orderComponent?.remove();
533
+ orderComponent?.init(config);
534
+ }
535
+ }, [userEmail, userId, name, city, country, postalCode, streetAddress, journey, submitStartCallback]);
536
+
537
+ return (
538
+ <div
539
+ id={ORDER_PLACE_ID}
540
+ className="w-100 order-wrapper"
541
+ data-testid="order-place-id"
542
+ />
543
+ );
544
+ };
545
+
546
+ export default OrderPlace;
547
+ ```
548
+
549
+ <!-- prettier-ignore -->
550
+ | Option | Default | Description |
551
+ | --------------------- | :----------------------------------------------------------------------------: | -------------------------: |
552
+ | moduleTitle | '' | module title |
553
+ | apiKey | '' | order api key |
554
+ | apiUrl | '' | order api url |
555
+ | templatePackageId | '' | template package id |
556
+ | subscriberId | '' | subscriber id |
557
+ | identityProviderId | '' | identity provider id |
558
+ | organizationId | '' | organization id |
559
+ | redirectUrl | window.location.href | redirect url |
560
+ | userActionCallback | undefined | function for tracking user actions |
561
+ | cancelVippsCallback | undefined | callback invoked when a Vipps/MobilePay payment is cancelled |
562
+ | paymentMethodsOptions | orderFormFields: [{name: 'phoneNumber', required: false, readOnly: false, label: ''}] | default form fields |
563
+ | availablePaymentMethods | [] | available payment methods to display |
564
+ | allowedPaymentMethods | [] | list of payment methods the subscriber is allowed to use |
565
+ | requireTermsAcceptance | false | when true, the user must accept terms and conditions before submitting |
566
+ | language | 'en-US' | language |
567
+ | merchantAgreementUrl | '' | vipps and MobilePay property |
568
+ | settings.paymentMethodElementId / settings.contactDetailsElementId | undefined | ids of host page elements to render the payment method / contact detail sections into, instead of inline |
569
+ | settings.submitConfirmation | undefined | `{ title, description?, confirmText, cancelText }` — shows a confirmation dialog before the order is submitted |
570
+ | settings.contactDetailsLabel | undefined | heading for the contact details section |
571
+ | settings.errorTermsMsg | undefined | validation message shown when terms are not accepted |
572
+ | settings | {successText: 'Order completed successfully!', failureText: 'Something went wrong!', submitButtonText: 'Start', backButtonText: 'Back', verifyButtonText: 'Verify', organizationNumberLabel: 'Organization Number', cvrLabel: 'CVR', glnLabel: 'GLN', paymentMethodLabel: 'Select Payment Method', orderDefaultValues: 'Default order form values', errorReqMsg: '', errorInvalidEmailMsg: '', errorInvalidPhoneMsg: '', errorValidationTitleMsg: 'One or more validation errors occurred.', errorValidationDenialOrderBlockingMsg: '...', errorValidationBlockingOffersMsg: '...', paymentMethodNotAllowedMsg: 'This payment method not allowed!', invoiceLookupNotFoundText: 'There was no recipient found for the given information', termsAndConditionsText: '' } | label and text properties |