csharp
java
javascript
php
python
ruby
typescript

webhook

/webhook

Webhooks are asynchronous outbound notifications of events to an external server. For a complete description of Webhooks, please see:

Topics -> Webhooks

The Webhook resource allows for programmatic configuration of Webhooks on an UltraCart account. This document only covers the configuration of webhooks. Please consult each individual resource for details on the webhooks that a particular resource supports.

An example usage of this webhook resource is a Wordpress plugin creating a webhook so that item related events trigger webhook notifications to the Wordpress server so it can update it's local cache.

Delete a webhook by URL

Permissions:
  • webhook_write

Consumes: application/json
Produces: application/json
delete
/webhook/webhooks

Delete a webhook based upon the URL on the webhook_url matching an existing webhook.

SDK Function Name: deleteWebhookByUrl

Parameters
Parameter Description Location Data Type Required
webhook Webhook to delete body Webhook required
Responses
Status Code Reason Response Model
200
Successful response WebhookResponse
400
Bad Request 400
401
Unauthorized 401
410
Authorized Application Disabled 410
429
Too Many Requests 429
500
Server Side 500
using System;
using com.ultracart.admin.v2.Api;
using com.ultracart.admin.v2.Model;

namespace SdkSample.webhook
{
    public class DeleteWebhookByUrl
    {
        public static void Execute()
        {
            /*
             * This method can be confusing due to its payload. The method does indeed delete a webhook by url, but you need to
             * pass a webhook object in as the payload. However, only the url is used. UltraCart does this to avoid any confusion
             * with the rest url versus the webhook url.
             *
             * To use:
             * Get your webhook url.
             * Create a Webhook object.
             * Set the Webhook url property.
             * Pass the webhook to deleteWebhookByUrl()
             *
             * Returns status code 204 (No Content) on success
             */

            WebhookApi webhookApi = new WebhookApi(Constants.ApiKey);

            string webhookUrl = "https://www.mywebiste.com/page/to/call/when/this/webhook/fires.php";
            Webhook webhook = new Webhook();
            webhook.WebhookUrl = webhookUrl;

            webhookApi.DeleteWebhookByUrl(webhook);
        }
    }
}
package webhook;

import com.ultracart.admin.v2.WebhookApi;
import com.ultracart.admin.v2.models.*;
import com.ultracart.admin.v2.util.ApiException;
import common.Constants;

public class DeleteWebhookByUrl {
   public static void execute() throws ApiException {
       /*
        * This method can be confusing due to its payload. The method does indeed delete a webhook by url, but you need to
        * pass a webhook object in as the payload. However, only the url is used. UltraCart does this to avoid any confusion
        * with the rest url versus the webhook url.
        *
        * To use:
        * Get your webhook url.
        * Create a Webhook object.
        * Set the Webhook url property.
        * Pass the webhook to deleteWebhookByUrl()
        *
        * Returns status code 204 (No Content) on success
        */

       WebhookApi webhookApi = new WebhookApi(Constants.API_KEY);

       String webhookUrl = "https://www.mywebiste.com/page/to/call/when/this/webhook/fires.php";
       Webhook webhook = new Webhook();
       webhook.setWebhookUrl(webhookUrl);

       webhookApi.deleteWebhookByUrl(webhook);
   }
}
// Import API and UltraCart types
import {webhookApi} from '../api.js';

// Namespace-like structure using a class
export class DeleteWebhookByUrl {
    static async execute() {
        /*
         * This method can be confusing due to its payload. The method does indeed delete a webhook by url, but you need to
         * pass a webhook object in as the payload. However, only the url is used. UltraCart does this to avoid any confusion
         * with the rest url versus the webhook url.
         *
         * To use:
         * Get your webhook url.
         * Create a Webhook object.
         * Set the Webhook url property.
         * Pass the webhook to deleteWebhookByUrl()
         *
         * Returns status code 204 (No Content) on success
         */
        try {
            const webhookUrl = "https://www.mywebiste.com/page/to/call/when/this/webhook/fires.php";
            const webhook = {
                webhook_url: webhookUrl,
            };

            // UltraCart API call with parameter as an anonymous object
            await new Promise((resolve, reject) => {
                webhookApi.deleteWebhookByUrl(webhook, function (error, data, response) {
                    if (error) {
                        reject(error);
                    } else {
                        resolve(data, response);
                    }
                });
            });

            console.log(`Webhook with URL ${webhookUrl} deleted successfully`);
        } catch (ex) {
            console.log(`Error: ${ex.message}`);
            console.log(ex.stack);
        }
    }
}
<?php

ini_set('display_errors', 1);

/*

This method can be confusing due to its payload.  The method does indeed delete a webhook by url, but you need to
pass a webhook object in as the payload.  However, only the url is used.  UltraCart does this to avoid any confusion
with the rest url versus the webhook url.

To use:
Get your webhook url.
Create a Webhook object.
Set the Webhook url property.
Pass the webhook to deleteWebhookByUrl()

Returns status code 204 (No Content) on success

*/


use ultracart\v2\api\WebhookApi;
use ultracart\v2\models\Webhook;

require_once '../vendor/autoload.php';
require_once '../constants.php';

$webhook_api = WebhookApi::usingApiKey(Constants::API_KEY);

$webhook_url = "https://www.mywebiste.com/page/to/call/when/this/webhook/fires.php";
$webhook = new Webhook();
$webhook->setWebhookUrl($webhook_url);

$webhook_api->deleteWebhookByUrl($webhook);

"""
This method can be confusing due to its payload.  The method does indeed delete a webhook by url, but you need to
pass a webhook object in as the payload.  However, only the url is used.  UltraCart does this to avoid any confusion
with the rest url versus the webhook url.

To use:
Get your webhook url.
Create a Webhook object.
Set the Webhook url property.
Pass the webhook to deleteWebhookByUrl()

Returns status code 204 (No Content) on success
"""

from ultracart.apis import WebhookApi
from ultracart.models import Webhook
from samples import api_client

# Create Webhook API instance
webhook_api = WebhookApi(api_client())

# Webhook URL to delete
webhook_url = "https://www.mywebiste.com/page/to/call/when/this/webhook/fires.php"

# Create Webhook object with the URL
webhook = Webhook(webhook_url=webhook_url)

# Delete webhook by URL
webhook_api.delete_webhook_by_url(webhook)
require 'ultracart_api'
require_relative '../constants'

# This method can be confusing due to its payload.  The method does indeed delete a webhook by url, but you need to
# pass a webhook object in as the payload.  However, only the url is used.  UltraCart does this to avoid any confusion
# with the rest url versus the webhook url.
#
# To use:
# Get your webhook url.
# Create a Webhook object.
# Set the Webhook url property.
# Pass the webhook to deleteWebhookByUrl()
#
# Returns status code 204 (No Content) on success

webhook_api = UltracartClient::WebhookApi.new_using_api_key(Constants::API_KEY)

webhook_url = "https://www.mywebiste.com/page/to/call/when/this/webhook/fires.php"
webhook = UltracartClient::Webhook.new
webhook.webhook_url = webhook_url

webhook_api.delete_webhook_by_url(webhook)
// Import API and UltraCart types
import { webhookApi } from '../api';
import { Webhook } from 'ultracart_rest_api_v2_typescript';

// Namespace-like structure using a class
export class DeleteWebhookByUrl {
  public static async execute(): Promise<void> {
    /*
     * This method can be confusing due to its payload. The method does indeed delete a webhook by url, but you need to
     * pass a webhook object in as the payload. However, only the url is used. UltraCart does this to avoid any confusion
     * with the rest url versus the webhook url.
     *
     * To use:
     * Get your webhook url.
     * Create a Webhook object.
     * Set the Webhook url property.
     * Pass the webhook to deleteWebhookByUrl()
     *
     * Returns status code 204 (No Content) on success
     */
    try {
      const webhookUrl = "https://www.mywebiste.com/page/to/call/when/this/webhook/fires.php";
      const webhook: Webhook = {
        webhook_url: webhookUrl,
      };

      // UltraCart API call with parameter as an anonymous interface
      await webhookApi.deleteWebhookByUrl({
        webhook: webhook,
      });

      console.log(`Webhook with URL ${webhookUrl} deleted successfully`);
    } catch (ex) {
      console.log(`Error: ${(ex as Error).message}`);
      console.log((ex as Error).stack);
    }
  }
}

Retrieve webhooks

Permissions:
  • webhook_read

Produces: application/json
get
/webhook/webhooks

Retrieves the webhooks associated with this application.

SDK Function Name: getWebhooks

Parameters
Parameter Description Location Data Type Required
_limit The maximum number of records to return on this one API call.
Default: 100
query integer optional
_offset Pagination of the record set. Offset is a zero based index.
Default: 0
query integer optional
_sort The sort order of the webhooks. See documentation for examples query string optional
_placeholders Whether or not placeholder values should be returned in the result. Useful for UIs that consume this REST API. query boolean optional
Responses
Status Code Reason Response Model
200
Successful response WebhooksResponse
400
Bad Request 400
401
Unauthorized 401
410
Authorized Application Disabled 410
429
Too Many Requests 429
500
Server Side 500
using System;
using System.Collections.Generic;
using com.ultracart.admin.v2.Api;
using com.ultracart.admin.v2.Client;
using com.ultracart.admin.v2.Model;

namespace SdkSample.webhook
{
    public class GetWebhooks
    {
        /*
         * This example illustrates how to retrieve all webhooks.
         */

        /// <summary>
        /// Gets a chunk of webhooks
        /// </summary>
        /// <param name="webhookApi">The webhook API instance</param>
        /// <param name="offset">Offset for pagination</param>
        /// <param name="limit">Maximum number of records to return</param>
        /// <returns>List of webhooks</returns>
        /// <exception cref="ApiException">Thrown when API call fails</exception>
        private static List<Webhook> GetWebhookChunk(WebhookApi webhookApi, int offset, int limit)
        {
            string sort = null; // default sorting is webhook_url, disabled, and those are also the two choices for sorting.
            bool? placeholders = null;  // useful for UI displays, but not needed here.
            // Pay attention to whether limit or offset comes first in the method signature. UltraCart is not consistent with their ordering.
            WebhooksResponse apiResponse = webhookApi.GetWebhooks(limit, offset, sort, placeholders);

            if (apiResponse.Webhooks != null)
            {
                return apiResponse.Webhooks;
            }
            return new List<Webhook>();
        }

        public static void Execute()
        {
            WebhookApi webhookApi = new WebhookApi(Constants.ApiKey);
            
            List<Webhook> webhooks = new List<Webhook>();

            int iteration = 1;
            int offset = 0;
            int limit = 200;
            bool moreRecordsToFetch = true;

            try
            {
                while (moreRecordsToFetch)
                {
                    Console.WriteLine("executing iteration " + iteration);

                    List<Webhook> chunkOfWebhooks = GetWebhookChunk(webhookApi, offset, limit);
                    webhooks.AddRange(chunkOfWebhooks);
                    offset = offset + limit;
                    moreRecordsToFetch = chunkOfWebhooks.Count == limit;
                    iteration++;
                }
            }
            catch (ApiException e)
            {
                Console.WriteLine("ApiException occurred on iteration " + iteration);
                Console.WriteLine(e.ToString());
                Environment.Exit(1);
            }

            // this will be verbose...
            foreach (Webhook webhook in webhooks)
            {
                Console.WriteLine(webhook.ToString());
            }
        }
    }
}
package webhook;

import com.ultracart.admin.v2.WebhookApi;
import com.ultracart.admin.v2.models.Webhook;
import com.ultracart.admin.v2.models.WebhooksResponse;
import com.ultracart.admin.v2.util.ApiException;
import common.Constants;

import java.util.ArrayList;
import java.util.List;

public class GetWebhooks {
  /*
   * This example illustrates how to retrieve all webhooks.
   */

  /**
   * Gets a chunk of webhooks
   *
   * @param webhookApi The webhook API instance
   * @param offset     Offset for pagination
   * @param limit      Maximum number of records to return
   * @return List of webhooks
   * @throws ApiException Thrown when API call fails
   */
  private static List<Webhook> getWebhookChunk(WebhookApi webhookApi, int offset, int limit) throws ApiException {
    String sort = null; // default sorting is webhook_url, disabled, and those are also the two choices for sorting.
    Boolean placeholders = null;  // useful for UI displays, but not needed here.
    // Pay attention to whether limit or offset comes first in the method signature. UltraCart is not consistent with their ordering.
    WebhooksResponse apiResponse = webhookApi.getWebhooks(limit, offset, sort, placeholders);

    if (apiResponse.getWebhooks() != null) {
      return apiResponse.getWebhooks();
    }
    return new ArrayList<>();
  }

  public static void execute() {
    WebhookApi webhookApi = new WebhookApi(Constants.API_KEY);

    List<Webhook> webhooks = new ArrayList<>();

    int iteration = 1;
    int offset = 0;
    int limit = 200;
    boolean moreRecordsToFetch = true;

    try {
      while (moreRecordsToFetch) {
        System.out.println("executing iteration " + iteration);

        List<Webhook> chunkOfWebhooks = getWebhookChunk(webhookApi, offset, limit);
        webhooks.addAll(chunkOfWebhooks);
        offset = offset + limit;
        moreRecordsToFetch = chunkOfWebhooks.size() == limit;
        iteration++;
      }
    } catch (ApiException e) {
      System.out.println("ApiException occurred on iteration " + iteration);
      System.out.println(e.toString());
      System.exit(1);
    }

    // this will be verbose...
    for (Webhook webhook : webhooks) {
      System.out.println(webhook.toString());
    }
  }
}
import {webhookApi} from '../api.js';

/**
 * This example illustrates how to retrieve all webhooks.
 */
export class GetWebhooks {
    /**
     * Gets a chunk of webhooks
     * @param webhookApi The webhook API instance
     * @param offset Offset for pagination
     * @param limit Maximum number of records to return
     * @returns List of webhooks
     * @throws ApiException Thrown when API call fails
     */
    static async getWebhookChunk(webhookApi, offset, limit) {
        const sort = null; // default sorting is webhook_url, disabled, and those are also the two choices for sorting.
        const placeholders = null;  // useful for UI displays, but not needed here.

        // Pay attention to whether limit or offset comes first in the method signature. UltraCart is not consistent with their ordering.
        const apiResponse = await new Promise((resolve, reject) => {
            webhookApi.getWebhooks({
                _limit: limit,
                _offset: offset,
                _sort: sort,
                _placeholders: placeholders
            }, function (error, data, response) {
                if (error) {
                    reject(error);
                } else {
                    resolve(data, response);
                }
            });
        });

        return apiResponse.webhooks || [];
    }

    /**
     * Execute method to fetch and process webhooks
     */
    static async execute() {
        const webhooks = [];

        let iteration = 1;
        let offset = 0;
        const limit = 200;
        let moreRecordsToFetch = true;

        try {
            while (moreRecordsToFetch) {
                console.log(`executing iteration ${iteration}`);

                const chunkOfWebhooks = await GetWebhooks.getWebhookChunk(webhookApi, offset, limit);
                webhooks.push(...chunkOfWebhooks);
                offset = offset + limit;
                moreRecordsToFetch = chunkOfWebhooks.length === limit;
                iteration++;
            }
        } catch (e) {
            console.error(`ApiException occurred on iteration ${iteration}`);
            console.error(e);
            process.exit(1);
        }

        // this will be verbose...
        webhooks.forEach(webhook => {
            console.log(webhook.toString());
        });
    }
}

