Rest API-将包含产品的JSON文件导入Drupal 8,并使用该数据创建产品节点

时间:2018-09-21 09:30:06

标签: php json api drupal drupal-8

对于一个网站,我必须将带有Rest API的产品导入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 :(得分:0)

这就是我要这样做的方法,希望它对您有用。

对于商店创建:

<?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,我不得不修改变量/值。