PHP: 3dcart-scripts.php, 3dcart API实例, 3dcar API 用法,3dcart REST API

 

App

有关回调网址和重定向URI的信息可以在这里找到:
https://developer.3dcart.com/build-an-app/

如果您的应用是支付网关,那么可以找到最需要关注的区域在底部。
网关结帐URL和网关后订单网址正如它所说的那样。这些是您希望购物车在结帐和下订单时重定向的网址。凭证1和2只是一个应该在商店中出现的标题,因此商家知道他们需要输入哪些凭据才能成功连接网关。这不是必需品。

有关使用REST API开发支付网关的更多信息,请访问此处并附上:
https://github.com/3dcart/3dcartSampleGatewayApp
这里的文档是一个“骨架”应用程序,可以帮助开发人员快速启动新的集成。

注意:文档中提供了我们在开发支付网关时提供的整个支持范围。我们无法帮助您开发网关。如果你特意卡在某个地方,我们会尽力协助,但一般来说,支持将基于已经提供的信息,并排除任何可能无法记录的功能。

 

REST API

将应用程序与3dcart集成所需的文档,参考和资源。

https://apirest.3dcart.com/

 

Developer 后台

https://devportal.3dcart.com/

更多参考:

如何获得3dCart REST API,获取3dCart的token,private key

如何获得3dCart REST API, How to get 3dCart REST API

 

实例 1:

config.php

<?php
// 3dcart API:
$secureURL = 'mystore.com';
$privateKey = '0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f';
$token = '0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f';
// Address validation:
$mailto = "error@mystore.com"; // send errors here
$usps_user = "123STORE4567";
// Warehouse FTP:
$ftp_host = 'warehouse.com';
$ftp_user = 'mystore@warehouse.com';
$ftp_pass = 'a good password';
$incoming_ftp_path = 'incoming/'; // upload after bundler
$outgoing_ftp_path = 'outgoing/'; // download before tracking
// Bundler:
$IgnoreSKUs = array('DigitalItem', '3dCartBundleItem', 'TestItem'); //Lines containing these SKUs will be removed
$BundleSKUs = array(						//Lines containing these SKUs will be bundled
	'Something' => array ( 100 => 'Somethingx100', 10 => 'Somethingx10' ),
	'IComeInABoxOf20' => array ( 20 => 'IComeInABoxOf20x20' ),	
);
// Hold Orders:
$DisregardSKUs = array('3dCartBundleItem', '3dcartBundleItem2'); //duplicated by 3dcart because of "bundle items"

 

3dapi.php