// Optional: If you want to run this directly
if (require.main === module) {
    GetWebhooks.execute().catch(console.error);
}
<?php

set_time_limit(3000); // pulling all records could take a long time.
ini_set('max_execution_time', 3000);
ini_set('display_errors', 1);

/*
 * This example illustrates how to retrieve all webhooks.
 */

use ultracart\v2\api\WebhookApi;
use ultracart\v2\ApiException;

require_once '../vendor/autoload.php';
require_once '../samples.php';


$webhook_api = WebhookApi::usingApiKey(Constants::API_KEY);


/**
 * @throws ApiException
 */
function getWebhookChunk(WebhookApi $webhook_api, int $offset, int $limit): array
{

    $_sort = null; // default sorting is webhook_url, disabled, and those are also the two choices for sorting.
    $_placeholders = null;  // useful for UI displays, but not needed here.
    // Pay attention to whether limit or offset comes first in the method signature.  UltraCart is not consistent with their ordering.
    $api_response = $webhook_api->getWebhooks($limit, $offset, $_sort, $_placeholders);

    if ($api_response->getWebhooks() != null) {
        return $api_response->getWebhooks();
    }
    return [];
}

$webhooks = [];

$iteration = 1;
$offset = 0;
$limit = 200;
$more_records_to_fetch = true;

try {
    while ($more_records_to_fetch) {

        echo "executing iteration " . $iteration . '<br>';

        $chunk_of_webhooks = getWebhookChunk($webhook_api, $offset, $limit);
        $orders = array_merge($webhooks, $chunk_of_webhooks);
        $offset = $offset + $limit;
        $more_records_to_fetch = count($chunk_of_webhooks) == $limit;
        $iteration++;
    }
} catch (ApiException $e) {
    echo 'ApiException occurred on iteration ' . $iteration;
    var_dump($e);
    die(1);
}


// this will be verbose...
var_dump($webhooks);
"""
This example illustrates how to retrieve all webhooks.
"""

from ultracart.apis import WebhookApi
from ultracart.exceptions import ApiException
from samples import api_client


def get_webhook_chunk(webhook_api, offset, limit):
    """Retrieve a chunk of webhooks."""
    _sort = None  # default sorting is webhook_url, disabled
    _placeholders = None  # useful for UI displays, but not needed here

    api_response = webhook_api.get_webhooks(limit=limit, offset=offset, sort=_sort, placeholders=_placeholders)
    return api_response.webhooks or []


def retrieve_all_webhooks():
    """Retrieve all webhooks in chunks."""
    webhook_api = WebhookApi(api_client())

    webhooks = []
    iteration = 1
    offset = 0
    limit = 200

    try:
        while True:
            print(f"executing iteration {iteration}")

            chunk_of_webhooks = get_webhook_chunk(webhook_api, offset, limit)
            webhooks.extend(chunk_of_webhooks)

            offset += limit
            if len(chunk_of_webhooks) < limit:
                break

            iteration += 1

    except ApiException as e:
        print(f'ApiException occurred on iteration {iteration}')
        print(e)
        return None

    return webhooks


# Retrieve and print webhooks
all_webhooks = retrieve_all_webhooks()
if all_webhooks is not None:
    print(all_webhooks)
require 'ultracart_api'
require_relative '../constants'

# This example illustrates how to retrieve all webhooks.

webhook_api = UltracartClient::WebhookApi.new_using_api_key(Constants::API_KEY)

def get_webhook_chunk(webhook_api, offset, limit)
  _sort = nil # default sorting is webhook_url, disabled, and those are also the two choices for sorting.
  _placeholders = nil  # useful for UI displays, but not needed here.
  # Pay attention to whether limit or offset comes first in the method signature.  UltraCart is not consistent with their ordering.
  opts = {
    '_sort' => _sort,
    '_placeholders' => _placeholders
  }
  api_response = webhook_api.get_webhooks(limit, offset, opts)

  return api_response.webhooks if api_response.webhooks
  []
end

webhooks = []

iteration = 1
offset = 0
limit = 200
more_records_to_fetch = true

begin
  while more_records_to_fetch
    puts "executing iteration #{iteration}"

    chunk_of_webhooks = get_webhook_chunk(webhook_api, offset, limit)
    webhooks.concat(chunk_of_webhooks)
    offset = offset + limit
    more_records_to_fetch = chunk_of_webhooks.length == limit
    iteration += 1
  end
rescue UltracartClient::ApiError => e
  puts "ApiError occurred on iteration #{iteration}"
  puts e.inspect
  exit 1
end

# this will be verbose...
puts webhooks.inspect
import { webhookApi } from '../api';
import { Webhook, WebhooksResponse } from 'ultracart_rest_api_v2_typescript';

/**
 * This example illustrates how to retrieve all webhooks.
 */
export class GetWebhooks {
    /**
     * Gets a chunk of webhooks
     * @param webhookApi The webhook API instance
     * @param offset Offset for pagination
     * @param limit Maximum number of records to return
     * @returns List of webhooks
     * @throws ApiException Thrown when API call fails
     */
    private static async getWebhookChunk(webhookApi: any, offset: number, limit: number): Promise<Webhook[]> {
        const sort: string | null = null; // default sorting is webhook_url, disabled, and those are also the two choices for sorting.
        const placeholders: boolean | null = null;  // useful for UI displays, but not needed here.

        // Pay attention to whether limit or offset comes first in the method signature. UltraCart is not consistent with their ordering.
        const apiResponse: WebhooksResponse = await webhookApi.getWebhooks(limit, offset, sort, placeholders);

        return apiResponse.webhooks || [];
    }

    /**
     * Execute method to fetch and process webhooks
     */
    public static async execute(): Promise<void> {
        const webhooks: Webhook[] = [];

        let iteration = 1;
        let offset = 0;
        const limit = 200;
        let moreRecordsToFetch = true;

        try {
            while (moreRecordsToFetch) {
                console.log(`executing iteration ${iteration}`);

                const chunkOfWebhooks = await GetWebhooks.getWebhookChunk(webhookApi, offset, limit);
                webhooks.push(...chunkOfWebhooks);
                offset = offset + limit;
                moreRecordsToFetch = chunkOfWebhooks.length === limit;
                iteration++;
            }
        } catch (e) {
            console.error(`ApiException occurred on iteration ${iteration}`);
            console.error(e);
            process.exit(1);
        }

        // this will be verbose...
        webhooks.forEach(webhook => {
            console.log(webhook.toString());
        });
    }
}

// Optional: If you want to run this directly
if (require.main === module) {
    GetWebhooks.execute().catch(console.error);
}

Add a webhook

Permissions:
  • webhook_write

Consumes: application/json
Produces: application/json
post
/webhook/webhooks

Adds a new webhook on the account. If you add a new webhook with the authentication_type set to basic, but do not specify the basic_username and basic_password, UltraCart will automatically generate random ones and return them. This allows your application to have simpler logic on the setup of a secure webhook.

SDK Function Name: insertWebhook

Parameters
Parameter Description Location Data Type Required
webhook Webhook to create body Webhook required
_placeholders Whether or not placeholder values should be returned in the result. Useful for UIs that consume this REST API. query boolean optional
Responses
Status Code Reason Response Model
200
Successful response WebhookResponse
400
Bad Request 400
401
Unauthorized 401
410
Authorized Application Disabled 410
429
Too Many Requests 429
500
Server Side 500
using System;
using System.Collections.Generic;
using com.ultracart.admin.v2.Api;
using com.ultracart.admin.v2.Model;

namespace SdkSample.webhook
{
    public class InsertWebhook
    {
        public static void Execute()
        {
            /*
             * Adds a new webhook on the account.  If you add a new webhook with the authentication_type set to basic, but
             * do not specify the basic_username and basic_password, UltraCart will automatically generate random ones and
             * return them.  This allows your application to have simpler logic on the setup of a secure webhook.
             * 
             * Event Category      Event Name                      Description
             * auto_order	        auto_order_cancel	            Fired when an auto order is canceled
             * auto_order	        auto_order_create	            Fired when an auto order is created
             * auto_order	        auto_order_decline	            Fired when an auto order is declined
             * auto_order	        auto_order_disable	            Fired when an auto order is disabled
             * auto_order	        auto_order_preshipment          Fired when an auto order generates a new pre-shipment notice
             * auto_order	        auto_order_rebill	            Fired when an auto order is rebilled
             * auto_order	        auto_order_update	            Fired when an auto order is updated
             * chargeback	        chargeback_create	            Fired when a chargeback is created
             * chargeback	        chargeback_delete	            Fired when a chargeback is deleted
             * chargeback	        chargeback_update	            Fired when a chargeback is updated
             * checkout	            checkout_cart_abandon	        Fired when a cart is abandoned
             * checkout	            checkout_cart_send_return_email Fired when a return email should be sent to a customer
             * customer	            customer_create                 Fired when a customer profile is created.
             * customer	            customer_delete                 Fired when a customer profile is deleted.
             * customer	            customer_update                 Fired when a customer profile is updated.
             * fulfillment	        fulfillment_hold                Fired when an order is held for review
             * fulfillment	        fulfillment_transmit            Fired to transmit an order to the fulfillment house
             * item	                item_create                     Fired when a new item is created.
             * item	                item_delete                     Fired when an item is deleted.
             * item	                item_update                     Fired when an item is updated.
             * order	            order_abandon_recovery          Fired when a previously abandoned cart turns into an order
             * order	            order_create                    Fired when an order is placed
             * order	            order_delete                    Fired when an order is deleted
             * order	            order_payment_failed            Fired when a payment fails
             * order	            order_payment_process           Fired when a payment is processed
             * order	            order_refund                    Fired when an order is refunded
             * order	            order_reject                    Fired when an order is rejected
             * order	            order_s3_invoice                Fired when an invoice PDF is stored in S3 bucket
             * order	            order_s3_packing_slip           Fired when a packing slip PDF is stored in an S3 bucket
             * order	            order_ship                      Fired when an order is shipped
             * order	            order_ship_delivered            Fired when an order has a shipment delivered
             * order	            order_ship_expected             Fired when an order has an expected delivery date
             * order	            order_ship_out_for_delivery     Fired when an order has a shipment out for delivery
             * order	            order_stage_change              Fired when an order stage changes
             * order	            order_update                    Fired when an order is edited
             * storefront	        screen_recording                Fired when a screen recording is created
             * user	                user_create                     Fired when a user is created
             * user	                user_delete                     Fired when a user is deleted
             * user	                user_login                      Fired when a user logs in
             * user	                user_update                     Fired when a user is updated
             * workflow_task	    workflow_task_create            Fired when a workflow task is created
             * workflow_task	    workflow_task_delete            Fired when a workflow task is deleted
             * workflow_task	    workflow_task_update            Fired when a workflow task is updated
             * 
             * Note: Each event uses the same expansions as the event category.  To see a list of possible expansion values,
             * visit www.ultracart.com/api/. Order Expansions (https://www.ultracart.com/api/#resource_order.html) are listed
             * below because most webhooks are for order events.
             * Order Expansion:
             * affiliate	        auto_order          billing             checkout
             * affiliate.ledger	    channel_partner	    coupon	            customer_profile
             * digital_order	    edi	                fraud_score	        gift
             * gift_certificate	    internal	        item	            linked_shipment
             * marketing	        payment	            payment.transaction point_of_sale
             * quote	            salesforce	        shipping	        shipping.tracking_number_details
             * summary	            taxes	            utms
             * 
             * Note: The WebhookEventSubscription.event_ruler field is processed with the AWS Event Ruler library to filter down
             * events to just what you want.  If you wish to employ a ruler filter, see https://github.com/aws/event-ruler
             * for syntax examples.  You'll need to apply the aws syntax against the UltraCart object models.  Contact UltraCart
             * support if you need assistance creating the proper ruler expression.
             * 
             * 
             * Possible Errors:
             */

            WebhookApi webhookApi = new WebhookApi(Constants.ApiKey);

            Webhook webhook = new Webhook();
            webhook.WebhookUrl = "https://www.mywebiste.com/page/to/call/when/this/webhook/fires.php";  // Must be HTTPS if customer related information is being delivered.
            webhook.AuthenticationType = Webhook.AuthenticationTypeEnum.Basic;  // "basic","none","api user","aws iam"
            webhook.BasicUsername = "george";
            webhook.BasicPassword = "LlamaLlamaRedPajama";
            webhook.MaximumEvents = 10;
            webhook.MaximumSize = 5242880; // 5 MB is pretty chunky.
            webhook.ApiVersion = Webhook.ApiVersionEnum._20170301; // this is our only API version so far.
            webhook.CompressEvents = true; // compress events with gzip, then base64 encode them as a string.

            WebhookEventSubscription eventSub1 = new WebhookEventSubscription();
            eventSub1.EventName = "order_create";
            eventSub1.EventDescription = "when an order is placed";
            eventSub1.Expansion = "shipping,billing,item,coupon,summary"; // whatever you need.
            eventSub1.EventRuler = null; // no filtering.  we want all objects.
            eventSub1.Comments = "Merchant specific comment, for example: Bobby needs this webhook for the Accounting department.";

            WebhookEventSubscription eventSub2 = new WebhookEventSubscription();
            eventSub2.EventName = "order_update";
            eventSub2.EventDescription = "when an order is modified";
            eventSub2.Expansion = "shipping,billing,item,coupon,summary"; // whatever you need.
            eventSub2.EventRuler = null; // no filtering.  we want all objects.
            eventSub2.Comments = "Merchant specific comment, for example: Bobby needs this webhook for the Accounting department.";

            WebhookEventSubscription eventSub3 = new WebhookEventSubscription();
            eventSub3.EventName = "order_delete";
            eventSub3.EventDescription = "when an order is modified";
            eventSub3.Expansion = ""; // don't need any expansion on delete.  only need to know the order_id
            eventSub3.EventRuler = null; // no filtering.  we want all objects.
            eventSub3.Comments = "Merchant specific comment, for example: Bobby needs this webhook for the Accounting department.";

            WebhookEventCategory eventCategory1 = new WebhookEventCategory();
            eventCategory1.EventCategory = "order";
            eventCategory1.Events = new List<WebhookEventSubscription> { eventSub1, eventSub2, eventSub3 };

            // apiResponse.Webhook will return the newly created webhook.
            WebhookResponse apiResponse = webhookApi.InsertWebhook(webhook, false);

            if (apiResponse.Error != null)
            {
                Console.Error.WriteLine(apiResponse.Error.DeveloperMessage);
                Console.Error.WriteLine(apiResponse.Error.UserMessage);
                Environment.Exit(1);
            }

            Webhook createdWebhook = apiResponse.Webhook;
            // TODO - store the webhook oid in case you ever need to make changes.

            // This should equal what you submitted, plus contain much new information
            Console.WriteLine(createdWebhook.ToString());
 
        }
    }
}
package webhook;

import com.ultracart.admin.v2.WebhookApi;
import com.ultracart.admin.v2.models.Webhook;
import com.ultracart.admin.v2.models.WebhookEventCategory;
import com.ultracart.admin.v2.models.WebhookEventSubscription;
import com.ultracart.admin.v2.models.WebhookResponse;
import com.ultracart.admin.v2.util.ApiException;
import common.Constants;

