1

Here is my controller class

<?php
namespace Jlsmith\Netsuit\Controller\Api;
use Jlsmith\Netsuit\Model\NetSuite\NetSuiteService;
use Jlsmith\Netsuit\Model\NetSuite\Classes\GetRequest;
use Jlsmith\Netsuit\Model\NetSuite\Classes\RecordRef;

class Fetchcustomer extends \Magento\Framework\App\Action\Action
{
    public $_service;
    public $_nsrequest;
    public $_recordref;

    public function __construct(
        \Magento\Framework\App\Action\Context $context,
        NetSuiteService $_service,
        GetRequest $request,
        RecordRef $recordref)
    {
        $this->_service = $_service;
        $this->_nsrequest = $request;
        $this->_recordref = $recordref;
        parent::__construct($context);
    }

    public function execute()
    {
        $this->_nsrequest->baseRef = $this->_recordref;
        $this->_nsrequest->baseRef->internalId = "500";
        $this->_nsrequest->baseRef->type = "customer";
        $getResponse = $this->_service->get($this->_nsrequest);

        if (!$getResponse->readResponse->status->isSuccess) {
            echo "GET ERROR";
        } else {
            $customer = $getResponse->readResponse->record;
            echo "GET SUCCESS, customer:";
            echo "\nCompany name: ". $customer->companyName;
            echo "\nInternal Id: ". $customer->internalId;
            echo "\nEmail: ". $customer->email;
        }
        die("DAED");
    }
}

NetSuiteService class extends NetSuiteClient

Here is the NetSuiteClient code

<?php
namespace Jlsmith\Netsuit\Model\NetSuite;
use Jlsmith\Netsuit\Model\NetSuite\Classes\ApplicationInfo;
use Jlsmith\Netsuit\Model\NetSuite\Classes\Passport;
use Jlsmith\Netsuit\Model\NetSuite\Classes\Preferences;
use Jlsmith\Netsuit\Model\NetSuite\Classes\RecordRef;
use Jlsmith\Netsuit\Model\NetSuite\Classes\SearchPreferences;
use Jlsmith\Netsuit\Model\NetSuite\Classes\TokenPassport;
use Jlsmith\Netsuit\Model\NetSuite\Classes\TokenPassportSignature;
use Magento\Framework\Webapi\Soap\ClientFactory as ServerClient;
use SoapHeader;

class NetSuiteClient
{
    /**
     * @var array
     */
    protected $config;

    protected $client;
    /**
     * @var SoapHeader
     */
    protected $soapHeaders = array();

    public $_helper;
    /** 
     * @param array $config
     * @param array $options
     * @param Client $client
     */
    public function __construct(
        \Magento\Framework\Model\Context $contex,
        \Jlsmith\Netsuit\Helper\Data $helper)
    {
           $options = array();
            $this->config = $config;
        $this->_helper = $helper;
        $options['cache_wsdl'] = WSDL_CACHE_NONE;
        $options['keep_alive'] = true;
        $options['exceptions'] = true;
        $options = $this->createOptions($this->config, $options);
        $wsdl = $this->createWsdl($this->config);
        $this->client = new ServerClient();
        $this->client->create($wsdl, $options);
    }

    public static function createFromEnv($options = array(), \Magento\Framework\Webapi\Soap\ClientFactory $client = null)
    {
        $config = array(
            'endpoint' => getenv('NETSUITE_ENDPOINT') ?: '2017_1',
            'host' => getenv('NETSUITE_HOST') ?: 'https://webservices.netsuite.com',
            'email' => getenv('NETSUITE_EMAIL'),
            'password' => getenv('NETSUITE_PASSWORD'),
            'role' => getenv('NETSUITE_ROLE') ?: '3',
            'account' => getenv('NETSUITE_ACCOUNT'),
            'app_id' => getenv('NETSUITE_APP_ID') ?: 'XXXXX-XXXXXX-XXXX',
            'logging' => getenv('NETSUITE_LOGGING'),
            'log_path' => getenv('NETSUITE_LOG_PATH'),
        );
        echo "<pre>"; print_r($config);echo "</pre>";die(" DEAD");
        return new static($config, $options, $client);
    }

