Your IP : 216.73.216.189


Current Path : /var/www/magento.test.indacotrentino.com/www/scripts/import/OLD/
Upload File :
Current File : /var/www/magento.test.indacotrentino.com/www/scripts/import/OLD/RestShipment.php

<?php
/*
* OAuth 1.0a client (Example) for Magento 2
*
* @see: https://oauth.net/core/1.0a
* @see: https://tools.ietf.org/html/rfc5849
*/
class Api
{
    const CONNECT_TO_MAGENTO = 'INDACO2-38121'; // INDACO-TEST INDACO-38121 INDACO2-38121

    const OAUTH_VERSION = '1.0';

    const OAUTH_SIGNATURE = 'HMAC-SHA256';

    private $consumerKey;

    private $consumerSecret;

    private $accessToken;

    private $accessTokenSecret;

    private $host;

    private $token;

    public function __construct()
    {
        switch(self::CONNECT_TO_MAGENTO) {
            case 'INDACO-TEST':
                $this->host                 = 'https://magento.test.indaco.store';
                $this->consumerKey 		    = '610dee75s27oe0jlx7dx8cyr5k275861';
                $this->consumerSecret 		= 'aw0nis1v3kst9gxlozdewmf8pnotscxf';
                $this->accessToken 		    = '0kufmoncdszyzs13bkvyrkjxlgu593bj';
                $this->accessTokenSecret 	= 'jvdbnuw6w4cfbv4o18cg44p400ap4ad6';
                break;
            case 'INDACO-38121':
                $this->host                 = 'http://indaco.38121.it/';
                $this->consumerKey 		    = 'yh9nspb82lqo1h2buqi6l90hqltzwchb';
                $this->consumerSecret 		= 'i1j57ms6b418b5z4d8q6uq3unyc4s0nn';
                $this->accessToken 		    = 't0nj8c2n71y6gmsb8t5mzwc9i70ly2y5';
                $this->accessTokenSecret 	= 'u66odr3bnc5gr93bxv9rjg7ptx35psuc';
                break;
            case 'INDACO2-38121':
                $this->host                 = 'http://indaco2.38121.it/';
                $this->consumerKey 		    = '6fxozvw17jwgfeyqt48yjih4di3ssn0q';
                $this->consumerSecret 		= 'xpcpn35eyi137089gfoliknjfl27qyp3';
                $this->accessToken 		    = '1s535lnh4zp9ujjhna5v2vewofuo10p6';
                $this->accessTokenSecret 	= 'm5ab6997ciuhe9dfk6shls5ygr7dveqe';
        }
    }

    /*
    * Generate a unique nonce
    *
    * @return string unique string
    */
    private function getNonce(): string
    {
        return bin2hex(random_bytes(32));
    }

    /*
    * Create a oauth_signature
    *
    * @param string $verb HTTP Method/Verb
    * @param string $endpoint Complete url including scheme, host, path, params
    * @param array $params Parameters prefixed with oauth_
    * @return string oauth_signature value
    */
    private function sign(string $verb, string $endpoint, array $params): string
    {
        ksort($params);// @see Zend_Oauth_Signature_SignatureAbstract::_toByteValueOrderedQueryString() for more accurate sorting, including array params

        // define params that will be used either in Authorization header, or as url query params, excluding 'oauth_signature'
        $strParams = http_build_query($params, '', '&', PHP_QUERY_RFC3986);
var_dump($strParams);
        $baseString = sprintf('%s&%s&%s',
            strtoupper($verb),// HTTP method (POST/GET/PUT/...)
            rawurlencode($endpoint),// base resource url - without port & query params & anchors, @see how Zend extracts it in Zend_Oauth_Signature_SignatureAbstract::normaliseBaseSignatureUrl()
            rawurlencode($strParams)
        );
  //      var_dump($baseString);
        $key = rawurlencode($this->consumerSecret).'&'.rawurlencode($this->accessTokenSecret);
        return base64_encode(hash_hmac('SHA256', $baseString, $key, true));
    }

    /*
    * Generate Oauth token including signature
    *
    * @param string $verb HTTP Method/Verb
    * @param string $endpoint Complete url including scheme, host, path, params
    * @param array  $criteria Search Criteria
    */
    private function generateToken(string $verb, string $endpoint, array $criteria): string
    {
        $params = array_merge([
            'oauth_consumer_key'        => $this->consumerKey,
            'oauth_token'               => $this->accessToken,
            'oauth_timestamp'           => time(),
            'oauth_nonce'               => $this->getNonce(),
            'oauth_version'             => self::OAUTH_VERSION,
            'oauth_signature_method'    => self::OAUTH_SIGNATURE
        ],$criteria);

        $params['oauth_signature'] = $this->sign($verb, $endpoint, $params);

        return implode(',', array_map(
            function ($v, $k) { return sprintf('%s="%s"', $k, $v); }, // php ^7.4 fn($v, $k) => sprintf("%s='%s'", $k, $v) SICK!!!
            $params,
            array_keys($params)
        ));
    }