import java.util.ArrayList;
import java.util.List;

public class InsertWebhook {
    public static void execute() {
        /*
         * Adds a new webhook on the account.  If you add a new webhook with the authentication_type set to basic, but
         * do not specify the basic_username and basic_password, UltraCart will automatically generate random ones and
         * return them.  This allows your application to have simpler logic on the setup of a secure webhook.
         * 
         * Event Category      Event Name                      Description
         * [Full event list from original comment preserved]
         * 
         * Note: Each event uses the same expansions as the event category.  To see a list of possible expansion values,
         * visit www.ultracart.com/api/. Order Expansions (https://www.ultracart.com/api/#resource_order.html) are listed
         * below because most webhooks are for order events.
         * Order Expansion:
         * [Expansion list from original comment preserved]
         * 
         * Note: The WebhookEventSubscription.event_ruler field is processed with the AWS Event Ruler library to filter down
         * events to just what you want.  If you wish to employ a ruler filter, see https://github.com/aws/event-ruler
         * for syntax examples.  You'll need to apply the aws syntax against the UltraCart object models.  Contact UltraCart
         * support if you need assistance creating the proper ruler expression.
         * 
         * Possible Errors:
         */

        WebhookApi webhookApi = new WebhookApi(Constants.API_KEY);

        Webhook webhook = new Webhook();
        webhook.setWebhookUrl("https://www.mywebiste.com/page/to/call/when/this/webhook/fires.php");  // Must be HTTPS if customer related information is being delivered.
        webhook.setAuthenticationType(Webhook.AuthenticationTypeEnum.BASIC);  // "basic","none","api user","aws iam"
        webhook.setBasicUsername("george");
        webhook.setBasicPassword("LlamaLlamaRedPajama");
        webhook.setMaximumEvents(10);
        webhook.setMaximumSize(5242880); // 5 MB is pretty chunky.
        webhook.setApiVersion(Webhook.ApiVersionEnum._2017_03_01); // this is our only API version so far.
        webhook.setCompressEvents(true); // compress events with gzip, then base64 encode them as a string.

        WebhookEventSubscription eventSub1 = new WebhookEventSubscription();
        eventSub1.setEventName("order_create");
        eventSub1.setEventDescription("when an order is placed");
        eventSub1.setExpansion("shipping,billing,item,coupon,summary"); // whatever you need.
        eventSub1.setEventRuler(null); // no filtering.  we want all objects.
        eventSub1.setComments("Merchant specific comment, for example: Bobby needs this webhook for the Accounting department.");

        WebhookEventSubscription eventSub2 = new WebhookEventSubscription();
        eventSub2.setEventName("order_update");
        eventSub2.setEventDescription("when an order is modified");
        eventSub2.setExpansion("shipping,billing,item,coupon,summary"); // whatever you need.
        eventSub2.setEventRuler(null); // no filtering.  we want all objects.
        eventSub2.setComments("Merchant specific comment, for example: Bobby needs this webhook for the Accounting department.");

        WebhookEventSubscription eventSub3 = new WebhookEventSubscription();
        eventSub3.setEventName("order_delete");
        eventSub3.setEventDescription("when an order is modified");
        eventSub3.setExpansion(""); // don't need any expansion on delete.  only need to know the order_id
        eventSub3.setEventRuler(null); // no filtering.  we want all objects.
        eventSub3.setComments("Merchant specific comment, for example: Bobby needs this webhook for the Accounting department.");

        WebhookEventCategory eventCategory1 = new WebhookEventCategory();
        eventCategory1.setEventCategory("order");
        List<WebhookEventSubscription> events = new ArrayList<>();
        events.add(eventSub1);
        events.add(eventSub2);
        events.add(eventSub3);
        eventCategory1.setEvents(events);

        // apiResponse.getWebhook() will return the newly created webhook.
        try {
            WebhookResponse apiResponse = webhookApi.insertWebhook(webhook, false);

            if (apiResponse.getError() != null) {
                System.err.println(apiResponse.getError().getDeveloperMessage());
                System.err.println(apiResponse.getError().getUserMessage());
                System.exit(1);
            }

            Webhook createdWebhook = apiResponse.getWebhook();
            // TODO - store the webhook oid in case you ever need to make changes.

            // This should equal what you submitted, plus contain much new information
            System.out.println(createdWebhook.toString());
        } catch (ApiException e) {
            System.err.println("API Exception occurred: " + e.getMessage());
            e.printStackTrace();
            System.exit(1);
        }
    }
}
import {webhookApi} from '../api.js';

export class InsertWebhook {
    /**
     * Adds a new webhook on the account.  If you add a new webhook with the authentication_type set to basic, but
     * do not specify the basic_username and basic_password, UltraCart will automatically generate random ones and
     * return them.  This allows your application to have simpler logic on the setup of a secure webhook.
     *
     * Event Categories and Events:
     *
     * auto_order:
     * - auto_order_cancel       Fired when an auto order is canceled
     * - auto_order_create       Fired when an auto order is created
     * - auto_order_decline      Fired when an auto order is declined
     * - auto_order_disable      Fired when an auto order is disabled
     * - auto_order_preshipment  Fired when an auto order generates a new pre-shipment notice
     * - auto_order_rebill       Fired when an auto order is rebilled
     * - auto_order_update       Fired when an auto order is updated
     *
     * chargeback:
     * - chargeback_create       Fired when a chargeback is created
     * - chargeback_delete       Fired when a chargeback is deleted
     * - chargeback_update       Fired when a chargeback is updated
     *
     * checkout:
     * - checkout_cart_abandon           Fired when a cart is abandoned
     * - checkout_cart_send_return_email Fired when a return email should be sent to a customer
     *
     * customer:
     * - customer_create Fired when a customer profile is created
     * - customer_delete Fired when a customer profile is deleted
     * - customer_update Fired when a customer profile is updated
     *
     * fulfillment:
     * - fulfillment_hold      Fired when an order is held for review
     * - fulfillment_transmit  Fired to transmit an order to the fulfillment house
     *
     * item:
     * - item_create Fired when a new item is created
     * - item_delete Fired when an item is deleted
     * - item_update Fired when an item is updated
     *
     * order:
     * - order_abandon_recovery    Fired when a previously abandoned cart turns into an order
     * - order_create              Fired when an order is placed
     * - order_delete              Fired when an order is deleted
     * - order_payment_failed      Fired when a payment fails
     * - order_payment_process     Fired when a payment is processed
     * - order_refund              Fired when an order is refunded
     * - order_reject              Fired when an order is rejected
     * - order_s3_invoice          Fired when an invoice PDF is stored in S3 bucket
     * - order_s3_packing_slip     Fired when a packing slip PDF is stored in an S3 bucket
     * - order_ship                Fired when an order is shipped
     * - order_ship_delivered      Fired when an order has a shipment delivered
     * - order_ship_expected       Fired when an order has an expected delivery date
     * - order_ship_out_for_delivery Fired when an order has a shipment out for delivery
     * - order_stage_change        Fired when an order stage changes
     * - order_update              Fired when an order is edited
     *
     * storefront:
     * - screen_recording Fired when a screen recording is created
     *
     * user:
     * - user_create  Fired when a user is created
     * - user_delete  Fired when a user is deleted
     * - user_login   Fired when a user logs in
     * - user_update  Fired when a user is updated
     *
     * workflow_task:
     * - workflow_task_create Fired when a workflow task is created
     * - workflow_task_delete Fired when a workflow task is deleted
     * - workflow_task_update Fired when a workflow task is updated
     *
     * Note: Each event uses the same expansions as the event category. To see a list of possible expansion values,
     * visit www.ultracart.com/api/. Order Expansions (https://www.ultracart.com/api/#resource_order.html) are listed
     * below because most webhooks are for order events.
     *
     * Order Expansion:
     * - affiliate
     * - auto_order
     * - billing
     * - checkout
     * - affiliate.ledger
     * - channel_partner
     * - coupon
     * - customer_profile
     * - digital_order
     * - edi
     * - fraud_score
     * - gift
     * - gift_certificate
     * - internal
     * - item
     * - linked_shipment
     * - marketing
     * - payment
     * - payment.transaction
     * - point_of_sale
     * - quote
     * - salesforce
     * - shipping
     * - shipping.tracking_number_details
     * - summary
     * - taxes
     * - utms
     *
     * Note: The WebhookEventSubscription.event_ruler field is processed with the AWS Event Ruler library to filter down
     * events to just what you want. If you wish to employ a ruler filter, see https://github.com/aws/event-ruler
     * for syntax examples. You'll need to apply the aws syntax against the UltraCart object models. Contact UltraCart
     * support if you need assistance creating the proper ruler expression.
     *
     * Possible Errors:
     * (Specific error details may vary)
     */
    static async execute() {
        const webhook = {
            webhook_url: "https://www.mywebiste.com/page/to/call/when/this/webhook/fires.php",  // Must be HTTPS if customer related information is being delivered.
            authentication_type: "basic",  // "basic","none","api user","aws iam"
            basic_username: "george",
            basic_password: "LlamaLlamaRedPajama",
            maximum_events: 10,
            maximum_size: 5242880, // 5 MB is pretty chunky.
            api_version: "2017-03-01", // this is our only API version so far.
            compress_events: true // compress events with gzip, then base64 encode them as a string.
        };

        const eventSub1 = {
            event_name: "order_create",
            event_description: "when an order is placed",
            expansion: "shipping,billing,item,coupon,summary", // whatever you need.
            event_ruler: undefined, // no filtering.  we want all objects.
            comments: "Merchant specific comment, for example: Bobby needs this webhook for the Accounting department."
        };

        const eventSub2 = {
            event_name: "order_update",
            event_description: "when an order is modified",
            expansion: "shipping,billing,item,coupon,summary", // whatever you need.
            event_ruler: undefined, // no filtering.  we want all objects.
            comments: "Merchant specific comment, for example: Bobby needs this webhook for the Accounting department."
        };

        const eventSub3 = {
            event_name: "order_delete",
            event_description: "when an order is modified",
            expansion: "", // don't need any expansion on delete.  only need to know the order_id
            event_ruler: undefined, // no filtering.  we want all objects.
            comments: "Merchant specific comment, for example: Bobby needs this webhook for the Accounting department."
        };

        const eventCategory1 = {
            event_category: "order",
            events: [eventSub1, eventSub2, eventSub3]
        };

        try {
            // apiResponse.webhook will return the newly created webhook.
            const apiResponse = await new Promise((resolve, reject) => {
                webhookApi.insertWebhook(webhook, {}, function (error, data, response) {
                    if (error) {
                        reject(error);
                    } else {
                        resolve(data, response);
                    }
                });
            });

            if (apiResponse.error) {
                console.error(apiResponse.error.developer_message);
                console.error(apiResponse.error.user_message);
                process.exit(1);
            }

            const createdWebhook = apiResponse.webhook;
            // TODO - store the webhook oid in case you ever need to make changes.

            // This should equal what you submitted, plus contain much new information
            console.log(createdWebhook?.toString());
        } catch (error) {
            console.error('Error inserting webhook:', error);
            process.exit(1);
        }
    }
}

// Optional: If you want to run this directly
if (require.main === module) {
    InsertWebhook.execute().catch(console.error);
}
<?php

ini_set('display_errors', 1);

/*

Adds a new webhook on the account.  If you add a new webhook with the authentication_type set to basic, but
do not specify the basic_username and basic_password, UltraCart will automatically generate random ones and
return them.  This allows your application to have simpler logic on the setup of a secure webhook.

Event Category      Event Name                      Description
auto_order	        auto_order_cancel	            Fired when an auto order is canceled
auto_order	        auto_order_create	            Fired when an auto order is created
auto_order	        auto_order_decline	            Fired when an auto order is declined
auto_order	        auto_order_disable	            Fired when an auto order is disabled
auto_order	        auto_order_preshipment          Fired when an auto order generates a new pre-shipment notice
auto_order	        auto_order_rebill	            Fired when an auto order is rebilled
auto_order	        auto_order_update	            Fired when an auto order is updated
chargeback	        chargeback_create	            Fired when a chargeback is created
chargeback	        chargeback_delete	            Fired when a chargeback is deleted
chargeback	        chargeback_update	            Fired when a chargeback is updated
checkout	        checkout_cart_abandon	        Fired when a cart is abandoned
checkout	        checkout_cart_send_return_email Fired when a return email should be sent to a customer
customer	        customer_create                 Fired when a customer profile is created.
customer	        customer_delete                 Fired when a customer profile is deleted.
customer	        customer_update                 Fired when a customer profile is updated.
fulfillment	        fulfillment_hold                Fired when an order is held for review
fulfillment	        fulfillment_transmit            Fired to transmit an order to the fulfillment house
item	            item_create                     Fired when a new item is created.
item	            item_delete                     Fired when an item is deleted.
item	            item_update                     Fired when an item is updated.
order	            order_abandon_recovery          Fired when a previously abandoned cart turns into an order
order	            order_create                    Fired when an order is placed
order	            order_delete                    Fired when an order is deleted
order	            order_payment_failed            Fired when a payment fails
order	            order_payment_process           Fired when a payment is processed
order	            order_refund                    Fired when an order is refunded
order	            order_reject                    Fired when an order is rejected
order	            order_s3_invoice                Fired when an invoice PDF is stored in S3 bucket
order	            order_s3_packing_slip           Fired when a packing slip PDF is stored in an S3 bucket
order	            order_ship                      Fired when an order is shipped
order	            order_ship_delivered            Fired when an order has a shipment delivered
order	            order_ship_expected             Fired when an order has an expected delivery date
order	            order_ship_out_for_delivery     Fired when an order has a shipment out for delivery
order	            order_stage_change              Fired when an order stage changes
order	            order_update                    Fired when an order is edited
storefront	        screen_recording                Fired when a screen recording is created
user	            user_create                     Fired when a user is created
user	            user_delete                     Fired when a user is deleted
user	            user_login                      Fired when a user logs in
user	            user_update                     Fired when a user is updated
workflow_task	    workflow_task_create            Fired when a workflow task is created
workflow_task	    workflow_task_delete            Fired when a workflow task is deleted
workflow_task	    workflow_task_update            Fired when a workflow task is updated

Note: Each event uses the same expansions as the event category.  To see a list of possible expansion values,
visit www.ultracart.com/api/. Order Expansions (https://www.ultracart.com/api/#resource_order.html) are listed
below because most webhooks are for order events.
Order Expansion:
affiliate	        auto_order          billing             checkout
affiliate.ledger	channel_partner	    coupon	            customer_profile
digital_order	    edi	                fraud_score	        gift
gift_certificate	internal	        item	            linked_shipment
marketing	        payment	            payment.transaction point_of_sale
quote	            salesforce	        shipping	        shipping.tracking_number_details
summary	            taxes	            utms

Note: The WebhookEventSubscription.event_ruler field is processed with the AWS Event Ruler library to filter down
events to just what you want.  If you wish to employ a ruler filter, see https://github.com/aws/event-ruler
for syntax examples.  You'll need to apply the aws syntax against the UltraCart object models.  Contact UltraCart
support if you need assistance creating the proper ruler expression.


Possible Errors:

 */


use ultracart\v2\api\WebhookApi;
use ultracart\v2\models\Webhook;
use ultracart\v2\models\WebhookEventCategory;
use ultracart\v2\models\WebhookEventSubscription;

