Rest API - импортируйте файл JSON с продуктами в Drupal 8 и создавайте узлы продуктов с этими данными - PullRequest
0 голосов
/ 21 сентября 2018

Для веб-сайта я должен импортировать продукты с API Rest в интернет-магазин Drupal 8.Вот документация API: https://www.floraathome.nl/api-documentatie/v1/

Я успешно получил данные по всем продуктам, используя:

https://api.floraathome.nl/v1/products/get?apitoken=[MY_TOKE]&type=json

Мне также удалось распечатать некоторые данные из него в файле PHP:

<?php 

$url = 'https://api.floraathome.nl/v1/products/get?apitoken=[MY_TOKE]&type=json';
$json = file_get_contents($url);
$retVal = json_decode($json, TRUE);

foreach($retVal['data'] as $retV){
    echo $retV['dutchname']."<br>";
    echo $retV['purchaseprice']."<br>";
    echo $retV['promotionaltext']."<br><br>";
}

У меня нет опыта работы с API или чем-то подобным.Но теперь я хотел бы иметь возможность импортировать данные из API в Drupal 8, как продукты.

Каково было бы мое лучшее решение для этого?

Заранее спасибо,

Майк

1 Ответ

0 голосов
/ 08 марта 2019

Это то, как я бы это сделал, я надеюсь, что это сработает для вас.

Для создания магазина:

<?php
// The store type. Default is 'online'.
$type = 'online';

// The user id the store belongs to.
$uid = 1;

// The store's name.
$name = 'My Store';

// Store's email address.
$mail = 'admin@example.com';

// The country code.
$country = 'US';

// The store's address.
$address = [
  'country_code' => $country,
  'address_line1' => '123 Street Drive',
  'locality' => 'Beverly Hills',
  'administrative_area' => 'CA',
  'postal_code' => '90210',
];

// The currency code.
$currency = 'USD';

// If needed, this will import the currency.
$currency_importer = \Drupal::service('commerce_price.currency_importer');
$currency_importer->import($currency);

$store = \Drupal\commerce_store\Entity\Store::create([
  'type' => $type,
  'uid' => $uid,
  'name' => $name,
  'mail' => $mail,
  'address' => $address,
  'default_currency' => $currency,
  'billing_countries' => [
    $country,
  ],
]);

// If needed, this sets the store as the default store.
$store_storage = \Drupal::service('entity_type.manager')->getStorage('commerce_store');
$store_storage->markAsDefault($store);

// Finally, save the store.
$store->save();

Для вариации (обозначено $variation сделать что-то вроде

<?php
$price = new \Drupal\commerce_price\Price('24.99', 'USD');

$variation = ProductVariation::create([
  'type' => 'default', // The default variation type is 'default'.
  'sku' => 'test-product-01', // The variation sku.
  'status' => 1, // The product status. 0 for disabled, 1 for enabled.
  'price' => $price,
]);
$variation->save();

Наконец, для продукта:

<?php
use \Drupal\commerce_product\Entity\Product;
use \Drupal\commerce_product\Entity\ProductVariation;

$req=\Drupal::httpClient()->get("https://api.floraathome.nl/v1/products/get?apitoken=[MY_TOKE]&type=json");
$res=json_decode($req);
foreach($res['data'] as $r) {
  $product = Product::create(['type' => 'default', 'variations' => $variation, 'stores' => $sid]);
  $product->set('title', $r['dutchname'];
  ...
  ...
  ...

$ product-> save ();}

Надеюсь, вы поняли идею.

Примечание: Излишне говорить, что мне пришлось составлять переменные / значения, поскольку у меня нет доступа к API.

...