Search.../

createOnlineOrder( )

Creates an order online for currently logged-in member.

Description

The createOnlineOrder() function returns a Promise that resolves to an Order object when the order has been created. The order is for the currently logged-in member. The buyer must be logged in for you to be able to create an order.

Note: The pricing plan createOnlineOrder() and createOfflineOrder() functions replace the deprecated paid plans orderPlan() function. The deprecated function will continue to work, but will not receive updates. To keep any existing code compatible with future changes, see the migration instructions.

Purchasing a plan:

  1. Starts with creating an order.
  2. For non-free plans, calling the Wix Pay startPayment() function with the wixPayOrderId value as the paymentId parameter to enable your buyer to pay for the order. (Do not call the Wix Pay createPayment() function to create the payment ID because this createOnlineOrder() function does that for you.)
  3. If the order is free, do not call the Wix Pay startPayment() function after createOnlineOrder(). The order is created and considered paid for.

Once an online order is paid for, the status of the order is no longer "DRAFT" and at this point, its startDate cannot be changed.

Creating an online order causes:

  • The order status to be set to "PENDING" if the start date is in the future. Otherwise, the status is set to "ACTIVE".

The onOrderCreated() event handler runs when an online order is created.

Note: If startDate is not used in the function, the missing parameter has to be passed as undefined, for example: function createOnlineOrder(planId, undefined, couponCode)

Syntax

function createOnlineOrder(planId: string, [startDate: Date], [couponCode: string]): Promise<Order>

createOnlineOrder Parameters

NAME
TYPE
DESCRIPTION
planId
string

ID of the plan being ordered.

startDate
Optional
Date

Start date and time for the ordered plan.

couponCode
Optional
string

Coupon code to apply.

To learn more about coupons, see applyCoupon().

Returns

Fulfilled - The order of the plan.

Return Type:

Promise<Order>
NAME
TYPE
DESCRIPTION
_id
string

Order ID.

planId
string

ID of the plan that was ordered.

subscriptionId
string

ID of the related Wix subscription.

Every pricing plan order corresponds to a Wix subscription, including orders for single payment plans. You can see all orders from your site's Subscriptions page in the Dashboard.

wixPayOrderId
string

ID of the associated Wix Pay order.

Created by the createOnlineOrder() or createfflineOrder() function. For online orders, send this value as a parameter to the Wix Pay startPayment() function to enable your buyer to pay for the order. wixPayOrderId is omitted if the order is free.

buyer
Buyer

The buyer's IDs. Includes memberId and contactId.

Currently, Pricing Plan orders are limited to members only. contactId is returned, but a buyer will not be able to order a plan without a memberId.

priceDetails
PriceDetails

Deprecated. Use pricing instead.

pricing
Pricing

Order pricing model, price, and payment schedule.

type
string

How the order was processed. Supported values:

  • "ONLINE". The buyer ordered the plan using the site.
  • "OFFLINE". The buyer made a manual, offline order without using the site.
status
string

Status of the order. Supported values:

  • "DRAFT". The order has been initiated but payment hasn't been processed yet. The plan isn't yet available for use.
  • "PENDING". The order has been processed and its start date is set in the future. The plan isn't yet available for use.
  • "ACTIVE". The order has been processed. The plan is available for use.
  • "PAUSED". The order, and use of the plan, is paused. For example, if the buyer is away. The order, and use of the plan, can be resumed.
  • "ENDED". The order has completed its duration and is no longer available for use.
  • "CANCELED". The order has been canceled.
autoRenewCanceled
boolean

Whether the order will be canceled at the next payment date.

If true, the order status will be CANCELED and the next payment won't be charged. Omitted for single payment orders.

cancellation
Cancellation

Details about the cancellation of an order. Only present if the status is "CANCELED".

lastPaymentStatus
string

Status of the last payment for the order. This is updated automatically for online orders. The site owner updates this manually for offline orders. Supported values:

  • "PAID". The last payment was paid.
  • "REFUNDED". The last payment was refunded.
  • "FAILED". The last payment transaction didn't complete.
  • "UNPAID". The last payment wasn't paid.
  • "PENDING". Awaiting payment.
  • "NOT_APPLICABLE". No payment was necessary. For example, for free plans or free trials.
startDate
Date

Start date and time for the ordered plan.

endDate
Date

Current date and time the ordered plan will expire.

endDate may be updated over the course of an order. If the order is paused, it will have a later endDate once it resumes. endDate may also be postponed.