require_once '../vendor/autoload.php';
require_once '../constants.php';


$webhook_api = WebhookApi::usingApiKey(Constants::API_KEY);

$webhook = new Webhook();
$webhook->setWebhookUrl("https://www.mywebiste.com/page/to/call/when/this/webhook/fires.php");  // Must be HTTPS if customer related information is being delivered.
$webhook->setAuthenticationType("basic");  // "basic","none","api user","aws iam"
$webhook->setBasicUsername("george");
$webhook->setBasicPassword("LlamaLlamaRedPajama");
$webhook->setMaximumEvents(10);
$webhook->setMaximumSize( 5242880); // 5 MB is pretty chunky.
$webhook->setApiVersion("2017-03-01"); // this is our only API version so far.
$webhook->setCompressEvents(true); // compress events with gzip, then base64 encode them as a string.


$event_sub1 = new WebhookEventSubscription();
$event_sub1->setEventName("order_create");
$event_sub1->setEventDescription("when an order is placed");
$event_sub1->setExpansion("shipping,billing,item,coupon,summary"); // whatever you need.
$event_sub1->setEventRuler(null); // no filtering.  we want all objects.
$event_sub1->setComments("Merchant specific comment, for example: Bobby needs this webhook for the Accounting department.");

$event_sub2 = new WebhookEventSubscription();
$event_sub2->setEventName("order_update");
$event_sub2->setEventDescription("when an order is modified");
$event_sub2->setExpansion("shipping,billing,item,coupon,summary"); // whatever you need.
$event_sub2->setEventRuler(null); // no filtering.  we want all objects.
$event_sub2->setComments("Merchant specific comment, for example: Bobby needs this webhook for the Accounting department.");

$event_sub3 = new WebhookEventSubscription();
$event_sub3->setEventName("order_delete");
$event_sub3->setEventDescription("when an order is modified");
$event_sub3->setExpansion(""); // don't need any expansion on delete.  only need to know the order_id
$event_sub3->setEventRuler(null); // no filtering.  we want all objects.
$event_sub3->setComments("Merchant specific comment, for example: Bobby needs this webhook for the Accounting department.");


$eventCategory1 = new WebhookEventCategory();
$eventCategory1->setEventCategory("order");
$eventCategory1->setEvents([$event_sub1, $event_sub2, $event_sub3]);

// api_response->getWebhook will return the newly created webhook.
$api_response = $webhook_api->insertWebhook($webhook, false);


if ($api_response->getError() != null) {
    error_log($api_response->getError()->getDeveloperMessage());
    error_log($api_response->getError()->getUserMessage());
    exit();
}

$created_webhook = $api_response->getWebhook();
// TODO - store the webhook oid in case you ever need to make changes.

echo '<html lang="en"><body><pre>';
// This should equal what you submitted, plus contain much new information
var_dump($created_webhook);
echo '</pre></body></html>';

"""
Adds a new webhook on the account with multiple event subscriptions.
"""

from ultracart.apis import WebhookApi
from ultracart.models import Webhook, WebhookEventCategory, WebhookEventSubscription
from samples import api_client

def create_webhook():
    webhook_api = WebhookApi(api_client())

    # Configure webhook
    webhook = Webhook(
        webhook_url="https://www.mywebiste.com/page/to/call/when/this/webhook/fires.php",
        authentication_type="basic",
        basic_username="george",
        basic_password="LlamaLlamaRedPajama",
        maximum_events=10,
        maximum_size=5242880,  # 5 MB
        api_version="2017-03-01",
        compress_events=True
    )

    # Define event subscriptions
    event_subs = [
        WebhookEventSubscription(
            event_name="order_create",
            event_description="when an order is placed",
            expansion="shipping,billing,item,coupon,summary",
            event_ruler=None,
            comments="Merchant specific comment about webhook"
        ),
        WebhookEventSubscription(
            event_name="order_update",
            event_description="when an order is modified",
            expansion="shipping,billing,item,coupon,summary",
            event_ruler=None,
            comments="Merchant specific comment about webhook"
        ),
        WebhookEventSubscription(
            event_name="order_delete",
            event_description="when an order is deleted",
            expansion="",
            event_ruler=None,
            comments="Merchant specific comment about webhook"
        )
    ]

    # Create event category
    event_category = WebhookEventCategory(
        event_category="order",
        events=event_subs
    )

    # Insert webhook
    api_response = webhook_api.insert_webhook(webhook, False)

    if api_response.error:
        print(f"Developer Message: {api_response.error.developer_message}")
        print(f"User Message: {api_response.error.user_message}")
        return None

    return api_response.webhook

# Execute webhook creation
created_webhook = create_webhook()
if created_webhook:
    print(created_webhook)
require 'ultracart_api'
require_relative '../constants'

# Adds a new webhook on the account.  If you add a new webhook with the authentication_type set to basic, but
# do not specify the basic_username and basic_password, UltraCart will automatically generate random ones and
# return them.  This allows your application to have simpler logic on the setup of a secure webhook.
#
# Event Category      Event Name                      Description
# auto_order         auto_order_cancel               Fired when an auto order is canceled
# auto_order         auto_order_create               Fired when an auto order is created
# auto_order         auto_order_decline              Fired when an auto order is declined
# auto_order         auto_order_disable              Fired when an auto order is disabled
# auto_order         auto_order_preshipment          Fired when an auto order generates a new pre-shipment notice
# auto_order         auto_order_rebill               Fired when an auto order is rebilled
# auto_order         auto_order_update               Fired when an auto order is updated
# chargeback         chargeback_create               Fired when a chargeback is created
# chargeback         chargeback_delete               Fired when a chargeback is deleted
# chargeback         chargeback_update               Fired when a chargeback is updated
# checkout           checkout_cart_abandon           Fired when a cart is abandoned
# checkout           checkout_cart_send_return_email Fired when a return email should be sent to a customer
# customer           customer_create                 Fired when a customer profile is created.
# customer           customer_delete                 Fired when a customer profile is deleted.
# customer           customer_update                 Fired when a customer profile is updated.
# fulfillment        fulfillment_hold                Fired when an order is held for review
# fulfillment        fulfillment_transmit            Fired to transmit an order to the fulfillment house
# item               item_create                     Fired when a new item is created.
# item               item_delete                     Fired when an item is deleted.
# item               item_update                     Fired when an item is updated.
# order              order_abandon_recovery          Fired when a previously abandoned cart turns into an order
# order              order_create                    Fired when an order is placed
# order              order_delete                    Fired when an order is deleted
# order              order_payment_failed            Fired when a payment fails
# order              order_payment_process           Fired when a payment is processed
# order              order_refund                    Fired when an order is refunded
# order              order_reject                    Fired when an order is rejected
# order              order_s3_invoice                Fired when an invoice PDF is stored in S3 bucket
# order              order_s3_packing_slip           Fired when a packing slip PDF is stored in an S3 bucket
# order              order_ship                      Fired when an order is shipped
# order              order_ship_delivered            Fired when an order has a shipment delivered
# order              order_ship_expected             Fired when an order has an expected delivery date
# order              order_ship_out_for_delivery     Fired when an order has a shipment out for delivery
# order              order_stage_change              Fired when an order stage changes
# order              order_update                    Fired when an order is edited
# storefront         screen_recording                Fired when a screen recording is created
# user               user_create                     Fired when a user is created
# user               user_delete                     Fired when a user is deleted
# user               user_login                      Fired when a user logs in
# user               user_update                     Fired when a user is updated
# workflow_task      workflow_task_create            Fired when a workflow task is created
# workflow_task      workflow_task_delete            Fired when a workflow task is deleted
# workflow_task      workflow_task_update            Fired when a workflow task is updated
#
# Note: Each event uses the same expansions as the event category.  To see a list of possible expansion values,
# visit www.ultracart.com/api/. Order Expansions (https://www.ultracart.com/api/#resource_order.html) are listed
# below because most webhooks are for order events.
# Order Expansion:
# affiliate          auto_order          billing             checkout
# affiliate.ledger   channel_partner     coupon             customer_profile
# digital_order      edi                 fraud_score        gift
# gift_certificate   internal            item               linked_shipment
# marketing          payment             payment.transaction point_of_sale
# quote              salesforce          shipping           shipping.tracking_number_details
# summary            taxes               utms
#
# Note: The WebhookEventSubscription.event_ruler field is processed with the AWS Event Ruler library to filter down
# events to just what you want.  If you wish to employ a ruler filter, see https://github.com/aws/event-ruler
# for syntax examples.  You'll need to apply the aws syntax against the UltraCart object models.  Contact UltraCart
# support if you need assistance creating the proper ruler expression.

webhook_api = UltracartClient::WebhookApi.new_using_api_key(Constants::API_KEY)

webhook = UltracartClient::Webhook.new
webhook.webhook_url = "https://www.mywebiste.com/page/to/call/when/this/webhook/fires.php"  # Must be HTTPS if customer related information is being delivered.
webhook.authentication_type = "basic"  # "basic","none","api user","aws iam"
webhook.basic_username = "george"
webhook.basic_password = "LlamaLlamaRedPajama"
webhook.maximum_events = 10
webhook.maximum_size = 5242880 # 5 MB is pretty chunky.
webhook.api_version = "2017-03-01" # this is our only API version so far.
webhook.compress_events = true # compress events with gzip, then base64 encode them as a string.

event_sub1 = UltracartClient::WebhookEventSubscription.new
event_sub1.event_name = "order_create"
event_sub1.event_description = "when an order is placed"
event_sub1.expansion = "shipping,billing,item,coupon,summary" # whatever you need.
event_sub1.event_ruler = nil # no filtering.  we want all objects.
event_sub1.comments = "Merchant specific comment, for example: Bobby needs this webhook for the Accounting department."

event_sub2 = UltracartClient::WebhookEventSubscription.new
event_sub2.event_name = "order_update"
event_sub2.event_description = "when an order is modified"
event_sub2.expansion = "shipping,billing,item,coupon,summary" # whatever you need.
event_sub2.event_ruler = nil # no filtering.  we want all objects.
event_sub2.comments = "Merchant specific comment, for example: Bobby needs this webhook for the Accounting department."

event_sub3 = UltracartClient::WebhookEventSubscription.new
event_sub3.event_name = "order_delete"
event_sub3.event_description = "when an order is modified"
event_sub3.expansion = "" # don't need any expansion on delete.  only need to know the order_id
event_sub3.event_ruler = nil # no filtering.  we want all objects.
event_sub3.comments = "Merchant specific comment, for example: Bobby needs this webhook for the Accounting department."

event_category1 = UltracartClient::WebhookEventCategory.new
event_category1.event_category = "order"
event_category1.events = [event_sub1, event_sub2, event_sub3]

# api_response.webhook will return the newly created webhook.
api_response = webhook_api.insert_webhook(webhook, false)

if api_response.error
  puts api_response.error.developer_message
  puts api_response.error.user_message
  exit
end

created_webhook = api_response.webhook
# TODO - store the webhook oid in case you ever need to make changes.

# This should equal what you submitted, plus contain much new information
puts created_webhook.inspect
import { webhookApi } from '../api';
import {
    Webhook,
    WebhookResponse,
    WebhookEventSubscription,
    WebhookEventCategory
} from 'ultracart_rest_api_v2_typescript';

export class InsertWebhook {
    /**
     * Adds a new webhook on the account.  If you add a new webhook with the authentication_type set to basic, but
     * do not specify the basic_username and basic_password, UltraCart will automatically generate random ones and
     * return them.  This allows your application to have simpler logic on the setup of a secure webhook.
     *
     * Event Categories and Events:
     *
     * auto_order:
     * - auto_order_cancel       Fired when an auto order is canceled
     * - auto_order_create       Fired when an auto order is created
     * - auto_order_decline      Fired when an auto order is declined
     * - auto_order_disable      Fired when an auto order is disabled
     * - auto_order_preshipment  Fired when an auto order generates a new pre-shipment notice
     * - auto_order_rebill       Fired when an auto order is rebilled
     * - auto_order_update       Fired when an auto order is updated
     *
     * chargeback:
     * - chargeback_create       Fired when a chargeback is created
     * - chargeback_delete       Fired when a chargeback is deleted
     * - chargeback_update       Fired when a chargeback is updated
     *
     * checkout:
     * - checkout_cart_abandon           Fired when a cart is abandoned
     * - checkout_cart_send_return_email Fired when a return email should be sent to a customer
     *
     * customer:
     * - customer_create Fired when a customer profile is created
     * - customer_delete Fired when a customer profile is deleted
     * - customer_update Fired when a customer profile is updated
     *
     * fulfillment:
     * - fulfillment_hold      Fired when an order is held for review
     * - fulfillment_transmit  Fired to transmit an order to the fulfillment house
     *
     * item:
     * - item_create Fired when a new item is created
     * - item_delete Fired when an item is deleted
     * - item_update Fired when an item is updated
     *
     * order:
     * - order_abandon_recovery    Fired when a previously abandoned cart turns into an order
     * - order_create              Fired when an order is placed
     * - order_delete              Fired when an order is deleted
     * - order_payment_failed      Fired when a payment fails
     * - order_payment_process     Fired when a payment is processed
     * - order_refund              Fired when an order is refunded
     * - order_reject              Fired when an order is rejected
     * - order_s3_invoice          Fired when an invoice PDF is stored in S3 bucket
     * - order_s3_packing_slip     Fired when a packing slip PDF is stored in an S3 bucket
     * - order_ship                Fired when an order is shipped
     * - order_ship_delivered      Fired when an order has a shipment delivered
     * - order_ship_expected       Fired when an order has an expected delivery date
     * - order_ship_out_for_delivery Fired when an order has a shipment out for delivery
     * - order_stage_change        Fired when an order stage changes
     * - order_update              Fired when an order is edited
     *
     * storefront:
     * - screen_recording Fired when a screen recording is created
     *
     * user:
     * - user_create  Fired when a user is created
     * - user_delete  Fired when a user is deleted
     * - user_login   Fired when a user logs in
     * - user_update  Fired when a user is updated
     *
     * workflow_task:
     * - workflow_task_create Fired when a workflow task is created
     * - workflow_task_delete Fired when a workflow task is deleted
     * - workflow_task_update Fired when a workflow task is updated
     *
     * Note: Each event uses the same expansions as the event category. To see a list of possible expansion values,
     * visit www.ultracart.com/api/. Order Expansions (https://www.ultracart.com/api/#resource_order.html) are listed
     * below because most webhooks are for order events.
     *
     * Order Expansion:
     * - affiliate
     * - auto_order
     * - billing
     * - checkout
     * - affiliate.ledger
     * - channel_partner
     * - coupon
     * - customer_profile
     * - digital_order
     * - edi
     * - fraud_score
     * - gift
     * - gift_certificate
     * - internal
     * - item
     * - linked_shipment
     * - marketing
     * - payment
     * - payment.transaction
     * - point_of_sale
     * - quote
     * - salesforce
     * - shipping
     * - shipping.tracking_number_details
     * - summary
     * - taxes
     * - utms
     *
     * Note: The WebhookEventSubscription.event_ruler field is processed with the AWS Event Ruler library to filter down
     * events to just what you want. If you wish to employ a ruler filter, see https://github.com/aws/event-ruler
     * for syntax examples. You'll need to apply the aws syntax against the UltraCart object models. Contact UltraCart
     * support if you need assistance creating the proper ruler expression.
     *
     * Possible Errors:
     * (Specific error details may vary)
     */
    public static async execute(): Promise<void> {
        const webhook: Webhook = {
            webhook_url: "https://www.mywebiste.com/page/to/call/when/this/webhook/fires.php",  // Must be HTTPS if customer related information is being delivered.
            authentication_type: "basic",  // "basic","none","api user","aws iam"
            basic_username: "george",
            basic_password: "LlamaLlamaRedPajama",
            maximum_events: 10,
            maximum_size: 5242880, // 5 MB is pretty chunky.
            api_version: "2017-03-01", // this is our only API version so far.
            compress_events: true // compress events with gzip, then base64 encode them as a string.
        };

        const eventSub1: WebhookEventSubscription = {
            event_name: "order_create",
            event_description: "when an order is placed",
            expansion: "shipping,billing,item,coupon,summary", // whatever you need.
            event_ruler: undefined, // no filtering.  we want all objects.
            comments: "Merchant specific comment, for example: Bobby needs this webhook for the Accounting department."
        };

        const eventSub2: WebhookEventSubscription = {
            event_name: "order_update",
            event_description: "when an order is modified",
            expansion: "shipping,billing,item,coupon,summary", // whatever you need.
            event_ruler: undefined, // no filtering.  we want all objects.
            comments: "Merchant specific comment, for example: Bobby needs this webhook for the Accounting department."
        };

        const eventSub3: WebhookEventSubscription = {
            event_name: "order_delete",
            event_description: "when an order is modified",
            expansion: "", // don't need any expansion on delete.  only need to know the order_id
            event_ruler: undefined, // no filtering.  we want all objects.
            comments: "Merchant specific comment, for example: Bobby needs this webhook for the Accounting department."
        };

        const eventCategory1: WebhookEventCategory = {
            event_category: "order",
            events: [eventSub1, eventSub2, eventSub3]
        };

        try {
            // apiResponse.webhook will return the newly created webhook.
            const apiResponse: WebhookResponse = await webhookApi.insertWebhook({webhook: webhook, placeholders: false});

            if (apiResponse.error) {
                console.error(apiResponse.error.developer_message);
                console.error(apiResponse.error.user_message);
                process.exit(1);
            }

            const createdWebhook = apiResponse.webhook;
            // TODO - store the webhook oid in case you ever need to make changes.

            // This should equal what you submitted, plus contain much new information
            console.log(createdWebhook?.toString());
        } catch (error) {
            console.error('Error inserting webhook:', error);
            process.exit(1);
        }
    }
}

