如何使用 PHP 在 Shopify Rest API 中创建分页

0 php api rest shopify postman

我在 php 中创建了curl 来使用shopify 产品休息API。现在我想在其中创建分页。

如何创作?

Link: "<https://{shop}.myshopify.com/admin/api/{version}/products.json?page_info={page_info}&limit={limit}>; rel={next}, <https://{shop}.myshopify.com/admin/api/{version}/products.json?page_info={page_info}&limit={limit}>; rel={previous}"
Run Code Online (Sandbox Code Playgroud)

如何使用链接?

谢谢

Bha*_*ara 5

下面的函数可以帮助你。在 Php/Laravel 中使用 API 获取数据

public function request($method,$url,$param = []){
    $client = new \GuzzleHttp\Client();
    $url = 'https://'.$this->username.':'.$this->password.'@'.$this->domain.'/admin/api/2019-10/'.$url;
    $parameters = [
        'headers' => [
            'Content-Type' => 'application/json',
            'Accept' => 'application/json'
        ]
    ];
    if(!empty($param)){ $parameters['json'] = $param;}
    $response = $client->request($method, $url,$parameters);
    $responseHeaders = $response->getHeaders();
    $tokenType = 'next';
    if(array_key_exists('Link',$responseHeaders)){
        $link = $responseHeaders['Link'][0];
        $tokenType  = strpos($link,'rel="next') !== false ? "next" : "previous";
        $tobeReplace = ["<",">",'rel="next"',";",'rel="previous"'];
        $tobeReplaceWith = ["","","",""];
        parse_str(parse_url(str_replace($tobeReplace,$tobeReplaceWith,$link),PHP_URL_QUERY),$op);
        $pageToken = trim($op['page_info']);
    }
    $rateLimit = explode('/', $responseHeaders["X-Shopify-Shop-Api-Call-Limit"][0]);
    $usedLimitPercentage = (100*$rateLimit[0])/$rateLimit[1];
    if($usedLimitPercentage > 95){sleep(5);}
    $responseBody = json_decode($response->getBody(),true);
    $r['resource'] =  (is_array($responseBody) && count($responseBody) > 0) ? array_shift($responseBody) : $responseBody;
    $r[$tokenType]['page_token'] = isset($pageToken) ? $pageToken : null;
    return $r;
}
Run Code Online (Sandbox Code Playgroud)

该函数的使用示例

$product_ids = [];
$nextPageToken = null;
do{
    $response = $shop->request('get','products.json?limit=250&page_info='.$nextPageToken);
    foreach($response['resource'] as $product){
        array_push($product_ids, $product['id']);
    }
    $nextPageToken = $response['next']['page_token'] ?? null;
}while($nextPageToken != null);
Run Code Online (Sandbox Code Playgroud)

如果你想在 php / laravel 中使用 graphQL api 那么下面的帖子可以帮助你

如何从 api 请求 shopify graphql-admin-api?

  • 我还使用 Laravel 和上述函数,我已将其包含在我的模型中(与存储访问令牌的表关联的商店模型)并在控制器中调用。----------------- 第一个代码块是模型,第二个代码块是控制器 (2认同)