Omitted if the order is valid until canceled and still "ACTIVE".

pausePeriods
Array<PausePeriod>

List of periods during which this order is paused.

freeTrialDays
string

Free trial period, in days. Only available for recurring plans.

earliestEndDate
Date

Earliest end date and time that the plan for this order can expire.

This is calculated by adding all pause periods to the original end date. Omitted if the order is active until canceled. Reserved for future use.

currentCycle
CurrentCycle

Current payment cycle for the order.

currentCycle will be omitted if the order's status is CANCELED or ENDED, or if the startDate hasn't passed yet.

planName
string

Name of the plan at the time of the order.

planDescription
string

Description of the plan at the time of the order.

planPrice
string

Plan price as it was at the moment of order creation.

_createdDate
Date

Date and time the order was created.

_updatedDate
Date

Date and time the order was last updated. For example, the date and time an order was paused, resumed, or canceled.

Was this helpful?

Create an online order for a plan

Copy Code
1import { Permissions, webMethod } from 'wix-web-module';
2import { checkout } from 'wix-pricing-plans-backend';
3
4// Sample planId value: 'aef93bb6-aaaa-4965-966e-bd68dd2a1cc2'
5
6export const myCreateOnlineOrderFunction = webMethod(Permissions.Anyone, async (planId) => {
7 try {
8 const order = await checkout.createOnlineOrder(planId);
9 const orderId = order._id;
10 const plan = order.planName;
11 const orderType = order.type;
12
13 return order;
14 } catch (error) {
15 console.error(error);
16 }
17});
18
19/* Promise resolves to:
20 *
21 * {
22 * "_id": "73a646b3-6aff-4fc6-a18b-9e30cf725aa5",
23 * "planId": "aef93bb6-aaaa-4965-966e-bd68dd2a1cc2",
24 * "subscriptionId": "f713e998-8344-4791-8c54-00d578746ff4",
25 * "wixPayOrderId": "6a5c0cfc-490b-4120-a704-c49facae1172",
26 * "buyer": {
27 * "memberId": "ea3d74df-b7dc-4ca1-a7c9-c416b9017a86",
28 * "contactId": "ea3d74df-b7dc-4ca1-a7c9-c416b9017a86"
29 * },
30 * "priceDetails": {
31 * "subtotal": "2",
32 * "discount": "0",
33 * "total": "2",
34 * "planPrice": "2",
35 * "currency": "USD",
36 * "subscription": {
37 * "cycleDuration": {
38 * "count": 1,
39 * "unit": "WEEK"
40 * },
41 * "cycleCount": 26
42 * }
43 * },
44 * "pricing": {
45 * "subscription": {
46 * "cycleDuration": {
47 * "count": 1,
48 * "unit": "WEEK"
49 * },
50 * "cycleCount": 26
51 * },
52 * "prices": [
53 * {
54 * "duration": {
55 * "cycleFrom": 1,
56 * "numberOfCycles": 26
57 * },
58 * "price": {
59 * "subtotal": "2",
60 * "discount": "0",
61 * "total": "2",
62 * "currency": "USD"
63 * }
64 * }
65 * ]
66 * },
67 * "type": "ONLINE",
68 * "orderMethod": "UNKNOWN",
69 * "status": "DRAFT",
70 * "autoRenewCanceled": false,
71 * "lastPaymentStatus": "UNPAID",
72 * "startDate": "2022-08-01T11:00:00.000Z",
73 * "endDate": "2023-01-30T11:00:00.000Z",
74 * "pausePeriods": [],
75 * "earliestEndDate": "2023-01-30T11:00:00.000Z",
76 * "planName": "Cooking for Kids",
77 * "planDescription": "Get easy-to-make recipes that kids can prepare on their own!",
78 * "planPrice": "2",
79 * "_createdDate": "2022-07-13T04:37:11.197Z",
80 * "_updatedDate": "2022-07-13T04:37:11.197Z"
81 * }
82 */
Create an online order and purchase it with Wix Pay

This example demonstrates how you can start an online order with the wix-pricing-plans-backend createOnlineOrder() function and then send the payment ID (wixPayOrderId) to the frontend Wix Pay startPayment() function to facilitate payment.