// Optional: If you want to run this directly
if (require.main === module) {
    InsertWebhook.execute().catch(console.error);
}

Delete a webhook

Permissions:
  • webhook_write

Produces: application/json
delete
/webhook/webhooks/{webhookOid}

Delete a webhook on the UltraCart account.

SDK Function Name: deleteWebhook

Parameters
Parameter Description Location Data Type Required
webhookOid The webhook oid to delete. path integer (int32) required
Responses
Status Code Reason Response Model
204
No Content
400
Bad Request 400
401
Unauthorized 401
410
Authorized Application Disabled 410
429
Too Many Requests 429
500
Server Side 500
using System;
using com.ultracart.admin.v2.Api;
using com.ultracart.admin.v2.Model;

namespace SdkSample.webhook
{
    public class DeleteWebhook
    {
        public static void Execute()
        {
            /*
             * Deletes a webhook
             *
             * You will need the webhook_oid to call this method. Call getWebhooks() if you don't know your oid.
             * Returns status code 204 (No Content) on success
             */

            WebhookApi webhookApi = new WebhookApi(Constants.ApiKey);
            int webhookOid = 123456789; // call getWebhooks if you don't know this.
            webhookApi.DeleteWebhook(webhookOid);
        }
    }
}
package webhook;

import com.ultracart.admin.v2.WebhookApi;
import com.ultracart.admin.v2.models.*;
import com.ultracart.admin.v2.util.ApiException;
import common.Constants;

public class DeleteWebhook {
   public static void execute() throws ApiException {
       /*
        * Deletes a webhook
        *
        * You will need the webhook_oid to call this method. Call getWebhooks() if you don't know your oid.
        * Returns status code 204 (No Content) on success
        */

       WebhookApi webhookApi = new WebhookApi(Constants.API_KEY);
       int webhookOid = 123456789; // call getWebhooks if you don't know this.
       webhookApi.deleteWebhook(webhookOid);
   }
}
// Import API and UltraCart types
import { webhookApi } from '../api.js';

// Namespace-like structure using a class
export class DeleteWebhook {
  static async execute() {
    /*
     * Deletes a webhook
     *
     * You will need the webhook_oid to call this method. Call getWebhooks() if you don't know your oid.
     * Returns status code 204 (No Content) on success
     */
    try {
      const webhookOid = 123456789; // call getWebhooks if you don't know this.

      // UltraCart API call with parameter as an anonymous object
      await new Promise((resolve, reject) => {
        webhookApi.deleteWebhook(webhookOid, function (error, data, response) {
          if (error) {
            reject(error);
          } else {
            resolve(data, response);
          }
        });
      });

      console.log(`Webhook ${webhookOid} deleted successfully`);
    } catch (ex) {
      console.log(`Error: ${ex.message}`);
      console.log(ex.stack);
    }
  }
}
<?php

ini_set('display_errors', 1);

/*

deletes a webhook

You will need the webhook_oid to call this method.  Call getWebhooks() if you don't know your oid.
Returns status code 204 (No Content) on success

*/


use ultracart\v2\api\WebhookApi;

require_once '../vendor/autoload.php';
require_once '../constants.php';

$webhook_api = WebhookApi::usingApiKey(Constants::API_KEY);
$webhook_oid = 123456789; // call getWebhooks if you don't know this.
$webhook_api->deleteWebhook($webhook_oid);

"""
deletes a webhook

You will need the webhook_oid to call this method.  Call getWebhooks() if you don't know your oid.
Returns status code 204 (No Content) on success
"""

from ultracart.apis import WebhookApi
from samples import api_client

# Create Webhook API instance
webhook_api = WebhookApi(api_client())

# webhook_oid to delete (call getWebhooks if you don't know this)
webhook_oid = 123456789

# Delete the webhook
webhook_api.delete_webhook(webhook_oid=webhook_oid)
require 'ultracart_api'
require_relative '../constants'

# deletes a webhook
#
# You will need the webhook_oid to call this method.  Call getWebhooks() if you don't know your oid.
# Returns status code 204 (No Content) on success

webhook_api = UltracartClient::WebhookApi.new_using_api_key(Constants::API_KEY)
webhook_oid = 123456789 # call getWebhooks if you don't know this.
webhook_api.delete_webhook(webhook_oid)
// Import API and UltraCart types
import { webhookApi } from '../api';

// Namespace-like structure using a class
export class DeleteWebhook {
  public static async execute(): Promise<void> {
    /*
     * Deletes a webhook
     *
     * You will need the webhook_oid to call this method. Call getWebhooks() if you don't know your oid.
     * Returns status code 204 (No Content) on success
     */
    try {
      const webhookOid = 123456789; // call getWebhooks if you don't know this.

      // UltraCart API call with parameter as an anonymous interface
      await webhookApi.deleteWebhook({
        webhookOid: webhookOid,
      });

      console.log(`Webhook ${webhookOid} deleted successfully`);
    } catch (ex) {
      console.log(`Error: ${(ex as Error).message}`);
      console.log((ex as Error).stack);
    }
  }
}


Update a webhook

Permissions:
  • webhook_write

Consumes: application/json
Produces: application/json
put
/webhook/webhooks/{webhookOid}

Update a webhook on the account

SDK Function Name: updateWebhook

Parameters
Parameter Description Location Data Type Required
webhook Webhook to update body Webhook required
webhookOid The webhook oid to update. path integer (int32) required
_placeholders Whether or not placeholder values should be returned in the result. Useful for UIs that consume this REST API. query boolean optional
Responses
Status Code Reason Response Model
200
Successful response WebhookResponse
400
Bad Request 400
401
Unauthorized 401
410
Authorized Application Disabled 410
429
Too Many Requests 429
500
Server Side 500
using System;
using System.Collections.Generic;
using com.ultracart.admin.v2.Api;
using com.ultracart.admin.v2.Model;

namespace SdkSample.webhook
{
    public class UpdateWebhook
    {
        public static void Execute()
        {
            /*
             * Updates a webhook on the account.  See insertWebhook.php for a complete example with field usage.
             * For this example, we are just updating the basic password.
             */

            WebhookApi webhookApi = new WebhookApi(Constants.ApiKey);

            // you should have stored this when you created the webhook.  If you don't know it, call getWebhooks and iterate through
            // them to find you target webhook (add useful comments to each webhook really helps in this endeavor) and get the
            // webhook oid from that.  You'll want to call getWebhooks any way to get the object for updating. It is HIGHLY
            // recommended to get the object from UltraCart for updating rather than constructing it yourself to avoid accidentally
            // deleting a part of the object during the update.
            int webhookOid = 123456789;

            Webhook webhookToUpdate = null;
            List<Webhook> webhooks = webhookApi.GetWebhooks(100, 0, null, null).Webhooks;
            foreach (Webhook webhook in webhooks)
            {
                if (webhook.WebhookOid == webhookOid)
                {
                    webhookToUpdate = webhook;
                    break;
                }
            }

            webhookToUpdate.BasicPassword = "new password here";
            WebhookResponse apiResponse = webhookApi.UpdateWebhook(webhookOid, webhookToUpdate);
            Webhook updatedWebhook = apiResponse.Webhook;

            if (apiResponse.Error != null)
            {
                Console.Error.WriteLine(apiResponse.Error.DeveloperMessage);
                Console.Error.WriteLine(apiResponse.Error.UserMessage);
                Environment.Exit(1);
            }

 
            Console.WriteLine(updatedWebhook.ToString());
 
        }
    }
}
package webhook;

import com.ultracart.admin.v2.WebhookApi;
import com.ultracart.admin.v2.models.Webhook;
import com.ultracart.admin.v2.models.WebhookResponse;
import com.ultracart.admin.v2.util.ApiException;
import common.Constants;

import java.util.List;

public class UpdateWebhook {
    public static void execute() {
        /*
         * Updates a webhook on the account.  See insertWebhook.php for a complete example with field usage.
         * For this example, we are just updating the basic password.
         */

        WebhookApi webhookApi = new WebhookApi(Constants.API_KEY);

        // you should have stored this when you created the webhook.  If you don't know it, call getWebhooks and iterate through
        // them to find you target webhook (add useful comments to each webhook really helps in this endeavor) and get the
        // webhook oid from that.  You'll want to call getWebhooks any way to get the object for updating. It is HIGHLY
        // recommended to get the object from UltraCart for updating rather than constructing it yourself to avoid accidentally
        // deleting a part of the object during the update.
        int webhookOid = 123456789;

        try {
            Webhook webhookToUpdate = null;
            List<Webhook> webhooks = webhookApi.getWebhooks(100, 0, null, null).getWebhooks();
            for (Webhook webhook : webhooks) {
                if (webhook.getWebhookOid() == webhookOid) {
                    webhookToUpdate = webhook;
                    break;
                }
            }

            if (webhookToUpdate == null) {
                System.err.println("Webhook not found with OID: " + webhookOid);
                System.exit(1);
                return;
            }

            webhookToUpdate.setBasicPassword("new password here");
            WebhookResponse apiResponse = webhookApi.updateWebhook(webhookOid, webhookToUpdate, false);
            Webhook updatedWebhook = apiResponse.getWebhook();

            if (apiResponse.getError() != null) {
                System.err.println(apiResponse.getError().getDeveloperMessage());
                System.err.println(apiResponse.getError().getUserMessage());
                System.exit(1);
            }

            System.out.println(updatedWebhook.toString());
        } catch (ApiException e) {
            System.err.println("API Exception occurred: " + e.getMessage());
            e.printStackTrace();
            System.exit(1);
        }
    }
}
import { webhookApi } from '../api.js';

export class UpdateWebhook {
    /**
     * Updates a webhook on the account. See insertWebhook.php for a complete example with field usage.
     * For this example, we are just updating the basic password.
     *
     * Notes:
     * - You should have stored the webhook OID when you created the webhook.
     * - If you don't know the OID, call getWebhooks and iterate through them to find your target webhook.
     * - Adding useful comments to each webhook helps in identifying the correct one.
     *
     * HIGHLY RECOMMENDED:
     * - Get the object from UltraCart for updating
     * - Avoid constructing the object yourself to prevent accidentally deleting parts of the object during update
     */
    static async execute() {
        // You should have stored this when you created the webhook
        const webhookOid = 123456789;

        try {
            // Fetch webhooks to find the specific one to update
            const webhooksResponse = await new Promise((resolve, reject) => {
                webhookApi.getWebhooks({_limit: 100, _offset: 0}, function (error, data, response) {
                    if (error) {
                        reject(error);
                    } else {
                        resolve(data, response);
                    }
                });
            });

            const webhooks = webhooksResponse.webhooks || [];

            // Find the specific webhook to update
            const webhookToUpdate = webhooks.find(webhook => webhook.webhook_oid === webhookOid);

            if (!webhookToUpdate) {
                console.error(`Webhook with OID ${webhookOid} not found`);
                process.exit(1);
            }

            // Update the basic password
            webhookToUpdate.basic_password = "new password here";

            // Perform the update
            const apiResponse = await new Promise((resolve, reject) => {
                webhookApi.updateWebhook(webhookOid, webhookToUpdate, function (error, data, response) {
                    if (error) {
                        reject(error);
                    } else {
                        resolve(data, response);
                    }
                });
            });

            // Check for errors
            if (apiResponse.error) {
                console.error(apiResponse.error.developer_message);
                console.error(apiResponse.error.user_message);
                process.exit(1);
            }

            // Log the updated webhook
            const updatedWebhook = apiResponse.webhook;
            console.log(updatedWebhook?.toString());

        } catch (error) {
            console.error('Error updating webhook:', error);
            process.exit(1);
        }
    }
}

// Optional: If you want to run this directly
if (require.main === module) {
    UpdateWebhook.execute().catch(console.error);
}
<?php

ini_set('display_errors', 1);

/*

Updates a webhook on the account.  See insertWebhook.php for a complete example with field usage.
For this example, we are just updating the basic password.

 */


use ultracart\v2\api\WebhookApi;

require_once '../vendor/autoload.php';
require_once '../constants.php';


$webhook_api = WebhookApi::usingApiKey(Constants::API_KEY);

// you should have stored this when you created the webhook.  If you don't know it, call getWebhooks and iterate through
// them to find you target webhook (add useful comments to each webhook really helps in this endeavor) and get the
// webhook oid from that.  You'll want to call getWebhooks any way to get the object for updating. It is HIGHLY
// recommended to get the object from UltraCart for updating rather than constructing it yourself to avoid accidentally
// deleting a part of the object during the update.
$webhook_oid = 123456789;

$webhook_to_update = null;
$webhooks = $webhook_api->getWebhooks(100, 0, null, null)->getWebhooks();
foreach ($webhooks as $webhook) {
    if($webhook->getWebhookOid() == $webhook_oid){
        $webhook_to_update = $webhook;
        break;
    }
}

