Я работаю над Opencart API (opencart v2.3) и перехожу по этой ссылке для документации (OpenCart ) Но нет никаких данных об API opencart и о том, как их использовать, поэтому я следую инструкциям других сайтов и, используя этот код, получаю это сообщение при вызове login api, Успешно: сессия API успешно запущена!
Но всякий раз, когда я использую другой API для добавления товара в корзину, просмотра корзины или добавления заказа, я получаю разрешение. Я отлаживаю код и обнаружил, что это требует сеанса app_id и когда я проверяю, он хранит только знак, не app_id
Я использую следующий код, который я нашел путем поиска в Google.
common.php
<?php
function do_curl_request($url, $params=array()) {
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_COOKIEJAR, 'E:\practice\oc2.3\tmp\apicookie.txt');
curl_setopt($ch, CURLOPT_COOKIEFILE, 'E:\practice\oc2.3\tmp\apicookie.txt');
$params_string = '';
if (is_array($params) && count($params)) {
foreach($params as $key=>$value) {
$params_string .= $key.'='.$value.'&';
}
rtrim($params_string, '&');
curl_setopt($ch,CURLOPT_POST, count($params));
curl_setopt($ch,CURLOPT_POSTFIELDS, $params_string);
}
//execute post
$result = curl_exec($ch);
//close connection
curl_close($ch);
return $result;
}
login.php
<?php
require "common.php";
// set up params
$url = 'http://opencart2_3.local/index.php?route=api/restopencart/login';
$fields = array(
'key' => 'FpafURRNAHgVcaUXZozahVdEOV7mtp1Q0ejvAMAIAfiZyVqIptqZ2uV9eQvT3PytlzELULH1vQwLKikFGBOm3yky1rTuFO6sEi0eBkH1y6WgpaNWIsB0ZMiRCCbGCBZZak2uR1CBg0TpOzcbevXWGStvoUsaKgl0B3OKRoHk6mRj7e6S63HJQzQksbbz0JfCuZsY9cvhY4ArQPzNf3XfrdgE3nTG5hYQCXaKPVqtS3R2Vqr4sazwjgXYajy7h6Dv',
);
$json = do_curl_request($url, $fields);
$data = json_decode($json);
if (isset($data->token)) {
$token = $data->token;
}
var_dump($data);
add_product.php
<?php
require "common.php";
// set up params
$url = 'http://opencart2_3.local/index.php?route=api/restopencart/addproduct';
$fields = array(
'product_id' => '32',
'quantity' => '1',
'option[226]' => '15'
);
$json = do_curl_request($url, $fields);
$data = json_decode($json);
var_dump($data);
клиент API
public function index() {
$this->load->language('api/customer');
// Delete past customer in case there is an error
unset($this->session->data['customer']);
$json = array();
if (!isset($this->session->data['api_id'])) {
$json['error']['warning'] = $this->language->get('error_permission');
} else {
// Add keys for missing post vars
$keys = array(
'customer_id',
'customer_group_id',
'firstname',
'lastname',
'email',
'telephone',
'fax'
);
foreach ($keys as $key) {
if (!isset($this->request->post[$key])) {
$this->request->post[$key] = '';
}
}
// Customer
if ($this->request->post['customer_id']) {
$this->load->model('account/customer');
$customer_info = $this->model_account_customer->getCustomer($this->request->post['customer_id']);
if (!$customer_info || !$this->customer->login($customer_info['email'], '', true)) {
$json['error']['warning'] = $this->language->get('error_customer');
}
}
if ((utf8_strlen(trim($this->request->post['firstname'])) < 1) || (utf8_strlen(trim($this->request->post['firstname'])) > 32)) {
$json['error']['firstname'] = $this->language->get('error_firstname');
}
if ((utf8_strlen(trim($this->request->post['lastname'])) < 1) || (utf8_strlen(trim($this->request->post['lastname'])) > 32)) {
$json['error']['lastname'] = $this->language->get('error_lastname');
}
if ((utf8_strlen($this->request->post['email']) > 96) || (!filter_var($this->request->post['email'], FILTER_VALIDATE_EMAIL))) {
$json['error']['email'] = $this->language->get('error_email');
}
if ((utf8_strlen($this->request->post['telephone']) < 3) || (utf8_strlen($this->request->post['telephone']) > 32)) {
$json['error']['telephone'] = $this->language->get('error_telephone');
}
// Customer Group
if (is_array($this->config->get('config_customer_group_display')) && in_array($this->request->post['customer_group_id'], $this->config->get('config_customer_group_display'))) {
$customer_group_id = $this->request->post['customer_group_id'];
} else {
$customer_group_id = $this->config->get('config_customer_group_id');
}
// Custom field validation
$this->load->model('account/custom_field');
$custom_fields = $this->model_account_custom_field->getCustomFields($customer_group_id);
foreach ($custom_fields as $custom_field) {
if (($custom_field['location'] == 'account') && $custom_field['required'] && empty($this->request->post['custom_field'][$custom_field['custom_field_id']])) {
$json['error']['custom_field' . $custom_field['custom_field_id']] = sprintf($this->language->get('error_custom_field'), $custom_field['name']);
} elseif (($custom_field['location'] == 'account') && ($custom_field['type'] == 'text') && !empty($custom_field['validation']) && !filter_var($this->request->post['custom_field'][$custom_field['custom_field_id']], FILTER_VALIDATE_REGEXP, array('options' => array('regexp' => $custom_field['validation'])))) {
$json['error']['custom_field' . $custom_field['custom_field_id']] = sprintf($this->language->get('error_custom_field'), $custom_field['name']);
}
}
if (!$json) {
$this->session->data['customer'] = array(
'customer_id' => $this->request->post['customer_id'],
'customer_group_id' => $customer_group_id,
'firstname' => $this->request->post['firstname'],
'lastname' => $this->request->post['lastname'],
'email' => $this->request->post['email'],
'telephone' => $this->request->post['telephone'],
'fax' => $this->request->post['fax'],
'custom_field' => isset($this->request->post['custom_field']) ? $this->request->post['custom_field'] : array()
);
$json['success'] = $this->language->get('text_success');
}
}
if (isset($this->request->server['HTTP_ORIGIN'])) {
$this->response->addHeader('Access-Control-Allow-Origin: ' . $this->request->server['HTTP_ORIGIN']);
$this->response->addHeader('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS');
$this->response->addHeader('Access-Control-Max-Age: 1000');
$this->response->addHeader('Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With');
}
$this->response->addHeader('Content-Type: application/json');
$this->response->setOutput(json_encode($json));
}
Поместите токен сразу после того, как URL вашего запроса заработает.
Предположим, что токен возвращен api/login
является KYMmXA4Bcj8nL9WD3nl0oalaJOL1KSKo
,
add_product.php
<?php
require "common.php";
// set up params
$url = 'http://opencart2_3.local/index.php?route=api/restopencart/addproduct&token=KYMmXA4Bcj8nL9WD3nl0oalaJOL1KSKo';
$fields = array(
'product_id' => '32',
'quantity' => '1',
'option[226]' => '15'
);
$json = do_curl_request($url, $fields);
$data = json_decode($json);
var_dump($data);
Других решений пока нет …