    /**
     * Make the SOAP call!
     *
     * @param string $operation
     * @param mixed $parameter
     * @return mixed
     */
    protected function makeSoapCall($operation, $parameter)
    {
        //$this->fixWtfCookieBug();
        if (isset($this->config['token'])) {
            $this->addHeader('tokenPassport', $this->createTokenPassportFromConfig($this->config));
        } else {
            $this->setApplicationInfo($this->config['app_id']);
            $this->addHeader("passport", $this->createPassportFromConfig($this->config));
        }

        try {
            $response = $this->client->create($operation, array($parameter), null, $this->soapHeaders);
            $this->logSoapCall($operation);
            return $response;
        } catch (\Exception $e) {
            print_r($e->getMessage());die;
            $this->logSoapCall($operation);
            throw $e;
        }
    }

    /**
     * Create the options array.
     *
     * @param array $config
     * @param array $overrides
     * @return array
     */
    protected function createOptions($config, $overrides = array())
    {
        return array_merge(array(
            'classmap' => $this->_helper->classmap(),
            'trace' => 1,
            'connection_timeout' => 50,
            'cache_wsdl' => WSDL_CACHE_BOTH,
            'location' => $config['host']."/services/NetSuitePort_".$config['endpoint'],
            'keep_alive' => false,
            'features' => SOAP_SINGLE_ELEMENT_ARRAYS,
            'user_agent' => "PHPSoapClient"
            //'user_agent' => "PHP-SOAP/".phpversion()." + ryanwinchester/netsuite-php",
        ), $overrides);
    }

    /**
     * Build the WSDL address from the config.
     *
     * @param array $config
     * @return string
     */
    protected function createWsdl($config)
    {
        return $config['host'].'/wsdl/v'.$config['endpoint'].'_0/netsuite.wsdl';
    }

    /**
     * Create the Passport.
     *
     * @param array $config
     * @return Passport
     */
    protected function createPassportFromConfig($config)
    {
        $passport = new \Jlsmith\Netsuit\Model\NetSuite\Classes\Passport();
        $passport->account = $config['account'];
        $passport->email = $config['email'];
        $passport->password = $config['password'];
        $passport->role = new RecordRef();
        $passport->role->internalId = $config['role'];

        return $passport;
    }

    /**
     * Create the TokenPassport.
     *
     * @param array $config
     * @return TokenPassport
     */
    protected function createTokenPassportFromConfig($config)
    {
        $tokenPassport = new TokenPassport();
        $tokenPassport->account = $config['account'];
        $tokenPassport->consumerKey = $config['consumerKey'];
        $tokenPassport->token = $config['token'];
        $tokenPassport->nonce = $this->generateTokenPassportNonce();
        $tokenPassport->timestamp = time();

        $signatureAlgorithm = isset($config['signatureAlgorithm']) ? $config['signatureAlgorithm'] : 'sha256';

        $tokenSignature = new TokenPassportSignature();
        $tokenSignature->_ = $this->computeTokenPassportSignature(
            $config['account'],
            $config['consumerKey'],
            $config['consumerSecret'],
            $config['token'],
            $config['tokenSecret'],
            $tokenPassport->nonce,
            $tokenPassport->timestamp,
            $signatureAlgorithm
        );
        $tokenSignature->algorithm = 'HMAC_' . strtoupper($signatureAlgorithm);
        $tokenPassport->signature = $tokenSignature;

        return $tokenPassport;
    }

    /**
     * Add a header by name.
     *
     * @param string $header
     * @param mixed $value
     */
    public function addHeader($header, $value)
    {
        $this->soapHeaders[$header] = new SoapHeader("ns", $header, $value);
    }

    /**
     * Remove a header by name.
     *
     * @param string $header
     */
    public function clearHeader($header)
    {
        unset($this->soapHeaders[$header]);
    }

    /**
     * Set the application id.
     *
     * @param string $appId
     */
    public function setApplicationInfo($appId = null)
    {
        $applicationInfo = new ApplicationInfo();
        $applicationInfo->applicationId = $appId;
        $this->addHeader("applicationInfo", $applicationInfo);
    }