    /*
    * Send HTTP Request to Magento 2 REST API
    *
    * @param string $verb HTTP Method/Verb
    * @param string $endpoint Complete url including scheme, host, path, params
    * @param array $criteria Search criteria
    * @param string $token Token oauth_token
    * @return null|string Json response
    */
    private function client(string $verb, string $endpoint, array $criteria=null, string $token): ?string
    {
        $ch = curl_init();
/*
        curl_setopt_array($ch, [
            CURLOPT_URL => $endpoint.($criteria ? '?'.http_build_query($criteria) : ''),
            CURLOPT_CUSTOMREQUEST => $verb,
            CURLOPT_HTTPHEADER => [
                'Authorization: OAuth ' . $token,
                'Content-Type: application/json'
            ],
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_SSL_VERIFYPEER => false, // WARNING: Don't use this in production!
            CURLOPT_SSL_VERIFYHOST => false, // WARNING: Don't use this in production!
            CURLOPT_VERBOSE => false // Set true for Debugging
        ]);
*/

        curl_setopt_array($ch, [
            CURLOPT_URL => $endpoint.($criteria ? '?'.http_build_query($criteria) : ''),
            CURLOPT_CUSTOMREQUEST => $verb,
            CURLOPT_HTTPHEADER => [
                'Authorization: OAuth ' . $token,
                'Content-Type: application/json'
            ],
            CURLOPT_POST => 1,
            CURLOPT_POSTFIELDS => '{"entity":{"orderId":78,"items":[{"orderItemId":166,"qty":1}]}}',
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_SSL_VERIFYPEER => false, // WARNING: Don't use this in production!
            CURLOPT_SSL_VERIFYHOST => false, // WARNING: Don't use this in production!
            CURLOPT_VERBOSE => false // Set true for Debugging
        ]);




//        var_dump($endpoint.($criteria ? '?'.http_build_query($criteria) : ''));
        //  CURLOPT_POST => 1,
        //  CURLOPT_POSTFIELDS => $criteria,
        //curl_setopt($ch, CURLOPT_POST, 1);
        //curl_setopt($ch, CURLOPT_POSTFIELDS,
        //            "postvar1=value1&postvar2=value2&postvar3=value3");

        $err = curl_error($ch);
        $response = curl_exec($ch);
        curl_close($ch);

        echo var_dump($response);
        return $response;
    }


    /*
    * Send API Request
    *
    * @param string $verb HTTP Method/Verb
    * @param string $rest Rest path and params
    * @param array $criteria Search criteria
    * @return null|object|array response
    */
    public function request(string $verb, string $rest, array $criteria)
    {
        $endpoint = $this->host . $rest;
        $token = $this->generateToken($verb, $endpoint, $criteria);

        try {
            $response =  $this->client($verb, $endpoint, $criteria, $token);

            if (!$response) {
                die("\n\nERROR: Failed to get reponse!\n\n");
            }

        } catch(\Exception $e) {
            error_log($e->getMessage());
        }
        return json_decode($response);
    }

    public function getModules() {
        return $this->request('GET', '/rest/V1/modules');
    }

    public function getAttributeSets() {
        $criteria = [
            'searchCriteria' => 0
        ];
        return $this->request('GET', '/rest/V1/products/attribute-sets/sets/list/', $criteria);
    }

    public function getAttributeSetById($id) {
        $criteria = [
            'searchCriteria[filter_groups][0][filters][0][field]' => 'attribute_set_id',
            'searchCriteria[filter_groups][0][filters][0][value]' => $id,
            'searchCriteria[filter_groups][0][filters][0][condition_type]' => 'eq'
        ];
        return $this->request('GET', '/rest/V1/products/attribute-sets/sets/list/', $criteria);
    }

    public function getAttributeSetGroupsById($id) {
        $criteria = [
            'searchCriteria[filter_groups][0][filters][0][field]' => 'attribute_set_id',
            'searchCriteria[filter_groups][0][filters][0][value]' => $id,
            'searchCriteria[filter_groups][0][filters][0][condition_type]' => 'eq'
        ];
        return $this->request('GET', '/rest/default/V1/products/attribute-sets/groups/list/', $criteria);
    }

    public function getProducts($pageSize, $page) {
        $criteria = [
            'searchCriteria[page_size]' => $pageSize,
            'searchCriteria[current_page]' => $page
        ];
        return $this->request('GET', '/rest/default/V1/products', $criteria);
    }

    public function getSimpleProductBySku($sku) {
        $criteria = [
            'fields' => 'sku,price,name'
        ];
        return $this->request('GET', '/rest/default/V1/products/'.$sku, $criteria);
    }

    public function getOrder($id) {
        // OR $api->request('GET', '/rest/V1/orders/1');
        $criteria = [
            'searchCriteria[filter_groups][0][filters][0][field]' => 'entity_id',
            'searchCriteria[filter_groups][0][filters][0][value]' => $id,
            'searchCriteria[filter_groups][0][filters][0][condition_type]' => 'eq'
        ];
        return $this->request('GET', '/rest/V1/orders', $criteria);
    }

    public function getTEST() {
        $criteria = [
            'searchCriteria[filterGroups][0][filters][0][field]' => 'attribute_set_name',
            'searchCriteria[filterGroups][0][filters][0][value]' => 'vino',
            'searchCriteria[filterGroups][0][filters][0][conditionType]' => 'eq'
        ];

        return $this->request('GET', '/rest/V1/products/attribute-sets/sets/list', $criteria);
    }

    public function sendData($rest, $attribute) {
        return $this->request('POST', $rest, $attribute);
    }

}

$api = new Api();

$result = $api->sendData('//rest/V1/shipment', []);

/*
$api = new Api();

//$result = $api->getModules();
//$result = $api->getAttributeSets();
//$result = $api->getAttributeSetById(9);
//$result = $api->getAttributeSetGroupsById(9);
//$result = $api->getProducts(10,1);
//$result = $api->getSimpleProductBySku('vinotest');
//$result = $api->getOrder(1);

$result = $api->getTEST();

print_r($result).PHP_EOL;
exit(1);
*/