NetSuite PHP API Client

repository·master·Indexed 42 days ago

https://github.com/netsuitephp/netsuite-php

A modern PHP API client and wrapper (NetSuiteService) for the official NetSuite PHP Toolkit. It simplifies authentication via Token-Based Authentication (TBA), environment variable configuration, and logging. The library supports account-specific data center URL detection for versions 2021_1 and later, and provides a dedicated integration package for Laravel.

Tokens
15.8K
Snippets
25
Records
34
Agent score
52%

What's inside NetSuite PHP

  1. Configure Account-Specific Data Center URLs

    master

    Since version 2021_1, the library supports NetSuite's account-specific data center URL detection.

    • For batch processing (fewer connections): You can use the legacy https://webservices.netsuite.com host. The service will perform a lookup to find the correct URL for your account on the fly. Note that this lookup adds measurable overhead.
    • For frequent, brief requests: It is recommended to provide your specific data center URL explicitly in the host config key to avoid the lookup overhead on every session.
    // Recommended for high-frequency requests: Use your specific data center URL
    $config['host'] = 'https://123456789.suitetalk.api.netsuite.com';
    
    // Use legacy URL to allow automatic lookup (adds overhead):
    $config['host'] = 'https://webservices.netsuite.com';
  2. Instantiate the NetSuiteService class

    master

    To use the client, instantiate NetSuite\NetSuiteService. You must use Token-Based Authentication (TBA), as user credential authentication is no longer supported.

    You can provide configuration via an associative array or by setting environment variables (the constructor will automatically extract values from $_ENV).

    require 'vendor/autoload.php';
    
    use NetSuite\NetSuiteService;
    
    $config = [
        // required -------------------------------------
        "endpoint"       => "2021_1",
        "host"           => "https://webservices.netsuite.com",
        "account"        => "MYACCT1",
        "consumerKey"    => "0123456789ABCDEF",
        "consumerSecret" => "0123456789ABCDEF",
        "token"          => "0123456789ABCDEF",
        "tokenSecret"    => "0123456789ABCDEF",
        // optional -------------------------------------
        "signatureAlgorithm" => 'sha256', // Defaults to 'sha256'
        "logging"  => true,
        "log_path" => "/var/www/myapp/logs/netsuite",
        "log_format"     => "netsuite-php-%date-%operation",
        "log_dateformat" => "Ymd.His.u",
    ];
    
    $service = new NetSuiteService($config);
  3. Generate NetSuite classes manually

    master

    The repository includes classes generated from the NetSuite PHP Toolkit. If you need to regenerate these classes yourself, follow these steps:

    1. Download the NetSuite PHP Toolkit.
    2. Unzip the toolkit contents into the ./original/ directory of this project.
    3. Execute either ./utilities/separate_classes.php or use the composer command composer generate.
  4. Configure NetSuite via environment variables

    master

    Instead of passing an array to the constructor, you can define your configuration in your environment (e.g., via a .env file). The NetSuiteService constructor will automatically detect these values. This is the recommended approach for modern hosted environments.

    require 'vendor/autoload.php';
    
    use NetSuite\NetSuiteService;
    
    // The client will infer configuration from $_ENV
    $service = new NetSuiteService();
  5. Integrate with Laravel

    master

    For Laravel applications, use the netsuitephp/netsuite-laravel package. This streamlines the instantiation process and makes the NetSuite client available within the Laravel service container. Ensure your NetSuite configuration is present in your application's environment variables.

    composer require netsuitephp/netsuite-laravel
  6. Search for records using SearchRequest

    master

    To perform a search, use a SearchRequest containing a search record object (e.g., CustomerSearchBasic). You can define search criteria using field objects like SearchStringField to specify operators (e.g., startsWith) and values. You can also control pagination using $service->setSearchPreferences(false, limit). The results are accessed via $searchResponse->searchResult->recordList.

    // Find a record whose first name starts with "Justin"
    use NetSuite\\Classes\\SearchStringField;
    use NetSuite\\Classes\\CustomerSearchBasic;
    use NetSuite\\Classes\\SearchRequest;
    
    // Limit to 20 results per page
    $service->setSearchPreferences(false, 20);
    
    $searchField = new SearchStringField();
    $searchField->operator = "startsWith";
    $searchField->searchValue = "Justin";
    
    $search = new CustomerSearchBasic();
    $search->firstName = $searchField;
    
    $request = new SearchRequest();
    $request->searchRecord = $search;
    
    $searchResponse = $service->search($request);
    
    if (!$searchResponse->searchResult->status->isSuccess) {
        echo "SEARCH ERROR";
    } else {
        $result = $searchResponse->searchResult;
        $count = $result->totalRecords;
        $records = $result->recordList;
    
        echo $count . " records were found.";
    }
  7. Retrieve a record by internalId

    master

    To fetch a specific record from NetSuite, use a GetRequest. You must provide a RecordRef containing the internalId and the type of the record (e.g., 'customer'). The response contains the record data in $getResponse->readResponse->record if the status is successful.

    // Fetch a Customer record by their internalId
    use NetSuite\
    Classes\\GetRequest;
    use NetSuite\\Classes\\RecordRef;
    
    $request = new GetRequest();
    $request->baseRef = new RecordRef();
    $request->baseRef->internalId = "123456789";
    $request->baseRef->type = "customer";
    
    $getResponse = $service->get($request);
    
    if ( ! $getResponse->readResponse->status->isSuccess) {
        echo "GET ERROR";
    } else {
        $customer = $getResponse->readResponse->record;
    }
  8. Add a SalesOrder with custom fields

    master

    When creating a SalesOrder, you can associate existing records using RecordRef (e.g., for the entity field). To add custom fields, create instances of custom field classes (like StringCustomFieldRef), set their scriptId and value, collect them into an array, and assign them to a CustomFieldList on the record.

    use NetSuite\\Classes\\AddRequest;
    use NetSuite\\Classes\\CustomFieldList;
    use NetSuite\\Classes\\RecordRef;
    use NetSuite\\Classes\\SalesOrder;
    use NetSuite\\Classes\\StringCustomField;
    
    $sale = new SalesOrder();
    
    // Associate a customer record with this order
    $sale->entity = new RecordRef();
    $sale->entity->type = 'customer';
    $sale->entity->internalId = $myCustomerInternalId;
    
    // Set the date of the order
    $sale->tranDate = $myOrderDate;
    
    // Set the shipping method and price for the order
    $sale->shipMethod = new RecordRef();
    $sale->shipMethod->internalId = $myShipMethodId;
    $sale->shippingCost = $myShippingTotal;
    
    // Create a sample string-type custom field to the order which represents
    // the ID of the order in our source platform:
    $cfOrderNum = new StringCustomFieldRef();
    $cfOrderNum->scriptId = 'custbody_order_id';
    $cfOrderNum->value = $myOrderId; // Some value from your application
    
    // Collect all custom fields into an array and add the list of fields to the
    // order add request:
    $customFields[] = $cfOrderNum;
    $sale->customFieldList = new CustomFieldList();
    $sale->customFieldList->customField = $customFields;
    
    // Submit the sales order create request
    $request = new AddRequest();
    $request->record = $sale;
    $addResponse = $service->add($request);
    
    if (!$addResponse->writeResponse->status->isSuccess) {
        echo "ADD ERROR";
    } else {
        echo "ADD SUCCESS, id " . $addResponse->writeResponse->baseRef->internalId;
    }
  9. Add a new Customer record

    master

    To create a new record, instantiate the specific record class (e.g., Customer), populate its properties, wrap it in an AddRequest, and pass it to $service->add($request). On success, the new record's ID is available in $addResponse->writeResponse->baseRef->internalId.

    // Create a new Customer record
    use NetSuite\\Classes\\Customer;
    use NetSuite\\Classes\\RecordRef;
    use NetSuite\\Classes\\AddRequest;
    
    $customer = new Customer();
    $customer->firstName = "John";
    $customer->lastName = "Doe";
    $customer->companyName = "Bobby's Bits";
    $customer->phone = "123456789";
    $customer->email = "test@example.com";
    // ... add all of your fields, then create the request
    $request = new AddRequest();
    $request->record = $customer;
    
    $addResponse = $service->add($request);
    
    if (!$addResponse->writeResponse->status->isSuccess) {
        echo "ADD ERROR";
    } else {
        echo "ADD SUCCESS, id " . $addResponse->writeResponse->baseRef->internalId;
    }
  10. Initialize and add an Item Fulfillment

    master

    To create an ItemFulfillment based on an existing record (like a SalesOrder), use an InitializeRequest. This requires an InitializeRecord object specifying the target type and an InitializeRef object pointing to the source record's internalId and type. Once the record is initialized via $service->initialize($request), you can modify it (e.g., adding packages via ItemFulfillmentPackageList) and then submit it using an AddRequest.

    use NetSuite\\Classes\\AddRequest;
    use NetSuite\\Classes\\InitializeRecord;
    use NetSuite\\Classes\\InitializeRef;
    use NetSuite\\Classes\\InitializeRequest;
    use NetSuite\\Classes\\ItemFulfillmentPackage;
    use NetSuite\\Classes\\ItemFulfillmentPackageList;
    
    // Initialize an item fulfillment from an existing Sales Order
    $reference = new InitializeRef();
    $reference->type = InitializeRefType::salesOrder;
    $reference->internalId = $mySalesOrderInternalId;
    
    $record = new InitializeRecord();
    $record->type = InitializeType::itemFulfillment;
    $record->reference = $reference;
    
    $request = new InitializeRequest();
    $request->initializeRecord = $record;
    
    $initResponse = $service->initialize($request);
    
    if (!$initResponse->readResponse->status->isSuccess) {
        echo "INIT ERROR";
    }
    
    $itemFulfillment = $initResponse->readResponse->record;
    
    // Create and add a package object to the ItemFulfillment
    $package = new ItemFulfillmentPackage();
    $package->packageWeight = 1;
    $package->packageTrackingNumber = $myTrackingNumber;
    
    $packageList = new ItemFulfillmentPackageList();
    $packageList->package = $package;
    $itemFulfillment->packageList = $packageList;
    
    $request = new AddRequest();
    $request->record = $itemFulfillment;
    
    $addResponse = $service->add($request);
    
    if (!$addResponse->writeResponse->status->isSuccess) {
        echo "ADD ERROR";
    } else {
        echo "ADD SUCCESS, id " . $addResponse->writeResponse->baseRef->internalId;
    }
  11. Configure and manage logging

    master

    Logging can be enabled via the initial configuration array or managed at runtime.

    Requirements: You must specify a valid log_path in your configuration or via setLogPath(), otherwise no logs will be created.

    Runtime Methods:

    • $service->setLogPath(string $path): Sets the directory for logs.
    • $service->logRequests(bool $enable): Enables or disables request logging.

    As of 2023.1.0, you can also provide your own PSR-3 compatible logger for advanced requirements.

    // Set a logging path
    $service->setLogPath('/path/to/logs');
    
    // Turn logging on
    $service->logRequests(true);
    
    // Turn logging off
    $service->logRequests(false);