@infosoftas/s4-orders-js-sdk 0.1.21-3 → 0.2.0

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