Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shopify GraphQL PHP

I'm having some issues with using Shopify's GraphQL API. I've already made a bunch of REST calls, but for this one I would need GraphQL. I'm trying to add videos to certain products and this is what I have so far:

mutation productCreateMedia($productId: ID!, $media: [CreateMediaInput!]!) {
  productCreateMedia(productId: $productId, media: $media) {
    media {
      alt
    }
    mediaUserErrors {
      code
      field
      message
    }
    product {
      id
    }
  }
}

and for variables, I have an array of:

$gid = "gid://shopify/Product/".row('shopifyID');
$videoLink = "https://www.youtube.com/watch?v=".row('youtubeID');
$media = array('originalSource'=>$videoLink,'mediaContentType'=>'EXTERNAL_VIDEO');
$variables = array ('productId'=>$gid,'media'=>$media);

I use the next function for the call:

function graph($query , $variables = []){
$domain = 'domain.myshopify.com';
$url = 'https://'.$domain.'/admin/api/2020-01/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'=>'myAPIpass' // shopify app accessToken
    ],
]);

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

}

But what I'm getting back is: Variable productId of type ID! was provided invalid value

I used php-shopify SDK for REST API, but couldn't figure out how it works for GraphQL, so went with the usual way of just calling the JSON endpoint. Any help in what I'm doing wrong here?

like image 429
Bostjan Avatar asked Sep 03 '25 10:09

Bostjan


1 Answers

So...to answer my own question...the shopify ID string has to be base 64 encoded. I added just this line and it works now:

$gid = base64_encode($gid);
like image 75
Bostjan Avatar answered Sep 05 '25 03:09

Bostjan