繁体   English   中英

如何使用php在shopify rest api中创建分页

[英]How to create pagination in shopify rest api using php

我在 php 中创建了 curl 以使用 shopify product rest 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}"

如何使用链接?

谢谢

下面的功能可以帮助你。 在 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;
}

此函数的示例用法

$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);

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

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

从 API 版本 2019-07 开始,您确实需要使用基于游标的分页。

首先进行正常的 API 调用,包括标头响应。

然后在标头响应中,您将看到 link : ... with rel next or previous。

提取 page_info,然后使用 page_info 再次调用。

第一个调用是这样的:

https://...:...@xyz.myshopify.com/admin/api/2019-10/products.json?limit=2&published_status=published

然后第二个电话是

https://...:...@xyz.myshopify.com/admin/api/2019-10/products.json?limit=2&page_info=asdfas1321asdf3as1f651saf61s3f1x32v1akjhfasdj

当您进行第二次调用时,删除所有过滤器,因为过滤器将从第一次调用中应用。

顺便说一句:如果您在浏览器中测试由于链接在尖括号中的方式,它将被隐藏,因此只需在您的开发人员环境中查看源代码。

参考: https : //help.shopify.com/en/api/guides/paginated-rest-results

private $shop_url = '';
private $shop_user = '';
private $shop_password = '';

function __construct($shop) {
    $this->shop_url = $shop->url;
    $this->shop_user = $shop->user;
    $this->shop_password = $shop->userpas;
    $this->syncShopifyOrder($shop);
}

private function getOrderRequest($url){
    $client = new \GuzzleHttp\Client();
    $response = $client->request('GET', $url, [
        'auth' => [$this->shop_user, $this->shop_password]
    ]);

    if($response->getStatusCode() !== 200){
        throw new OrderSyncException('Connection problem!');
    }

    $data = [];
    $paginate_links = $response->getHeader('Link');

    if($paginate_links){

        $page_link = $paginate_links[0];
        $links_arr = explode(",", $page_link);

        if($links_arr){

            $tobeReplace = ["<",">",'rel="next"',";",'rel="previous"'];
            $tobeReplaceWith = ["","","",""];

            foreach ($links_arr as $link) {
                $link_type  = strpos($link, 'rel="next') !== false ? "next" : "previous";
                parse_str(parse_url(str_replace($tobeReplace, $tobeReplaceWith, $link), PHP_URL_QUERY), $op);
                $data[$link_type] = trim($op['page_info']);
            }
        }
    }

    $order_data = $response->getBody()->getContents();
    $data['all_orders'] = (json_decode($order_data))->orders;
    return $data;
}


// Shopify Orders
private function syncShopifyOrder($shop)
{
    $count = 0;
    try{
        if($shop){
            $nextPageToken = null;
            do{
                $param = ($nextPageToken)? '&page_info='.$nextPageToken : '&status=any&fulfillment_status=any&order=created_at asc&created_at_min=2020-08-10T13:30:33+02:00';
                $url = $this->shop_url . 'admin/api/2020-01/orders.json?limit=250'.$param;

                $data = $this->getOrderRequest($url);
                $all_orders = $data['all_orders'];
                $nextPageToken = isset($data['next']) ? $data['next'] : null;
                
                if($all_orders){
                    $count += count((array) $all_orders);
                    $this->bulkorderInsertShopify($shop, $all_orders);
                }
            }while($nextPageToken);
        }else{
            throw new OrderSyncException('You have not configured shop!');
        }
        $this->syncSuccessReport($shop, $count);

    }catch(OrderSyncException $e) {
        $this->syncErrorReport($shop, $count, $e->getMessage());
        
    }catch(\Exception $e) {
        $this->syncErrorReportAdmin($shop, $count, $e);
    }
}

Rest API没有下一个功能。 您正在弥补。 如果要使用下一个分页样式的调用,请改用GraphQL API终结点,并在此处使用光标功能,该功能内置了下一个和上一个概念。

因此,您可以用与Rest API兼容的实际页码替换下一个愿望,或者切换到GraphQL并使用游标提供下一个和上一个。

暂无
暂无

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

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