$webhook_to_update->setBasicPassword("new password here");
$api_response = $webhook_api->updateWebhook($webhook_oid, $webhook_to_update);
$updated_webhook = $api_response->getWebhook();

if ($api_response->getError() != null) {
    error_log($api_response->getError()->getDeveloperMessage());
    error_log($api_response->getError()->getUserMessage());
    exit();
}

$created_webhook = $api_response->getWebhook();

echo '<html lang="en"><body><pre>';
var_dump($updated_webhook);
echo '</pre></body></html>';

"""
Update a webhook's basic password by retrieving the existing webhook first.
"""

from ultracart.apis import WebhookApi
from samples import api_client

def update_webhook():
   webhook_api = WebhookApi(api_client())

   # Webhook OID to update
   webhook_oid = 123456789

   # Retrieve existing webhooks and find the target
   webhooks = webhook_api.get_webhooks(limit=100, offset=0).webhooks
   webhook_to_update = next((w for w in webhooks if w.webhook_oid == webhook_oid), None)

   if not webhook_to_update:
       print(f"Webhook with OID {webhook_oid} not found")
       return None

   # Update basic password
   webhook_to_update.basic_password = "new password here"

   # Perform update
   api_response = webhook_api.update_webhook(webhook_oid=webhook_oid, webhook=webhook_to_update)

   if api_response.error:
       print(f"Developer Message: {api_response.error.developer_message}")
       print(f"User Message: {api_response.error.user_message}")
       return None

   return api_response.webhook

# Execute webhook update
updated_webhook = update_webhook()
if updated_webhook:
   print(updated_webhook)
require 'ultracart_api'
require_relative '../constants'

# Updates a webhook on the account.  See insertWebhook.php for a complete example with field usage.
# For this example, we are just updating the basic password.

webhook_api = UltracartClient::WebhookApi.new_using_api_key(Constants::API_KEY)

# you should have stored this when you created the webhook.  If you don't know it, call getWebhooks and iterate through
# them to find you target webhook (add useful comments to each webhook really helps in this endeavor) and get the
# webhook oid from that.  You'll want to call getWebhooks any way to get the object for updating. It is HIGHLY
# recommended to get the object from UltraCart for updating rather than constructing it yourself to avoid accidentally
# deleting a part of the object during the update.
webhook_oid = 123456789

webhook_to_update = nil
opts = {
  '_sort' => nil,
  '_placeholders' => nil
}
webhooks = webhook_api.get_webhooks(100, 0, opts).webhooks
webhooks.each do |webhook|
  if webhook.webhook_oid == webhook_oid
    webhook_to_update = webhook
    break
  end
end

webhook_to_update.basic_password = "new password here"
api_response = webhook_api.update_webhook(webhook_oid, webhook_to_update)
updated_webhook = api_response.webhook

if api_response.error
  puts api_response.error.developer_message
  puts api_response.error.user_message
  exit
end

puts updated_webhook.inspect
import { webhookApi } from '../api';
import {
    Webhook,
    WebhookResponse
} from 'ultracart_rest_api_v2_typescript';

export class UpdateWebhook {
    /**
     * Updates a webhook on the account. See insertWebhook.php for a complete example with field usage.
     * For this example, we are just updating the basic password.
     *
     * Notes:
     * - You should have stored the webhook OID when you created the webhook.
     * - If you don't know the OID, call getWebhooks and iterate through them to find your target webhook.
     * - Adding useful comments to each webhook helps in identifying the correct one.
     *
     * HIGHLY RECOMMENDED:
     * - Get the object from UltraCart for updating
     * - Avoid constructing the object yourself to prevent accidentally deleting parts of the object during update
     */
    public static async execute(): Promise<void> {
        // You should have stored this when you created the webhook
        const webhookOid: number = 123456789;

        try {
            // Fetch webhooks to find the specific one to update
            const webhooksResponse = await webhookApi.getWebhooks({limit: 100, offset: 0});
            const webhooks: Webhook[] = webhooksResponse.webhooks || [];

            // Find the specific webhook to update
            const webhookToUpdate = webhooks.find(webhook => webhook.webhook_oid === webhookOid);

            if (!webhookToUpdate) {
                console.error(`Webhook with OID ${webhookOid} not found`);
                process.exit(1);
            }

            // Update the basic password
            webhookToUpdate.basic_password = "new password here";

            // Perform the update
            const apiResponse: WebhookResponse = await webhookApi.updateWebhook({webhookOid, webhook: webhookToUpdate});

            // Check for errors
            if (apiResponse.error) {
                console.error(apiResponse.error.developer_message);
                console.error(apiResponse.error.user_message);
                process.exit(1);
            }

            // Log the updated webhook
            const updatedWebhook = apiResponse.webhook;
            console.log(updatedWebhook?.toString());

        } catch (error) {
            console.error('Error updating webhook:', error);
            process.exit(1);
        }
    }
}

// Optional: If you want to run this directly
if (require.main === module) {
    UpdateWebhook.execute().catch(console.error);
}

Retrieve the log summaries

Permissions:
  • webhook_read

Produces: application/json
get
/webhook/webhooks/{webhookOid}/logs

Retrieves the log summary information for a given webhook. This is useful for displaying all the various logs that can be viewed.

SDK Function Name: getWebhookLogSummaries

Parameters
Parameter Description Location Data Type Required
webhookOid The webhook oid to retrieve log summaries for. path integer (int32) required
requestId query string optional
beginDate query string optional
endDate query string optional
status query string optional
event query string optional
orderId query string optional
request query string optional
duration query integer (int32) optional
_limit The maximum number of records to return on this one API call.
Default: 100
query integer optional
_offset Pagination of the record set. Offset is a zero based index.
Default: 0
query integer optional
_since Fetch log summaries that have been delivered since this date/time. query dateTime optional
Responses
Status Code Reason Response Model
200
Successful response WebhookLogSummariesResponse
400
Bad Request 400
401
Unauthorized 401
410
Authorized Application Disabled 410
429
Too Many Requests 429
500
Server Side 500
using System;
using System.Collections.Generic;
using com.ultracart.admin.v2.Api;
using com.ultracart.admin.v2.Client;
using com.ultracart.admin.v2.Model;

namespace SdkSample.webhook
{
    public class GetWebhookLogSummaries
    {
        /*
         * This example illustrates how to retrieve webhook log summaries.
         */

        /// <summary>
        /// Gets a chunk of webhook log summaries
        /// </summary>
        /// <param name="webhookApi">The webhook API instance</param>
        /// <param name="offset">Offset for pagination</param>
        /// <param name="limit">Maximum number of records to return</param>
        /// <returns>Array of webhook log summaries</returns>
        /// <exception cref="ApiException">Thrown when API call fails</exception>
        private static List<WebhookLogSummary> GetSummaryChunk(WebhookApi webhookApi, int offset, int limit)
        {
            int webhookOid = 123456789; // if you don't know this, use getWebhooks to find your webhook, then get its oid.
            string since = DateTime.Now.AddDays(-10).ToString("yyyy-MM-dd") + "T00:00:00+00:00"; // get the last 10 days
            // Pay attention to whether limit or offset comes first in the method signature. UltraCart is not consistent with their ordering.
            WebhookLogSummariesResponse apiResponse = webhookApi.GetWebhookLogSummaries(webhookOid, limit, offset, since);

            if (apiResponse.WebhookLogSummaries != null)
            {
                return apiResponse.WebhookLogSummaries;
            }
            return new List<WebhookLogSummary>();
        }

        public static void Execute()
        {
            WebhookApi webhookApi = new WebhookApi(Constants.ApiKey);
            
            List<WebhookLogSummary> summaries = new List<WebhookLogSummary>();

            int iteration = 1;
            int offset = 0;
            int limit = 200;
            bool moreRecordsToFetch = true;

            try
            {
                while (moreRecordsToFetch)
                {
                    Console.WriteLine("executing iteration " + iteration);

                    List<WebhookLogSummary> chunkOfSummaries = GetSummaryChunk(webhookApi, offset, limit);
                    summaries.AddRange(chunkOfSummaries);
                    offset = offset + limit;
                    moreRecordsToFetch = chunkOfSummaries.Count == limit;
                    iteration++;
                }
            }
            catch (ApiException e)
            {
                Console.WriteLine("ApiException occurred on iteration " + iteration);
                Console.WriteLine(e.ToString());
                Environment.Exit(1);
            }

            // this will be verbose...
            foreach (WebhookLogSummary summary in summaries)
            {
                Console.WriteLine(summary.ToString());
            }
        }
    }
}
package webhook;

import com.ultracart.admin.v2.WebhookApi;
import com.ultracart.admin.v2.models.*;
import com.ultracart.admin.v2.util.ApiException;
import common.Constants;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.List;

public class GetWebhookLogSummaries {
   /*
    * This example illustrates how to retrieve webhook log summaries.
    */

   /**
    * Gets a chunk of webhook log summaries
    * @param webhookApi The webhook API instance
    * @param offset Offset for pagination
    * @param limit Maximum number of records to return
    * @return Array of webhook log summaries
    * @throws ApiException Thrown when API call fails
    */
   private static List<WebhookLogSummary> getSummaryChunk(WebhookApi webhookApi, int offset, int limit) throws ApiException {
       int webhookOid = 123456789; // if you don't know this, use getWebhooks to find your webhook, then get its oid.
       String since = Instant.now().minus(10, ChronoUnit.DAYS).toString(); // get the last 10 days
       // Pay attention to whether limit or offset comes first in the method signature. UltraCart is not consistent with their ordering.
       WebhookLogSummariesResponse apiResponse = webhookApi.getWebhookLogSummaries(webhookOid, limit, offset, since);

       if (apiResponse.getWebhookLogSummaries() != null) {
           return apiResponse.getWebhookLogSummaries();
       }
       return new ArrayList<WebhookLogSummary>();
   }

   public static void execute() {
       WebhookApi webhookApi = new WebhookApi(Constants.API_KEY);
       
       List<WebhookLogSummary> summaries = new ArrayList<WebhookLogSummary>();

       int iteration = 1;
       int offset = 0;
       int limit = 200;
       boolean moreRecordsToFetch = true;

       try {
           while (moreRecordsToFetch) {
               System.out.println("executing iteration " + iteration);

               List<WebhookLogSummary> chunkOfSummaries = getSummaryChunk(webhookApi, offset, limit);
               summaries.addAll(chunkOfSummaries);
               offset = offset + limit;
               moreRecordsToFetch = chunkOfSummaries.size() == limit;
               iteration++;
           }
       } catch (ApiException e) {
           System.out.println("ApiException occurred on iteration " + iteration);
           System.out.println(e.toString());
           System.exit(1);
       }

       // this will be verbose...
       for (WebhookLogSummary summary : summaries) {
           System.out.println(summary.toString());
       }
   }
}
// Import API and UltraCart types
import { webhookApi } from '../api.js';
import { DateTime } from 'luxon';

// Namespace-like structure using a class
export class GetWebhookLogSummaries {
  /*
   * This example illustrates how to retrieve webhook log summaries.
   */

  /**
   * Gets a chunk of webhook log summaries
   * @param offset Offset for pagination
   * @param limit Maximum number of records to return
   * @returns Array of webhook log summaries
   * @throws Error when API call fails
   */
  static async getSummaryChunk(offset, limit) {
    const webhookOid = 123456789; // if you don't know this, use getWebhooks to find your webhook, then get its oid
    const since = DateTime.now()
      .setZone('America/New_York')
      .minus({ days: 10 })
      .startOf('day')
      .toISO(); // get the last 10 days in ISO8601 format

    // UltraCart API call with parameters as an anonymous object
    const opts = {
      _limit: limit,
      _offset: offset,
      _since: since,
    };

    const apiResponse = await new Promise((resolve, reject) => {
      webhookApi.getWebhookLogSummaries(webhookOid, opts, function (error, data, response) {
        if (error) {
          reject(error);
        } else {
          resolve(data, response);
        }
      });
    });

    if (apiResponse.webhook_log_summaries) {
      return apiResponse.webhook_log_summaries;
    }
    return [];
  }

  static async execute() {
    const summaries = [];

    let iteration = 1;
    let offset = 0;
    const limit = 200;
    let moreRecordsToFetch = true;

    try {
      while (moreRecordsToFetch) {
        console.log(`executing iteration ${iteration}`);

        const chunkOfSummaries = await this.getSummaryChunk(offset, limit);
        summaries.push(...chunkOfSummaries);
        offset += limit;
        moreRecordsToFetch = chunkOfSummaries.length === limit;
        iteration++;
      }

      // this will be verbose...
      for (const summary of summaries) {
        console.log(summary); // No ToString() in TS; outputs JSON-like object
      }
    } catch (ex) {
      console.log(`Error occurred on iteration ${iteration}`);
      console.log(ex.toString());
      process.exit(1); // Equivalent to Environment.Exit(1) in Node.js
    }
  }
}
<?php

set_time_limit(3000); // pulling all records could take a long time.
ini_set('max_execution_time', 3000);
ini_set('display_errors', 1);

/*
 * This example illustrates how to retrieve webhook log summaries.
 */

use ultracart\v2\api\WebhookApi;
use ultracart\v2\ApiException;

require_once '../vendor/autoload.php';
require_once '../samples.php';


$webhook_api = WebhookApi::usingApiKey(Constants::API_KEY);


/**
 * @throws ApiException
 */
function getSummaryChunk(WebhookApi $webhook_api, int $offset, int $limit): array
{
    $webhook_oid = 123456789; // if you don't know this, use getWebhooks to find your webhook, then get its oid.
    $_since = date('Y-m-d', strtotime('-10 days')) . "T00:00:00+00:00"; // get the last 10 days
    // Pay attention to whether limit or offset comes first in the method signature.  UltraCart is not consistent with their ordering.
    $api_response = $webhook_api->getWebhookLogSummaries($webhook_oid, $limit, $offset, $_since);

    if ($api_response->getWebhookLogSummaries() != null) {
        return $api_response->getWebhookLogSummaries();
    }
    return [];
}

$summaries = [];

$iteration = 1;
$offset = 0;
$limit = 200;
$more_records_to_fetch = true;

try {
    while ($more_records_to_fetch) {

        echo "executing iteration " . $iteration . '<br>';

        $chunk_of_summaries = getSummaryChunk($webhook_api, $offset, $limit);
        $orders = array_merge($summaries, $chunk_of_summaries);
        $offset = $offset + $limit;
        $more_records_to_fetch = count($chunk_of_summaries) == $limit;
        $iteration++;
    }
} catch (ApiException $e) {
    echo 'ApiException occurred on iteration ' . $iteration;
    var_dump($e);
    die(1);
}


// this will be verbose...
var_dump($summaries);
"""
This example illustrates how to retrieve webhook log summaries.
"""

from datetime import datetime, timedelta
from ultracart.apis import WebhookApi
from ultracart.exceptions import ApiException
from samples import api_client


def get_summary_chunk(webhook_api, offset, limit):
    """Retrieve a chunk of webhook log summaries."""
    webhook_oid = 123456789  # Use getWebhooks to find your webhook's oid
    _since = (datetime.now() - timedelta(days=10)).strftime('%Y-%m-%dT00:00:00+00:00')

    api_response = webhook_api.get_webhook_log_summaries(webhook_oid=webhook_oid, limit=limit, offset=offset,
                                                         since=_since)
    return api_response.webhook_log_summaries or []