Copy Code
1/**********************************
2 * Backend code - checkout.web.js *
3 *********************************/
4import { Permissions, webMethod } from 'wix-web-module';
5import { checkout } from 'wix-pricing-plans-backend';
6
7export const myCreateOnlineOrderFunction = webMethod(Permissions.Anyone, async (planId, startDate) => {
8 try {
9 const order = await checkout.createOnlineOrder(planId, startDate)
10 return order;
11 } catch (error) {
12 console.error(error);
13 // Handle the error
14 }
15});
16
17/* Returns a Promise that resolves to an
18 * `order` object with a `"DRAFT"`
19 * status. In the object, there is a
20 * `wixPayOrderId` property you can use to
21 * complete the purchase.
22 */
23
24/*************
25 * Page code *
26 *************/
27
28import { myCreateOnlineOrderFunction } from 'backend/checkout.web';
29import wixPayFrontend from 'wix-pay-frontend';
30
31// ...
32
33const planId = $w('#planId').value;
34const startDate = new Date('July 22, 2022 11:00:00');
35
36$w('#submitButton').onClick(async () => {
37 try {
38 const order = await myCreateOnlineOrderFunction(planId, startDate);
39 const result = await wixPayFrontend.startPayment(order.wixPayOrderId);
40 if (result.status === 'Successful') {
41 console.log('Successfully Ordered');
42 // Handle payment success
43 } else if (result.status === 'Failed to Order') {
44 console.log('Failed');
45 // Handle payment failure
46 } else if (result.status === 'Order Pending') {
47 console.log('Pending');
48 // Handle payment pending
49 } else if (result.status === 'Order Cancelled') {
50 console.log('Cancelled');
51 // Handle user closing the payment panel
52 // without paying
53 } else {
54 console.log('Failed to Create Order');
55 // Handle any remaining possibilities
56 }
57 } catch(error) {
58 // Handle the error
59 }
60});
61
62/* Returns a Promise that resolves to
63 * the created payment.
64 */
A full order plan scenario including a collection

This example demonstrates how to create an order and save its details in a collection after an event fires.

The code assumes:

  • An Orders collection with the following fields: _id, planId, planName, nickname, and status
  • The Members app is installed on the site, including the Members/PublicData collection
  • The Pricing Plans app is installed on the site, including the PaidPlans/Plans collection
  • A backend code file exists called process-orders.jsw
  • A backend events file exists called events.js

The OrderCreated event is fired in response to an order being created. The initial order creation might be initiated in several ways, such as by a button click on the page or by an external event request sent by an HTTP function call. The order creation is routed to backend code.

In this example, when the OrderCreated event is fired:

  • The myInsertOrderFunction() function is called, with the order object extracted from the event object
  • The myInsertOrderFunction() function calls a getMember() function to gets details about the member ordering the plan
  • The myInsertOrderFunction() function calls the Wix Data insert() function to add order and member details into the Orders collection

Copy Code
1/***********************************************
2 * For demonstration purposes, the *
3 * following myCreateOnlineOrderFunction() *
4 * triggers the onOrderCreated event. You *
5 * can put this code in a backend jsw file *
6 * or use a different method for triggering *
7 * the event such as with http functions. *
8 ***********************************************/
9
10import { checkout } from 'wix-pricing-plans-backend';
11
12export const myCreateOnlineOrderFunction = webMethod(Permissions.Anyone, (planId) => {
13 return checkout.createOnlineOrder(planId);
14});
15
16/*******************************
17 * Backend code - events.js *
18 *******************************/
19
20import { myInsertNewOrderFunction } from 'backend/process-orders.web';
21
22export function wixPricingPlans_onOrderCreated(event) {
23 myInsertNewOrderFunction(event.entity);
24}
25
26/****************************************
27 * Backend code - process-orders.web.js *
28 ***************************************/
29import { Permissions, webMethod } from 'wix-web-module';
30import wixData from 'wix-data';
31
32export const myInsertOrderFunction = webMethod(Permissions.Anyone, async (order) => {
33
34 const member = await getMember(order.buyer.memberId);
35 const data = ({
36 _id: order.id,
37 planId: order.planId,
38 planName: order.planName,
39 status: order.status,
40 nickname: member.nickname
41 });
42
43 wixData.insert('Orders', data)
44 .then(() => {
45 console.log('Inserted successfully', data);
46 })
47 .catch(() => {
48 console.error('Failed to insert', data);
49 });
50});
51
52// Gets member details to associate with the order
53async function getMember(memberId) {
54 try {
55 return wixData.get('Members/PublicData', memberId)
56 } catch (error) {
57 console.error('Failed to fetch member by ID', memberId, error);
58 };
59}