How I fetch the products from the shiphero by using the query method

Sonar,

You should be able to use low-level functions like cURL or any HTTP library (e.g. Guzzle) to manually make POST requests to your endpoint. If you use a tool like Postman (which is just like Insomnia) and they have a feature that will take your built request and convert it to a cURL request which you can manually rebuild in PHP.

The basics of it would be that the GraphQL query you build and the variables need to be wrapped in a JSON object and that object placed as the POST body:

{
  "query": "query($orderId:ID!) {  order(id:$orderId) {    transactions {      createdAt      gateway      formattedGateway      receipt    }  }}",
  "variables": { "orderId": "12345" }
}

Keep in mind that JSON doesn’t allow for multi-line strings. So generally the easiest thing to do would be to create an array and use json_encode to get the POST body:

$body = json_encode([
  "query": 'query($orderId:ID!) {
  order(id:$orderId) {
    transactions {
      createdAt
      gateway
      formattedGateway
      receipt
    }
  }
}',
  "variables": [
    "orderId": 12345,
  ]
]);

As for the request itself, all you need to specify is the correct headers, set the post body, and then send the request away and capture the response. A simplistic version would be:

$ch = curl_init();
curl_setopt_array($ch, [
  CURLOPT_POST => true,
  CURLOPT_POSTFIELDS => $body, // Created same as previous snippet
  CURLOPT_HTTPHEADER => [
    'Content-Type: application/json',
    'Accept: application/json',
    'Authorization: Bearer <ShipHeroAuthToken>',
  ],
  CURLOPT_RETURNTRANSFER => true,
]);
$response = curl_exec($ch);

Then you just need to parse the response JSON and extract the information you want/need out of it.

If you don’t want to build out your own mini-library for this, you can use Composer to install a client and use it instead (though they all basically do the same thing I just posted above).

GraphQL PHP Client
Gist of a minimal GraphQL client

Hope that helps. FWIW, I’m implementing something very similar using Go. The auth process has to be separate from the GraphQL stuff, but the auth process is pretty straightforward.

2 Likes