【问题标题】:How to create pagination in shopify rest api using php如何使用php在shopify rest api中创建分页
【发布时间】:2019-09-05 09:00:02
【问题描述】:

我在 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}"

如何使用链接?

谢谢

【问题讨论】:

    标签: php rest api postman shopify


    【解决方案1】:

    以下功能可以帮助您。在 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 那么下面的帖子可以帮助你

    How to request shopify graphql-admin-api from an api?

    【讨论】:

    • 这看起来正是我所需要的,但是我很难理解它是如何在 Laravel 中设置的。这可以在控制器中的一个函数中完成,然后返回到视图或持久化到数据库中的“产品”表中吗?
    • 我也在使用 Laravel 及以上功能,我已包含在我的模型中(与存储访问令牌的表相关联的商店模型)并在控制器中调用。 ----------------- 第一个代码块是模型,第二个代码块是控制器
    【解决方案2】:

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

    首先进行一个普通的 API 调用,包含响应头。

    然后在标题响应中,您将看到链接:... 带有 rel 下一个或上一个。

    提取 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

    【讨论】:

      【解决方案3】:
      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);
          }
      }
      

      【讨论】:

      • 欢迎来到 Stackoverflow!请评论您的代码以解释它如何帮助任何未来的访问者回答您的问题。
      猜你喜欢
      • 1970-01-01
      • 2015-04-04
      • 1970-01-01
      • 2021-09-11
      • 1970-01-01
      • 2017-11-13
      • 1970-01-01
      • 2020-07-22
      • 1970-01-01
      相关资源
      最近更新 更多