<?php
//Sean Gillen / Anonymous Press
require_once('config.php');
$version = 1;
$apiBaseURL = "https://apirest.3dcart.com/3dCartWebAPI/v$version/";
$newOrderStatus = 1;
$shippedOrderStatus = 4;
$holdOrderStatus = 6;
$verbose = true;
if(!isset($num_requests)) $num_requests = 0;
$timeout = 30;
$apiheader = array(
	'Content-Type: application/json;charset=UTF-8',
	'Accept: application/json',
	'SecureUrl: ' . $secureURL,
	'PrivateKey: ' . $privateKey,
	'Token: '. $token,
);
set_time_limit(300);
if(php_sapi_name()=="cli"){
	set_time_limit(1800);
	echo "CLI interface detected. Time limit set to 30 minutes.\n";
}
else echo "Time limit set to 5 minutes.\n";
$responses = array();
function get($url,$params){
	global $apiBaseURL, $apiheader, $verbose, $num_requests;
	if($num_requests > 45) {
		if($verbose) echo "More than 45 requests. Sleeping for 500 ms.";
		usleep(500000);
	}
	$startTime = microtime(true);
	if($verbose) echo @array_shift(debug_backtrace())["line"].": GET $url\r\n";
	$ch = curl_init($apiBaseURL.$url.'?'.http_build_query($params));
	curl_setopt($ch, CURLOPT_HTTPHEADER, $apiheader);
	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
	$response = curl_exec($ch);
	$num_requests++;
	$runtime = number_format(microtime(true) - $startTime,3);
	if($verbose) outputResponse($response,$runtime);
	return $response===false?false:json_decode($response,true);
}
function getOrders($status) {
	$orders = array();
	$limit = 10;
	do {
		$ordersPage = get('Orders', array('orderstatus'=>$status, 'limit'=>$limit, 'offset'=>(count($orders) + 1)));
		$orders = array_merge($orders, $ordersPage);
	} while (count($ordersPage) == $limit);
	return $orders;
}
function put($url,$urlparams,$bodyparams,$post = false){
	global $apiBaseURL, $apiheader, $verbose, $debug, $num_requests;
	if($num_requests > 45) {
		if($verbose) echo "More than 45 requests. Sleeping for 500 ms.";
		usleep(500000);
	}
	$startTime = microtime(true);
	if($verbose) echo @array_shift(debug_backtrace())["line"].($post?': POST':': PUT')." $url\r\n";
	if($debug) {
		echo "DISABLED\r\n";
		return [false];
	}
	$data = json_encode($bodyparams);
	$ch = curl_init($apiBaseURL.$url.'?'.http_build_query($urlparams));
	curl_setopt($ch, CURLOPT_HTTPHEADER, array_merge($apiheader,array("Content-Length: ".strlen($data))));
	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
	if($post) curl_setopt($ch, CURLOPT_POST, 1);
	else curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
	curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
	$response = curl_exec($ch);
	$num_requests++;
	$runtime = number_format(microtime(true) - $startTime,3);
	if($verbose) outputResponse($response,$runtime);
	return $response===false?[false]:json_decode($response,true);
}
function outputResponse($response,$time){
	global $errors, $warnings, $responses;
	if($response === false){
		echo "FAILED in $time seconds\r\ncURL error ";
		echo curl_errno($ch).": ".curl_error($ch)."\r\n";
		$errors++;
		return true;
	}
		$responses[] = $response;
		$responseid = count($responses)-1;
	echo "Succeeded in $time seconds\r\n";
	$decodedResponse = json_decode($response,true);
	if((isset($decodedResponse[0]["Status"]) && $decodedResponse[0]["Status"][0]!=="2") || (count($decodedResponse)===1 && count($decodedResponse)[0]===1) || !$decodedResponse){
		echo "WARNING: Response was: $response\r\n";
		if(php_sapi_name()=='cli') echo "(id $responseid)\r\n";
		$warnings++;
	}
	elseif(strlen(addcslashes($response,"\r\n")) <= 240){
		echo "Response was: $response\r\n";
		if(php_sapi_name()=='cli') echo "(id $responseid)\r\n";
	}
	elseif(php_sapi_name()=='cli'){ //not $cli so this works on interactive shells only
		echo "Response was ".strlen($response)." bytes (id $responseid)\r\n";
	}
	else{
		$gzippedResponse = base64_encode(gzcompress($response,9));
		echo "Response was";
		echo strlen($gzippedResponse)<=240?" (gzipped): $gzippedResponse\r\n":" ".strlen($response)." bytes\r\n";
	}
	echo "\r\n";
	return true;
}
function human_bytes($bytes, $decimals = 2) {
	if($bytes < 1024) return $bytes." bytes";
	$sz = 'BkMGTP';
	$factor = floor((strlen($bytes) - 1) / 3);
	return @sprintf("%.{$decimals}f", $bytes / pow(1024, $factor)) . " ".@$sz[$factor]."iB";
}
function return_bytes($val) {
    $val = trim($val);
    $last = strtolower($val[strlen($val)-1]);
    switch($last) {
        // The 'G' modifier is available since PHP 5.1.0
        case 'g':
            $val *= 1024;
        case 'm':
            $val *= 1024;
        case 'k':
            $val *= 1024;
    }
    return $val;
}
function f($errorNumber, $errorMessage, $errorFile, $errorLine, $errorContext) {
	if(error_reporting()) {
		global $phpMessages;
		$phpMessages++;
		echo "PHP message: $errorFile:$errorLine: [$errorNumber] $errorMessage; context: ";
		var_dump($errorContext);
	}
	return false;
}

 

更多参考:https://github.com/anonpress/3dcart-scripts

 

实例 2:

<?php

/**
 * @filesource  :  cart3d.php
 * @Author      :  GLS
 * @version     :  Created on Dec 17, 2018 4:53:23 PM
 *
 *  $orders = $this->library('cart3d')->service('Orders')->request(array('limit'=>1,'offset'=>2))->find();
 *  $orders = $this->library('cart3d')->service('Orders')->request(array('orderstatus'=>1))->find();
 *  $orders = $this->library('cart3d')->service('Orders', 5)->find();
 *  $orders = $this->library('cart3d')->order_status(true);
 */
defined('BASEPATH') or die('Restricted access');

class Cart3d
{
    private $host         = API_HOST_3DCART;
    private $version      = API_VERSION;        // API version
    private $secure_url   = STORE_3DCART;       // Secure URL is set in Settings->General->StoreSettings
    private $private_key  = PRIVATE_KEY_3DCART; // Private key is obtained when registering your app at http://devportal.3dcart.com
    private $token        = TOKEN_3DCART;       // The token is generated when a customer authorizes your app
    private $curl_post    = false;
    private $http_header;
    private $service;                           // API service
    private $url_request;
    private $body;
    private $url;                               // Output: https://apirest.3dcart.com/3dCartWebAPI/v1/Customers
    private $order_status = array();

    function __construct($params = array())
    {
        $this->init($params);
    }

