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 { checkout } from 'wix-pricing-plans-backend';
2
3// Sample planId value: 'aef93bb6-aaaa-4965-966e-bd68dd2a1cc2'
4
5export async function myCreateOnlineOrderFunction(planId) {
6 try {
7 const order = await checkout.createOnlineOrder(planId);
8 const orderId = order._id;
9 const plan = order.planName;
10 const orderType = order.type;
11
12 return order;
13 } catch (error) {
14 console.error(error);
15 }
16}
17
18/* Promise resolves to:
19 *
20 * {
21 * "_id": "73a646b3-6aff-4fc6-a18b-9e30cf725aa5",
22 * "planId": "aef93bb6-aaaa-4965-966e-bd68dd2a1cc2",
23 * "subscriptionId": "f713e998-8344-4791-8c54-00d578746ff4",
24 * "wixPayOrderId": "6a5c0cfc-490b-4120-a704-c49facae1172",
25 * "buyer": {
26 * "memberId": "ea3d74df-b7dc-4ca1-a7c9-c416b9017a86",
27 * "contactId": "ea3d74df-b7dc-4ca1-a7c9-c416b9017a86"
28 * },
29 * "priceDetails": {
30 * "subtotal": "2",
31 * "discount": "0",
32 * "total": "2",
33 * "planPrice": "2",
34 * "currency": "USD",
35 * "subscription": {
36 * "cycleDuration": {
37 * "count": 1,
38 * "unit": "WEEK"
39 * },
40 * "cycleCount": 26
41 * }
42 * },
43 * "pricing": {
44 * "subscription": {
45 * "cycleDuration": {
46 * "count": 1,
47 * "unit": "WEEK"
48 * },
49 * "cycleCount": 26
50 * },
51 * "prices": [
52 * {
53 * "duration": {
54 * "cycleFrom": 1,
55 * "numberOfCycles": 26
56 * },
57 * "price": {
58 * "subtotal": "2",
59 * "discount": "0",
60 * "total": "2",
61 * "currency": "USD"
62 * }
63 * }
64 * ]
65 * },
66 * "type": "ONLINE",
67 * "orderMethod": "UNKNOWN",
68 * "status": "DRAFT",
69 * "autoRenewCanceled": false,
70 * "lastPaymentStatus": "UNPAID",
71 * "startDate": "2022-08-01T11:00:00.000Z",
72 * "endDate": "2023-01-30T11:00:00.000Z",
73 * "pausePeriods": [],
74 * "earliestEndDate": "2023-01-30T11:00:00.000Z",
75 * "planName": "Cooking for Kids",
76 * "planDescription": "Get easy-to-make recipes that kids can prepare on their own!",
77 * "planPrice": "2",
78 * "_createdDate": "2022-07-13T04:37:11.197Z",
79 * "_updatedDate": "2022-07-13T04:37:11.197Z"
80 * }
81 */
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.jsw *
3 *******************************/
4import { checkout } from 'wix-pricing-plans-backend';
5
6export async function myCreateOnlineOrderFunction(planId, startDate) {
7 try {
8 const order = await checkout.createOnlineOrder(planId, startDate)
9 return order;
10 } catch (error) {
11 console.error(error);
12 // Handle the error
13 }
14}
15
16/* Returns a Promise that resolves to an
17 * `order` object with a `"DRAFT"`
18 * status. In the object, there is a
19 * `wixPayOrderId` property you can use to
20 * complete the purchase.
21 */
22
23/*************
24 * Page code *
25 *************/
26
27import {myCreateOnlineOrderFunction} from 'backend/checkout';
28import wixPayFrontend from 'wix-pay-frontend';
29
30// ...
31
32const planId = $w('#planId').value;
33const startDate = new Date('July 22, 2022 11:00:00');
34
35$w('#submitButton').onClick(async () => {
36 try {
37 const order = await myCreateOnlineOrderFunction(planId, startDate);
38 const result = await wixPayFrontend.startPayment(order.wixPayOrderId);
39 if (result.status === 'Successful') {
40 console.log('Successfully Ordered');
41 // Handle payment success
42 } else if (result.status === 'Failed to Order') {
43 console.log('Failed');
44 // Handle payment failure
45 } else if (result.status === 'Order Pending') {
46 console.log('Pending');
47 // Handle payment pending
48 } else if (result.status === 'Order Cancelled') {
49 console.log('Cancelled');
50 // Handle user closing the payment panel
51 // without paying
52 } else {
53 console.log('Failed to Create Order');
54 // Handle any remaining possibilities
55 }
56 } catch(error) {
57 // Handle the error
58 }
59});
60
61/* Returns a Promise that resolves to
62 * the created payment.
63 */
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 function myCreateOnlineOrderFunction(planId) {
13 return checkout.createOnlineOrder(planId);
14}
15
16/*******************************
17 * Backend code - events.js *
18 *******************************/
19
20 import { myInsertNewOrderFunction } from 'backend/process-orders'
21
22 export function wixPricingPlans_onOrderCreated(event) {
23 myInsertNewOrderFunction(event.entity);
24}
25
26/*************************************
27 * Backend code - process-orders.jsw *
28 *************************************/
29 import wixData from 'wix-data';
30
31 export async function myInsertOrderFunction(order) {
32
33 const member = await getMember(order.buyer.memberId);
34 const data = ({
35 _id: order.id,
36 planId: order.planId,
37 planName: order.planName,
38 status: order.status,
39 nickname: member.nickname
40 });
41
42 wixData.insert('Orders', data)
43 .then(() => {
44 console.log('Inserted successfully', data);
45 })
46 .catch(() => {
47 console.error('Failed to insert', data);
48 });
49 }
50
51 // Gets member details to associate with the order
52 async function getMember(memberId) {
53 try {
54 return wixData.get('Members/PublicData', memberId)
55 } catch (error) {
56 console.error('Failed to fetch member by ID', memberId, error);
57 };
58 }