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

时间:2019-08-08 05:51:54

标签: graphql shopify

我正在尝试从我的api请求shopify graphql-admin-api。我正在根据graphql-admin-api提供的文档进行此操作,但仍然会出现授权错误。

2 个答案:

答案 0 :(得分:0)

PHP用户可以使用此功能使用GraphQL向Shopify Admin API发出请求

我正在使用GuzzleHttp(PHP HTTP客户端)创建请求

public function graph($query , $variables = []){
    $domain = 'xxx.myshopify.com';
    $url = 'https://'.$domain.'/admin/api/2019-10/graphql.json';

    $request = ['query' => $query];

    if(count($variables) > 0) { $request['variables'] = $variables; }

    $req = json_encode($request);
    $parameters['body'] = $req;

    $stack = HandlerStack::create();
    $client = new \GuzzleHttp\Client([
        'handler'  => $stack,
        'headers'  => [
            'Accept'       => 'application/json',
            'Content-Type' => 'application/json',
            'X-Shopify-Access-Token'=>$this->token // shopify app accessToken
        ],
    ]);

    $response = $client->request('post',$url,$parameters);
    return $body =  json_decode($response->getBody(),true);
 }

  $query = "{ shop { name email } }"; // this is example graphQL query

  $response = graph($query) // call this function 

下面的代码可以帮助您检查此graphQL查询的费用

$calls = $response->extensions->cost;
$apiCallLimitGraph = [
     'left'          => (int) $calls->throttleStatus->currentlyAvailable,
     'made'          => (int) ($calls->throttleStatus->maximumAvailable - $calls->throttleStatus->currentlyAvailable),
     'limit'         => (int) $calls->throttleStatus->maximumAvailable,
     'restoreRate'   => (int) $calls->throttleStatus->restoreRate,
     'requestedCost' => (int) $calls->requestedQueryCost,
     'actualCost'    => (int) $calls->actualQueryCost,
];

答案 1 :(得分:0)

转到底部的应用程序 -> 管理应用程序,然后: 在 Shopify 中创建一个私人应用程序,它将连接到您的应用程序。确保您管理要查询的内容的权限

创建私有应用后,您将获得密码,您可以将其用作带有 header 'X-Shopify-Access-Token' value 的 HTTP 请求的令牌: 密码

  curl -X POST \
  https://{shop}.myshopify.com/admin/api/2021-04/graphql.json \
  -H 'Content-Type: application/graphql' \
  -H 'X-Shopify-Access-Token: {password}' \
  -d '
  {
    products(first: 5) {
      edges {
        node {
          id
          handle
        }
      }
      pageInfo {
        hasNextPage
      }
    }
  }
  '

更多访问:https://shopify.dev/docs/admin-api/getting-started#authentication

我在 NodeJS 中使用的方式是使用包 "graphql-request" 来发出请求和

const mutation = gql`
      mutation createProduct(
        $input: ProductInput!
        $media: [CreateMediaInput!]
      ) {
        productCreate(input: $input, media: $media) {
          userErrors {
            field
            message
          }
          product {
            id
            metafields(first: 1) {
              edges {
                node {
                  id
                }
              }
            }
          }
        }
      }
    `;
     //const input = form your own input 
     const res = await graphQLClient.rawRequest(mutation, input);