def retrieve_all_summaries():
    """Retrieve all webhook log summaries in chunks."""
    webhook_api = WebhookApi(api_client())

    summaries = []
    iteration = 1
    offset = 0
    limit = 200

    try:
        while True:
            print(f"executing iteration {iteration}")

            chunk_of_summaries = get_summary_chunk(webhook_api, offset, limit)
            summaries.extend(chunk_of_summaries)

            offset += limit
            if len(chunk_of_summaries) < limit:
                break

            iteration += 1

    except ApiException as e:
        print(f'ApiException occurred on iteration {iteration}')
        print(e)
        return None

    return summaries


# Retrieve and print summaries
all_summaries = retrieve_all_summaries()
if all_summaries is not None:
    print(all_summaries)
require 'ultracart_api'
require_relative '../constants'

# This example illustrates how to retrieve webhook log summaries.

webhook_api = UltracartClient::WebhookApi.new_using_api_key(Constants::API_KEY)

def get_summary_chunk(webhook_api, offset, limit)
  webhook_oid = 123456789 # if you don't know this, use getWebhooks to find your webhook, then get its oid.
  _since = (Date.today - 10).strftime('%Y-%m-%d') + "T00:00:00+00:00" # get the last 10 days
  # Pay attention to whether limit or offset comes first in the method signature.  UltraCart is not consistent with their ordering.
  api_response = webhook_api.get_webhook_log_summaries(webhook_oid, limit, offset, _since)

  return api_response.webhook_log_summaries if api_response.webhook_log_summaries
  []
end

summaries = []

iteration = 1
offset = 0
limit = 200
more_records_to_fetch = true

begin
  while more_records_to_fetch
    puts "executing iteration #{iteration}"

    chunk_of_summaries = get_summary_chunk(webhook_api, offset, limit)
    summaries.concat(chunk_of_summaries)
    offset = offset + limit
    more_records_to_fetch = chunk_of_summaries.length == limit
    iteration += 1
  end
rescue UltracartClient::ApiError => e
  puts "ApiError occurred on iteration #{iteration}"
  puts e.inspect
  exit 1
end

# this will be verbose...
puts summaries.inspect
// Import API and UltraCart types
import { webhookApi } from '../api';
import { WebhookLogSummary } from 'ultracart_rest_api_v2_typescript';
import { DateTime } from 'luxon';

// Namespace-like structure using a class
export class GetWebhookLogSummaries {
  /*
   * This example illustrates how to retrieve webhook log summaries.
   */

  /**
   * Gets a chunk of webhook log summaries
   * @param offset Offset for pagination
   * @param limit Maximum number of records to return
   * @returns Array of webhook log summaries
   * @throws Error when API call fails
   */
  private static async getSummaryChunk(offset: number, limit: number): Promise<WebhookLogSummary[]> {
    const webhookOid = 123456789; // if you don't know this, use getWebhooks to find your webhook, then get its oid
    const since = DateTime.now()
      .setZone('America/New_York')
      .minus({ days: 10 })
      .startOf('day')
      .toISO(); // get the last 10 days in ISO8601 format

    // UltraCart API call with parameters as an anonymous interface
    // Note: Order of limit/offset may vary; adjust based on SDK signature
    const apiResponse = await webhookApi.getWebhookLogSummaries({
      webhookOid: webhookOid,
      limit: limit,
      offset: offset,
      since: since,
    });

    if (apiResponse.webhook_log_summaries) {
      return apiResponse.webhook_log_summaries;
    }
    return [];
  }

  public static async execute(): Promise<void> {
    const summaries: WebhookLogSummary[] = [];

    let iteration = 1;
    let offset = 0;
    const limit = 200;
    let moreRecordsToFetch = true;

    try {
      while (moreRecordsToFetch) {
        console.log(`executing iteration ${iteration}`);

        const chunkOfSummaries = await this.getSummaryChunk(offset, limit);
        summaries.push(...chunkOfSummaries);
        offset += limit;
        moreRecordsToFetch = chunkOfSummaries.length === limit;
        iteration++;
      }

      // this will be verbose...
      for (const summary of summaries) {
        console.log(summary); // No ToString() in TS; outputs JSON-like object
      }
    } catch (ex) {
      console.log(`Error occurred on iteration ${iteration}`);
      console.log((ex as Error).toString());
      process.exit(1); // Equivalent to Environment.Exit(1) in Node.js
    }
  }
}

Retrieve an individual log

Permissions:
  • webhook_read

Produces: application/json
get
/webhook/webhooks/{webhookOid}/logs/{requestId}

Retrieves an individual log for a webhook given the webhook oid the request id.

SDK Function Name: getWebhookLog

Parameters
Parameter Description Location Data Type Required
webhookOid The webhook oid that owns the log. path integer (int32) required
requestId The request id associated with the log to view. path string required
Responses
Status Code Reason Response Model
200
Successful response WebhookLogResponse
400
Bad Request 400
401
Unauthorized 401
410
Authorized Application Disabled 410
429
Too Many Requests 429
500
Server Side 500
using System;
using com.ultracart.admin.v2.Api;
using com.ultracart.admin.v2.Model;

namespace SdkSample.webhook
{
    public class GetWebhookLog
    {
        public static void Execute()
        {
            /*
             * getWebhookLog() provides a detail log of a webhook event. It is used in tandem with getWebhookLogSummaries to audit
             * webhook events. This method call will require the webhook_oid and the request_id. The webhook_oid can be discerned
             * from the results of getWebhooks() and the request_id can be found from getWebhookLogSummaries(). see those examples
             * if needed.
             */

            WebhookApi webhookApi = new WebhookApi(Constants.ApiKey);

            int webhookOid = 123456789; // call getWebhooks if you don't know this.
            string requestId = "987654321";  // call getWebhookLogSummaries if you don't know this.

            WebhookLogResponse apiResponse = webhookApi.GetWebhookLog(webhookOid, requestId);
            WebhookLog webhookLog = apiResponse.WebhookLog;

            if (apiResponse.Error != null)
            {
                Console.Error.WriteLine(apiResponse.Error.DeveloperMessage);
                Console.Error.WriteLine(apiResponse.Error.UserMessage);
                Environment.Exit(1);
            }

            Console.WriteLine("<html lang=\"en\"><body><pre>");
            Console.WriteLine(webhookLog.ToString());
            Console.WriteLine("</pre></body></html>");
        }
    }
}
package webhook;

import com.ultracart.admin.v2.WebhookApi;
import com.ultracart.admin.v2.models.*;
import com.ultracart.admin.v2.util.ApiException;
import common.Constants;

public class GetWebhookLog {
   public static void execute() throws ApiException {
       /*
        * getWebhookLog() provides a detail log of a webhook event. It is used in tandem with getWebhookLogSummaries to audit
        * webhook events. This method call will require the webhook_oid and the request_id. The webhook_oid can be discerned
        * from the results of getWebhooks() and the request_id can be found from getWebhookLogSummaries(). see those examples
        * if needed.
        */

       WebhookApi webhookApi = new WebhookApi(Constants.API_KEY);

       int webhookOid = 123456789; // call getWebhooks if you don't know this.
       String requestId = "987654321";  // call getWebhookLogSummaries if you don't know this.

       WebhookLogResponse apiResponse = webhookApi.getWebhookLog(webhookOid, requestId);
       WebhookLog webhookLog = apiResponse.getWebhookLog();

       if (apiResponse.getError() != null) {
           System.err.println(apiResponse.getError().getDeveloperMessage());
           System.err.println(apiResponse.getError().getUserMessage());
           System.exit(1);
       }

       System.out.println(webhookLog.toString());
   }
}
// Import API and UltraCart types
import { webhookApi } from '../api.js';

// Namespace-like structure using a class
export class GetWebhookLog {
  static async execute() {
    /*
     * getWebhookLog() provides a detail log of a webhook event. It is used in tandem with getWebhookLogSummaries to audit
     * webhook events. This method call will require the webhook_oid and the request_id. The webhook_oid can be discerned
     * from the results of getWebhooks() and the request_id can be found from getWebhookLogSummaries(). See those examples
     * if needed.
     */
    try {
      const webhookOid = 123456789; // call getWebhooks if you don't know this
      const requestId = "987654321"; // call getWebhookLogSummaries if you don't know this

      // UltraCart API call with parameters as an anonymous object
      const apiResponse = await new Promise((resolve, reject) => {
        webhookApi.getWebhookLog(webhookOid,requestId, function (error, data, response) {
          if (error) {
            reject(error);
          } else {
            resolve(data, response);
          }
        });
      });

      const webhookLog = apiResponse.webhook_log;

      if (apiResponse.error) {
        console.error(apiResponse.error.developer_message);
        console.error(apiResponse.error.user_message);
        process.exit(1); // Equivalent to Environment.Exit(1) in Node.js
      }

      // For Node.js/console output (adjust for other environments)
      console.log(webhookLog); // JSON-like object output; no ToString() equivalent in TS by default
    } catch (ex) {
      console.log(`Error: ${ex.message}`);
      console.log(ex.stack);
    }
  }
}
<?php

ini_set('display_errors', 1);

/*

getWebhookLog() provides a detail log of a webhook event.  It is used in tandem with getWebhookLogSummaries to audit
webhook events.  This method call will require the webhook_oid and the request_id.  The webhook_oid can be discerned
from the results of getWebhooks() and the request_id can be found from getWebhookLogSummaries().  see those examples
if needed.

*/


use ultracart\v2\api\WebhookApi;

require_once '../vendor/autoload.php';
require_once '../constants.php';


$webhook_api = WebhookApi::usingApiKey(Constants::API_KEY);

$webhook_oid = 123456789; // call getWebhooks if you don't know this.
$request_id = '987654321';  // call getWebhookLogSummaries if you don't know this.

$api_response = $webhook_api->getWebhookLog($webhook_oid, $request_id);
$webhook_log = $api_response->getWebhookLog();

if ($api_response->getError() != null) {
    error_log($api_response->getError()->getDeveloperMessage());
    error_log($api_response->getError()->getUserMessage());
    exit();
}

echo '<html lang="en"><body><pre>';
var_dump($webhook_log);
echo '</pre></body></html>';

"""
getWebhookLog() provides a detail log of a webhook event.  It is used in tandem with getWebhookLogSummaries to audit
webhook events.  This method call will require the webhook_oid and the request_id.  The webhook_oid can be discerned
from the results of getWebhooks() and the request_id can be found from getWebhookLogSummaries().  see those examples
if needed.
"""

from ultracart.apis import WebhookApi
from samples import api_client

# Create Webhook API instance
webhook_api = WebhookApi(api_client())

# webhook_oid and request_id (call getWebhooks and getWebhookLogSummaries if you don't know these)
webhook_oid = 123456789
request_id = '987654321'

# Get webhook log
api_response = webhook_api.get_webhook_log(webhook_oid=webhook_oid, request_id=request_id)
webhook_log = api_response.webhook_log

# Check for errors
if api_response.error:
   print(f"Developer Message: {api_response.error.developer_message}")
   print(f"User Message: {api_response.error.user_message}")
else:
   # Print webhook log
   print(webhook_log)
require 'ultracart_api'
require_relative '../constants'

# getWebhookLog() provides a detail log of a webhook event.  It is used in tandem with getWebhookLogSummaries to audit
# webhook events.  This method call will require the webhook_oid and the request_id.  The webhook_oid can be discerned
# from the results of getWebhooks() and the request_id can be found from getWebhookLogSummaries().  see those examples
# if needed.

webhook_api = UltracartClient::WebhookApi.new_using_api_key(Constants::API_KEY)

webhook_oid = 123456789 # call getWebhooks if you don't know this.
request_id = '987654321'  # call getWebhookLogSummaries if you don't know this.

api_response = webhook_api.get_webhook_log(webhook_oid, request_id)
webhook_log = api_response.webhook_log

if api_response.error
  puts api_response.error.developer_message
  puts api_response.error.user_message
  exit
end

puts webhook_log
// Import API and UltraCart types
import { webhookApi } from '../api';
import { WebhookLog, WebhookLogResponse } from 'ultracart_rest_api_v2_typescript';

// Namespace-like structure using a class
export class GetWebhookLog {
  public static async execute(): Promise<void> {
    /*
     * getWebhookLog() provides a detail log of a webhook event. It is used in tandem with getWebhookLogSummaries to audit
     * webhook events. This method call will require the webhook_oid and the request_id. The webhook_oid can be discerned
     * from the results of getWebhooks() and the request_id can be found from getWebhookLogSummaries(). See those examples
     * if needed.
     */
    try {
      const webhookOid = 123456789; // call getWebhooks if you don't know this
      const requestId = "987654321"; // call getWebhookLogSummaries if you don't know this

      // UltraCart API call with parameters as an anonymous interface
      const apiResponse = await webhookApi.getWebhookLog({
        webhookOid: webhookOid,
        requestId: requestId,
      });

      const webhookLog: WebhookLog | undefined = apiResponse.webhook_log;

      if (apiResponse.error) {
        console.error(apiResponse.error.developer_message);
        console.error(apiResponse.error.user_message);
        process.exit(1); // Equivalent to Environment.Exit(1) in Node.js
      }

      // For Node.js/console output (adjust for other environments)
      console.log(webhookLog); // JSON-like object output; no ToString() equivalent in TS by default
    } catch (ex) {
      console.log(`Error: ${(ex as Error).message}`);
      console.log((ex as Error).stack);
    }
  }
}


Resend events to the webhook endpoint.

Permissions:
  • webhook_write

Produces: application/json
post
/webhook/webhooks/{webhookOid}/reflow/{eventName}

This method will resend events to the webhook endpoint. This method can be used for example to send all the existing items on an account to a webhook.

SDK Function Name: resendEvent

Parameters
Parameter Description Location Data Type Required
webhookOid The webhook oid that is receiving the reflowed events. path integer (int32) required
eventName The event to reflow.
Allowed Values
  • item_update
  • order_create
path string required
Responses
Status Code Reason Response Model
200
Successful response WebhookReflowResponse
400
Bad Request 400
401
Unauthorized 401
410
Authorized Application Disabled 410
429
Too Many Requests 429
500
Server Side 500
using System;
using com.ultracart.admin.v2.Api;
using com.ultracart.admin.v2.Model;

namespace SdkSample.webhook
{
    public class ResendEvent
    {
        public static void Execute()
        {
            /*
             * resentEvent is used to reflow an event.  It will resend ALL events in history.  So it is essentially a way to
             * get all objects from an event.  Currently, there are only two events available for reflow: "item_update", and "order_create".
             * These two events provide the means to have a webhook receive all items or orders.  This method is usually called
             * at the beginning of a webhook's life to prepopulate a merchant's database with all items or orders.
             *
             * You will need the webhook_oid to call this method.  Call getWebhooks() if you don't know your oid.
             */

            WebhookApi webhookApi = new WebhookApi(Constants.ApiKey);

            int webhookOid = 123456789; // call getWebhooks if you don't know this.
            string eventName = "item_update"; // or "order_create", but for this sample, we want all items.

            WebhookReflowResponse apiResponse = webhookApi.ResendEvent(webhookOid, eventName);
            WebhookReflow reflow = apiResponse.Reflow;
            bool success = reflow.Queued;

            if (apiResponse.Error != null)
            {
                Console.Error.WriteLine(apiResponse.Error.DeveloperMessage);
                Console.Error.WriteLine(apiResponse.Error.UserMessage);
                Environment.Exit(1);
            }

            Console.WriteLine(apiResponse.ToString());
        }
    }
}
package webhook;