    /**
     * Set preferences header.
     *
     * @param bool $warningAsError
     * @param bool $disableMandatoryCustomFieldValidation
     * @param bool $disableSystemNotesForCustomFields
     * @param bool $ignoreReadOnlyFields
     */
    public function setPreferences(
        $warningAsError = false,
        $disableMandatoryCustomFieldValidation = false,
        $disableSystemNotesForCustomFields = false,
        $ignoreReadOnlyFields = false
    ) {
        $preferences = new Preferences();
        $preferences->warningAsError = $warningAsError;
        $preferences->disableMandatoryCustomFieldValidation = $disableMandatoryCustomFieldValidation;
        $preferences->disableSystemNotesForCustomFields = $disableSystemNotesForCustomFields;
        $preferences->ignoreReadOnlyFields = $ignoreReadOnlyFields;
        $this->addHeader("preferences", $preferences);
    }

    /**
     * Clear preferences header.
     */
    public function clearPreferences()
    {
        $this->clearHeader("preferences");
    }

    /**
     * Set the search preferences header.
     *
     * @param bool $bodyFieldsOnly
     * @param int $pageSize
     * @param bool $returnSearchColumns
     */
    public function setSearchPreferences($bodyFieldsOnly = true, $pageSize = 50, $returnSearchColumns = true)
    {
        $preferences = new SearchPreferences();
        $preferences->bodyFieldsOnly = $bodyFieldsOnly;
        $preferences->pageSize = $pageSize;
        $preferences->returnSearchColumns = $returnSearchColumns;

        $this->addHeader("searchPreferences", $preferences);
    }

    /**
     * Clear the search preferences.
     */
    public function clearSearchPreferences()
    {
        $this->clearHeader("searchPreferences");
    }

    /**
     * SoapClient apparently always sends the JSESSIONID cookie.
     * So we'll just un-set it to prevent this.
     */
    protected function fixWtfCookieBug()
    {
        $this->client->setCookie("JSESSIONID");
    }

    /**
     * Turn request logging on or off.
     *
     * @param bool $on
     */
    public function logRequests($on = true)
    {
        $this->config['logging'] = $on;
    }

    /**
     * Set the logging path.
     *
     * @param string $logPath
     */
    public function setLogPath($logPath)
    {
        $this->config['log_path'] = $logPath;
    }

    /**
     * Log the last SOAP call.
     *
     * @param string $operation
     */
    protected function logSoapCall($operation)
    {
        if (isset($this->config['logging']) && $this->config['logging']) {
            $logger = new Logger(
                isset($this->config['log_path']) ? $this->config['log_path'] : null
            );
            $logger->logSoapCall($this->client, $operation);
        }
    }

    /**
     * Compute TokenPassport signature
     *
     * @param int|string $account
     * @param string $consumerKey
     * @param string $consumerKey
     * @param string $token
     * @param string $tokenSecret
     * @param string $nonce
     * @param int|string $timestamp
     * @param string $signatureAlgorithm
     * @return string
     */
    protected function computeTokenPassportSignature($account, $consumerKey, $consumerSecret, $token, $tokenSecret, $nonce, $timestamp, $signatureAlgorithm)
    {
        $baseString = implode('&', array($account, $consumerKey, $token, $nonce, $timestamp));
        $key = $consumerSecret . '&' . $tokenSecret;
        return base64_encode(hash_hmac($signatureAlgorithm, $baseString, $key, true));
    }

    /**
     * Generate random (or sufficiently enough so) string of characters
     */
    protected function generateTokenPassportNonce($length = 32)
    {
        $noncePool = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
        $key = '';
        for ($i = 0; $i < $length; $i++) {
            $key .= $noncePool[mt_rand(0, 61)];
        }
        return $key;
    }
}

Here is the error I'm facing

org.xml.sax.SAXException: {urn:core_2017_1.platform.webservices.netsuite.com}BaseRef is an abstract type and cannot be instantiated.
  • I've got the solution – Bhavin Shah Jan 8 '18 at 7:27
  • Can you please add your solution here?Because I am also facing the same issue. – Sneha Panchal Jan 8 '18 at 7:29
  • @BhavinShah Please post your solution for the community – William W Feb 19 '18 at 20:44
  • Hi sneha and william thank you. for sure I will post here. – Bhavin Shah Apr 23 '18 at 7:20
  • Hi @BhavinShah can you please help me with the solution. I am facing the same issue but while getting the item list. – Kalyan Chakravarthi V Jul 9 at 12:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.