    function init($params = array())
    {
        if($params) foreach ($params as $key => $config) $this->{$key} = $config;

        if(!$this->http_header) $this->http_header = array(
                                    'Content-Type: application/json;charset=UTF-8',
                                    'Accept: application/json',
                                    'SecureUrl: ' . $this->secure_url,
                                    'PrivateKey: ' . $this->private_key,
                                    'Token: ' . $this->token,
                                );

        if(!$this->url) $this->url();

        return $this;
    }

    function secure_url($secure_url = '')
    {
        if($secure_url) $this->secure_url = $secure_url;
        return $this;
    }

    function private_key($private_key = '')
    {
        if($private_key) $this->private_key = $private_key;
        return $this;
    }

    function token($token = '')
    {
        if($token) $this->token = $token;
        return $this;
    }

    function url($url = '')
    {
        $this->url = $url ? $url : $this->host . '/3dCartWebAPI/v' . $this->version;
        return $this;
    }

    function service($service = '', $field_id = '')
    {
        if($service) $this->service = $service.($field_id?'/'.$field_id:'');
        return $this;
    }

    function request($params = array())
    {
        if($params) $this->url_request = $params;
        return $this;
    }

    function body($params = array())
    {
        if($params) $this->body = $params;
        return $this;
    }

    function curl_post($curl_post = '')
    {
        if(is_bool($curl_post)) $this->curl_post = $curl_post;
        return $this;
    }

    function order_status($filp = false)
    {
        $statuses = array();

        $order_statuses = $this->service('OrderStatus')->find();
        if($order_statuses) foreach ($order_statuses as $order_status) $statuses[$order_status['OrderStatusID']] = trim(strtolower($order_status['StatusText']));

        $statuses = $filp ? array_flip($statuses) : $statuses;
        $this->order_status = $statuses;

        return $statuses;
    }

    function find($service = '', $params = array())
    {
        $response = false;

        if(!$service) $service = $this->service;
        if(!$params)  $params  = $this->url_request;

        if($service)
        {
//            if(!isset($params['orderstatus']) OR !$params['orderstatus']) $params['orderstatus'] = 1;
            if(!isset($params['limit']) OR !$params['limit'])             $params['limit']       = 200;

            $ch = curl_init(rtrim($this->url, '/').'/'.$service.($params?'?' . http_build_query($params):''));
            curl_setopt($ch, CURLOPT_HTTPHEADER, $this->http_header);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            $response = curl_exec($ch);
        }

        $this->reset();

        return $response === false ? false : json_decode($response,true);
    }

    function put($service = '', $params = array(), $update_data = array())
    {
        return $this->update($service, $params, $update_data, false);
    }

    function post($service = '', $params = array(), $update_data = array())
    {
        return $this->update($service, $params, $update_data, true);
    }

    function update($service = '', $params = array(), $update_data = array(), $post = true)
    {
        $response = false;

        if(!$service)       $service      = $this->service;
        if(!$params)        $params       = $this->url_request;
        if(!$update_data)   $update_data  = $this->body;
        if(!is_bool($post)) $post         = $this->curl_post;

        if($service AND $update_data)
        {
            $data = json_encode($update_data);
            $ch = curl_init(rtrim($this->url, '/').'/'.$service . ($params?'?' . http_build_query($params):''));
            curl_setopt($ch, CURLOPT_HTTPHEADER, array_merge($this->http_header, array("Content-Length: " . strlen($data))));
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            if ($post) curl_setopt($ch, CURLOPT_POST, 1);
            else curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
            $response = curl_exec($ch);
        }

        $this->reset();

        return $response === false ? false : json_decode($response,true);
    }

    function orders($status = '')
    {
        $orders = array();
        $limit = 10;

        do
        {
            $ordersPage = find('Orders', array('orderstatus'=>$status, 'limit'=>$limit, 'offset'=>(count($orders) + 1)));
            $orders = array_merge($orders, $ordersPage);
        } while (count($ordersPage) == $limit);

        return $orders;
    }

    function reset()
    {
        $this->service     = '';
        $this->url_request = '';
    }
}

//end class

 

configs:

// 3dcart.net
// API: https://apirest.3dcart.com/Help
// https://devportal.3dcart.com/
define('API_HOST_3DCART',    'https://apirest.3dcart.com');
define('API_VERSION',        1);
define('SECURE_Url_3DCART',  'your-domain-com.3dcartstores.com');
define('PRIVATE_KEY_3DCART', 'yours');
define('TOKEN_3DCART',       'yours');

define('STORE_3DCART',       'your-domain-com.3dcartstores.com'); 
define('PUBLIC_KEY_3DCART',  'yours');
define('CLIENT_3DCART',      'yours');
define('SECRET_KEY_3DCART',  'yours');

 

更多参考:

如何获得3dCart REST API,获取3dCart的token,private key

如何获得3dCart REST API, How to get 3dCart REST API

 

本文: PHP: 3dcart-scripts.php, 3dcart API实例, 3dcar API 用法,3dcart REST API

Leave a Reply