import com.ultracart.admin.v2.WebhookApi;
import com.ultracart.admin.v2.models.WebhookReflowResponse;
import com.ultracart.admin.v2.models.WebhookReflow;
import com.ultracart.admin.v2.util.ApiException;

import common.Constants;

public class ResendEvent {
    public static void execute() {
        /*
         * resentEvent is used to reflow an event.  It will resend ALL events in history.  So it is essentially a way to
         * get all objects from an event.  Currently, there are only two events available for reflow: "item_update", and "order_create".
         * These two events provide the means to have a webhook receive all items or orders.  This method is usually called
         * at the beginning of a webhook's life to prepopulate a merchant's database with all items or orders.
         *
         * You will need the webhook_oid to call this method.  Call getWebhooks() if you don't know your oid.
         */

        WebhookApi webhookApi = new WebhookApi(Constants.API_KEY);

        int webhookOid = 123456789; // call getWebhooks if you don't know this.
        String eventName = "item_update"; // or "order_create", but for this sample, we want all items.

        try {
            WebhookReflowResponse apiResponse = webhookApi.resendEvent(webhookOid, eventName);
            WebhookReflow reflow = apiResponse.getReflow();
            boolean success = reflow.getQueued();

            if (apiResponse.getError() != null) {
                System.err.println(apiResponse.getError().getDeveloperMessage());
                System.err.println(apiResponse.getError().getUserMessage());
                System.exit(1);
            }

            System.out.println(apiResponse.toString());
        } catch (ApiException e) {
            System.err.println("API Exception occurred: " + e.getMessage());
            e.printStackTrace();
            System.exit(1);
        }
    }
}
import { webhookApi } from '../api.js';

export class ResendEvent {
    /**
     * ResendEvent is used to reflow an event. It will resend ALL events in history.
     * So it is essentially a way to get all objects from an event. Currently, there are
     * only two events available for reflow: "item_update", and "order_create".
     *
     * These two events provide the means to have a webhook receive all items or orders.
     * This method is usually called at the beginning of a webhook's life to prepopulate
     * a merchant's database with all items or orders.
     *
     * You will need the webhook_oid to call this method. Call getWebhooks() if you don't know your oid.
     */
    static async execute() {
        const webhookOid = 123456789; // call getWebhooks if you don't know this.
        const eventName = "item_update"; // or "order_create", but for this sample, we want all items.

        try {
            const apiResponse = await new Promise((resolve, reject) => {
                webhookApi.resendEvent(webhookOid, eventName, function (error, data, response) {
                    if (error) {
                        reject(error);
                    } else {
                        resolve(data, response);
                    }
                });
            });

            const reflow = apiResponse.reflow;
            const success = !!(reflow && reflow.queued);

            if (apiResponse.error) {
                console.error(apiResponse.error.developer_message);
                console.error(apiResponse.error.user_message);
                process.exit(1);
            }

            console.log(apiResponse.toString());
        } catch (error) {
            console.error('Error resending event:', error);
            process.exit(1);
        }
    }
}

// Optional: If you want to run this directly
if (require.main === module) {
    ResendEvent.execute().catch(console.error);
}
<?php

ini_set('display_errors', 1);

/*

resentEvent is used to reflow an event.  It will resend ALL events in history.  So it is essentially a way to
get all objects from an event.  Currently, there are only two events available for reflow: "item_update", and "order_create".
These two events provide the means to have a webhook receive all items or orders.  This method is usually called
at the beginning of a webhook's life to prepopulate a merchant's database with all items or orders.

You will need the webhook_oid to call this method.  Call getWebhooks() if you don't know your oid.

*/


use ultracart\v2\api\WebhookApi;

require_once '../vendor/autoload.php';
require_once '../constants.php';


$webhook_api = WebhookApi::usingApiKey(Constants::API_KEY);

$webhook_oid = 123456789; // call getWebhooks if you don't know this.
$event_name = "item_update"; // or "order_create", but for this sample, we want all items.

$api_response = $webhook_api->resendEvent($webhook_oid, $event_name);
$reflow = $api_response->getReflow();
$success = $reflow->getQueued();

if ($api_response->getError() != null) {
    error_log($api_response->getError()->getDeveloperMessage());
    error_log($api_response->getError()->getUserMessage());
    exit();
}

echo '<html lang="en"><body><pre>';
var_dump($api_response);
echo '</pre></body></html>';

"""
Resend a specific event for a webhook to reflow all historical data.
Supports 'item_update' and 'order_create' events.
"""

from ultracart.apis import WebhookApi
from samples import api_client

def resend_webhook_event():
   webhook_api = WebhookApi(api_client())

   webhook_oid = 123456789  # Use getWebhooks to find your webhook's oid
   event_name = "item_update"  # or "order_create"

   api_response = webhook_api.resend_event(webhook_oid=webhook_oid, event_name=event_name)

   if api_response.error:
       print(f"Developer Message: {api_response.error.developer_message}")
       print(f"User Message: {api_response.error.user_message}")
       return None

   reflow = api_response.reflow
   success = reflow.queued

   return api_response

# Execute event resend
result = resend_webhook_event()
if result:
   print(result)
require 'ultracart_api'
require_relative '../constants'

# resentEvent is used to reflow an event.  It will resend ALL events in history.  So it is essentially a way to
# get all objects from an event.  Currently, there are only two events available for reflow: "item_update", and "order_create".
# These two events provide the means to have a webhook receive all items or orders.  This method is usually called
# at the beginning of a webhook's life to prepopulate a merchant's database with all items or orders.
#
# You will need the webhook_oid to call this method.  Call getWebhooks() if you don't know your oid.

webhook_api = UltracartClient::WebhookApi.new_using_api_key(Constants::API_KEY)

webhook_oid = 123456789 # call getWebhooks if you don't know this.
event_name = "item_update" # or "order_create", but for this sample, we want all items.

api_response = webhook_api.resend_event(webhook_oid, event_name)
reflow = api_response.reflow
success = reflow.queued

if api_response.error
  puts api_response.error.developer_message
  puts api_response.error.user_message
  exit
end

puts api_response.inspect
import { webhookApi } from '../api';
import {
    WebhookReflowResponse,
    WebhookReflow
} from 'ultracart_rest_api_v2_typescript';

export class ResendEvent {
    /**
     * ResendEvent is used to reflow an event. It will resend ALL events in history.
     * So it is essentially a way to get all objects from an event. Currently, there are
     * only two events available for reflow: "item_update", and "order_create".
     *
     * These two events provide the means to have a webhook receive all items or orders.
     * This method is usually called at the beginning of a webhook's life to prepopulate
     * a merchant's database with all items or orders.
     *
     * You will need the webhook_oid to call this method. Call getWebhooks() if you don't know your oid.
     */
    public static async execute(): Promise<void> {
        const webhookOid: number = 123456789; // call getWebhooks if you don't know this.
        const eventName: string = "item_update"; // or "order_create", but for this sample, we want all items.

        try {
            const apiResponse: WebhookReflowResponse = await webhookApi.resendEvent({webhookOid, eventName});
            const reflow: WebhookReflow | undefined = apiResponse.reflow;
            const success: boolean  = !!(reflow && reflow.queued);

            if (apiResponse.error) {
                console.error(apiResponse.error.developer_message);
                console.error(apiResponse.error.user_message);
                process.exit(1);
            }

            console.log(apiResponse.toString());
        } catch (error) {
            console.error('Error resending event:', error);
            process.exit(1);
        }
    }
}

// Optional: If you want to run this directly
if (require.main === module) {
    ResendEvent.execute().catch(console.error);
}

ApiUserApplicationProfile

Attributes
Name Data Type Description
api_application_logo_url string Application logo URL
application_description string Application description
application_name string Application name
developer_name string Developer name
developer_website string Developer website

Error

Attributes
Name Data Type Description
developer_message string A technical message meant to be read by a developer
error_code string HTTP status code
more_info string Additional information often a link to additional documentation
object_id string Object id that the error is associated with
user_message string An end-user friendly message suitable for display to the customer

ErrorResponse

Attributes
Name Data Type Description
error Error Error object if unsuccessful
metadata ResponseMetadata Meta-data about the response such as payload or paging information
success boolean Indicates if API call was successful
warning Warning Warning object if a non-fatal issue or side-effect occurs

HTTPHeader

Attributes
Name Data Type Description
name string Name of the HTTP header
value string Value of the HTTP header

ResponseMetadata

Attributes
Name Data Type Description
payload_name string Payload name
result_set ResultSet Result set

ResultSet

Attributes
Name Data Type Description
count integer (int32) Number of results in this set
limit integer (int32) Maximum number of results that can be returned in a set
more boolean True if there are more results to query
next_offset integer (int32) The next offset that you should query to retrieve more results
offset integer (int32) Offset of this result set (zero based)
total_records integer (int32) The total number of records in the result set. May be null if the number is not known and the client should continue iterating as long as more is true.

Warning

Attributes
Name Data Type Description
more_info string Additional information often a link to additional documentation
warning_message string A technical message meant to be read by a developer

Webhook

Attributes
Name Data Type Description
api_user_oid (read only) integer (int32) Populated if webhook associated with an API user
api_version string Version of the API objects that are sent in notifications
Allowed Values
  • 2017-03-01
application_profile (read only) ApiUserApplicationProfile If associate with an application, the profile for that application
authentication_type string The type of authentication this webhook will use when communicating with your server
Allowed Values
  • none
  • basic
  • api user
  • aws iam
basic_password string Basic authentication password
basic_username string Basic authentication user name
compress_events boolean Compress events with GZIP then base 64 encode them as a string
consecutive_failures (read only) integer (int32) The number of consecutive failures that have occurred trying to deliver notifications to the target server
disabled (read only) boolean True if the webhook has been disabled
event_categories array of WebhookEventCategory The categories of events. Individual events and subscriptions are handled in the child objects. _placeholders parameter effects the population of this on a retrieval.
iam_access_key string IAM Access Key for AWS SQS Delivery
iam_secret_key string IAM Secret Key for AWS SQS Delivery
maximum_events integer (int32) The maximum number of events in the payload that UltraCart will deliver
maximum_size integer (int32) The maximum size of the payload that UltraCart will deliver
merchant_id (read only) string The UltraCart merchant ID that owns this webhook
next_retry_after (read only) string (dateTime) The next time UltraCart will attempt delivery if failures have been occurring
pending (read only) integer (int32) The number of pending events for this webhook
webhook_oid (read only) integer (int32) The object identifier for this webhook
webhook_url string The URL to deliver events to. Must be HTTPS for customer related information.

WebhookEventCategory

Attributes
Name Data Type Description
any_subscribed (read only) boolean True if any events are subscribed to.
available_expansions array of string Array of available expansion constants
event_category string Name of the event category
events array of WebhookEventSubscription The events within the category. Individual subscription flags contained within the child object.
subscribed (read only) boolean True if all the events within this category are subscribed. This is a convenience flag to make user interfaces easier.

WebhookEventSubscription

Attributes
Name Data Type Description
comments (read only) string Comment about the event to provide further clarification to the end user
deprecated_flag (read only) boolean True if the event is deprecated. See the API change log for details on when it will be discontinued.
discontinued_flag (read only) boolean True if the event is discontinued. See the API change log for details on migration details.
event_description (read only) string Description of the event
event_name string Event name
event_ruler string Optional - Event ruler expression to filter events to. Only events that match this Ruler expression will be transmitted to the webhook.
expansion string The expand string for the notification object. See the individual resource _expand documentation for valid values.
subscribed boolean True if this is event is subscribed to
supports_reflow (read only) boolean True if the event can be triggered to reflow existing records
webhook_event_oid (read only) integer (int32) The webhook event object identifier

WebhookLog

Attributes
Name Data Type Description
delivery_dts (read only) string (dateTime) Date/time of delivery
duration (read only) integer (int32) Number of milliseconds to process the notification
queue_delay (read only) integer (int64) Number of milliseconds of delay caused by queuing
request (read only) string Request payload (first 100,000 characters)
request_headers (read only) array of HTTPHeader Request headers sent to the server
request_id (read only) string Request id is a unique string that you can look up in the logs
response (read only) string Response payload (first 100,000 characters)
response_headers (read only) array of HTTPHeader Response headers received from the server
status_code (read only) integer (int32) HTTP status code received from the server
success (read only) boolean True if the delivery was successful
uri (read only) string URI of the webhook delivered to
webhook_oid (read only) integer (int32) webhook oid

WebhookLogResponse

Attributes
Name Data Type Description
error Error Error object if unsuccessful
metadata ResponseMetadata Meta-data about the response such as payload or paging information
success boolean Indicates if API call was successful
warning Warning Warning object if a non-fatal issue or side-effect occurs
webhook_log WebhookLog Individual webhook log

WebhookLogSummariesResponse

Attributes
Name Data Type Description
error Error Error object if unsuccessful
metadata ResponseMetadata Meta-data about the response such as payload or paging information
success boolean Indicates if API call was successful
warning Warning Warning object if a non-fatal issue or side-effect occurs
webhook_log_summaries array of WebhookLogSummary Webhook log summaries

WebhookLogSummary

Attributes
Name Data Type Description
delivery_dts (read only) string (dateTime) Date/time of the delivery
request_id (read only) string Request id
success (read only) boolean True if the notification was successful

WebhookReflow

Attributes
Name Data Type Description
event_name string
queued boolean

WebhookReflowResponse

Attributes
Name Data Type Description
error Error Error object if unsuccessful
metadata ResponseMetadata Meta-data about the response such as payload or paging information
reflow WebhookReflow
success boolean Indicates if API call was successful
warning Warning Warning object if a non-fatal issue or side-effect occurs

WebhookResponse

Attributes
Name Data Type Description
error Error Error object if unsuccessful
metadata ResponseMetadata Meta-data about the response such as payload or paging information
success boolean Indicates if API call was successful
warning Warning Warning object if a non-fatal issue or side-effect occurs
webhook Webhook Webhook

WebhooksResponse

Attributes
Name Data Type Description
error Error Error object if unsuccessful
metadata ResponseMetadata Meta-data about the response such as payload or paging information
success boolean Indicates if API call was successful
warning Warning Warning object if a non-fatal issue or side-effect occurs
webhooks array of Webhook

400
Status Code 400: bad request input such as invalid json

Headers
Name Data Type Description
UC-REST-ERROR string Contains human readable error message
Response
Name Data Type
body ErrorResponse

401
Status Code 401: invalid credentials supplied

Headers
Name Data Type Description
UC-REST-ERROR string Contains human readable error message
Response
Name Data Type
body ErrorResponse

410
Status Code 410: Your authorized application has been disabled by UltraCart

Headers
Name Data Type Description
UC-REST-ERROR string Contains human readable error message
Response
Name Data Type
body ErrorResponse

429
Status Code 429: you have exceeded the allowed API call rate limit for your application.

Headers
Name Data Type Description
UC-REST-ERROR string Contains human readable error message
Response
Name Data Type
body ErrorResponse

500
Status Code 500: any server side error. the body will contain a generic server error message

Headers
Name Data Type Description
UC-REST-ERROR string Contains human readable error message
Response
Name Data Type
body ErrorResponse