繁体   English   中英

PHP 中的 Shopify API 使用 GuzzleHttp 对象数组

[英]Shopify API in PHP using GuzzleHttp array of objects

我目前正在尝试通过 Shopify API 更新一堆产品,但是,当我发送请求时,该产品已创建,但是,它似乎忽略了它是数组或 ZA3CBC3F9D0CE1F2C155CZD1B6 的内容(例如,变体)。

这是我用于所有请求的 Shopify 助手 class。

class Shopify {

    protected $api_key;
    protected $password;
    protected $url;
    protected $host;
    protected $secret;
    protected $client;

    public function __construct() {
        $this->api_key = env('SHOPIFY_API_KEY');
        $this->password = env('SHOPIFY_API_PASSWORD');
        $this->secret = env('SHOPIFY_API_SHARED_SECRET');
        $this->host = env('SHOPIFY_API_HOST');

        $this->url = "https://{$this->api_key}:{$this->password}@{$this->host}";
        $this->client = new Client();
    }

    public function __call($method, $args)
    {
        $method = strtoupper($method);
        $allowedMethods = ['POST','GET','PUT','DELETE'];

        if(!in_array($method,$allowedMethods)){
            throw new InvalidMethodRequestException();
        }
        return $this->request($method,trim($args[0]),$args[1] ?? []);
    }

    protected function request(string $method, string $uri, array $payload)
    {
        $response = $this->client->request(
            $method,
            "{$this->url}{$uri}",
            [
                'form_params' => $payload
            ]
        );

        return json_decode($response->getBody());
    }

}

这是我使用此客户端创建具有变体的产品的示例:

$shopify = new Shopify();

$result = $shopify->post('/admin/api/2020-10/products.json', [
    'product' => [
        'title' => $product->title,
        'body_html' => $product->body_text,
        "variants" => [
            [ "sku" => $product->sku, "price" => 20.00 ]
        ]
    ]
]);

正如我上面提到的,该产品是在 Shopify 中创建的,但缺少数据为 arrays 数组的任何内容。 这可能与 GuzzleHttp 编码数据的方式有关吗? 如何以 Shopify 需要的格式获取这些数据?

你的代码看起来不错。 变体 output 可能需要转换为 json 格式。

正如您在此处看到的,预期的发布请求:

 "variants": [
  {
    "option1": "First",
    "price": "10.00",
    "sku": "123"
  },

我会尝试在请求之前转储 post 变量,看看有什么问题。

我过去使用 Facades 用 laravel 制作了一些成功的代码,并且工作正常。 但是我花了一些时间来满足 shopify 的需要。

PS:我在这里使用令牌https://www.shopify.com/partners/blog/17056443-how-to-generate-a-shopify-api-token

看:

//my endpoint, in your case '/admin/api/2020-10/products.json
$endpoint = config('endpoint');
//registered as a token.

$token = config('token');

$postFields = 'product' => [
    'title' => $product->title,
    'body_html' => $product->body_text,
    "variants" => [
        [ "sku" => $product->sku, "price" => 20.00 ]
    ]
];
//in case of any problems, you can uncomment this line and inspect your request.
//json_encode will help with this
//dd(json_encode($postFields));
return Http::withHeaders([
  "content-type" => "application/json",
  "Authorization" => "Bearer " . $token
])->post($endpoint, $postFields)->json();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM