Laravel + Shopify inventoryBulkAdjustQuantityAtLocation - php

I'm using following package : 'osiset/Basic-Shopify-API' and need bulk update products by location.
It's only possible with GraphQL. This function should work :
inventoryBulkAdjustQuantityAtLocation Shopify documentation
$shop = 'example.myshopify.com';
$token = 'shppa_admin_api_token';
/ Create options for the API
$options = new Options();
$options->setVersion('2020-04');
// Create the client and session
$api = new BasicShopifyAPI($options);
$api->setSession(new Session($shop, $token));
$products[0]['inventoryItemId'] = '33125243617303';
$products[0]['availableDelta'] = 2000;
$result = $api->graph(
'mutation inventoryBulkAdjustQuantityAtLocation($inventoryItemAdjustments: InventoryAdjustItemInput!,$locationId: ID!)
{inventoryBulkAdjustQuantityAtLocation(inventoryItemAdjustments: $InventoryAdjustItemInput, locationId: $locationId) {userErrors {field message } inventoryLevels { id }}}',
['inventoryItemAdjustments' =>
$products
],
);
But I don't understand how to use it. Could anyone help me ?

Now it works. It's a challenge to understand GraphQL queries if you never used them before.
Here are some more information :
https://www.shopify.com/partners/blog/multi-location_and_graphql
$locationId = "gid://shopify/Location/1";
$inventoryItemAdjustments1['locationId'] = $locationId;
$inventoryItemAdjustments1['inventoryItemAdjustments']['inventoryItemId'] = 'gid://shopify/InventoryItem/1';
$inventoryItemAdjustments1['inventoryItemAdjustments']['availableDelta'] = 500;
$result = $api->graph('mutation inventoryBulkAdjustQuantityAtLocation($inventoryItemAdjustments: [InventoryAdjustItemInput!]!, $locationId: ID!)
{inventoryBulkAdjustQuantityAtLocation(inventoryItemAdjustments: $inventoryItemAdjustments, locationId: $locationId) {userErrors { field message }}}',
$inventoryItemAdjustments1
);

Not so good examples (hardcoded values, aliases - not real life examples) ... graphql variables should be used and they should match mutation requirements ('root' parameters), in this case locationId and inventoryItemAdjustments (array of objects).
You can test this mutation in graphiql/playground using 'query variables' defined like this:
{
locationId: "gid://shopify/Location/1",
inventoryItemAdjustments: [
{
'inventoryItemId': 'gid://shopify/InventoryItem/1',
'availableDelta': 500
},
{
'inventoryItemId': 'gid://shopify/InventoryItem/2',
'availableDelta': 100
}
]
}
... so using php (associative arrays are encoded to json as objects - explicitely declared for readability) it should look more like this:
$locationId = "gid://shopify/Location/1";
$inventoryItemAdjustments = [];
$inventoryItemAdjustments[] = (object)[
'inventoryItemId' => 'gid://shopify/InventoryItem/1',
'availableDelta'] => 500;
];
$inventoryItemAdjustments[] = (object)[
'inventoryItemId' => 'gid://shopify/InventoryItem/2',
'availableDelta'] => 100;
];
$variables = (object)[
'locationId' => $locationId;
'inventoryItemAdjustments' => $inventoryItemAdjustments
];
$result = $api->graph('mutation inventoryBulkAdjustQuantityAtLocation($inventoryItemAdjustments: [InventoryAdjustItemInput!]!, $locationId: ID!)
{inventoryBulkAdjustQuantityAtLocation(inventoryItemAdjustments: $inventoryItemAdjustments, locationId: $locationId) {userErrors { field message }}}',
$variables
);

I would like to show another library that uses this and expand on the last example.
I am using a slightly different library for graphql:
https://github.com/Shopify/shopify-php-api/
Updating the inventory like it was posted here shows a [statusCode:GuzzleHttp\Psr7\Response:private] => 200
So it seems to work but does not reflect in updated inventory. :(
Checking at /admin/products/inventory?location_id=62241177806&query=F11_27781195
would not show the new inventory.
I am using the inventoryid correctly (not product or variantid).
$inventoryItemAdjustments = array();
$inventoryItemAdjustments[] = (object)[
'inventoryItemId' => 'gid://shopify/InventoryItem/43151435235534',
'availableDelta' => 500
];
$inventoryItemAdjustments[] = (object)[
'inventoryItemId' => 'gid://shopify/InventoryItem/43151435268302',
'availableDelta' => 500
];
$variables = array(
'locationId' => ConfigClass::$locationId,
'inventoryItemAdjustments' => $inventoryItemAdjustments
);
$graphqlquery='mutation inventoryBulkAdjustQuantityAtLocation($inventoryItemAdjustments: [InventoryAdjustItemInput!]!, $locationId: ID!)
{inventoryBulkAdjustQuantityAtLocation(inventoryItemAdjustments: $inventoryItemAdjustments, locationId: $locationId) {userErrors { field message }}}';
$response = $client->query(['query' => $graphqlquery, 'variables' => $variables]);
Deleting a product works (and is a good test if the library is initialized well):
$query = <<<QUERY
mutation {
productDelete(input: {id: "gid://shopify/Product/6975310463182"})
{
deletedProductId
}
}
QUERY;
$response = $client->query(["query" => $query]);
print_r($response);
die;

Related

Google Task API PHP: Setting the TaskList ID & "Invalid task list ID" error

I'm trying to loop through task lists in order to generate a list of tasks using the Google Task PHP library.
I have:
Done all the credential stuff & can call the API
I can get task lists
A list of tasks for the respective task list output correctly using the ids generated from the point above & the tasklist parameter in Task API explorer
Where I'm stuck:
I'm not sure if I'm calling the 1) wrong method or 2) passing the wrong parameter to get a list of tasks for a respective tasklist id.
My code:
function getGcalTasks(){
$client = $this->getGcalTaskClient();
try {
$service = new Google_Service_Tasks($client);
$optParamLists = array(
'maxResults' => 10,
);
$result_lists = $service->tasklists->listTasklists($optParamLists);
if (
is_array($result_lists->getItems())
&& count($result_lists->getItems())
) {
foreach ($result_lists->getItems() as $tasklist) {
$taskListId = trim($tasklist->getId());
$taskListTitle = trim($tasklist->getTitle());
if(
$taskListId
){
$optParamsTasks = array(
// I've tried all of the below and still get: "Invalid task list ID",
'id' => $taskListId,
'kind' => 'tasks#taskList',
'title' => $taskListTitle,
//'tasklist' => $taskListId,
//'taskList' => $taskListId,
//'tasklistId' => $taskListId,
//'listName' => $taskListTitle,
);
$result_tasks = $service->tasks->listTasks($optParamsTasks);
}
}
}
} catch (Exception $e) {
log_message('error',$e->getMessage());
}
}
Welp, I took a look a few minutes later and realized that listTasks() only accepts one parameter, the id. The code below is working for me:
function getGcalTasks(){
$client = $this->getGcalTaskClient();
$tasks = array();
try {
$service = new Google_Service_Tasks($client);
$optParamLists = array(
'maxResults' => 10,
);
$result_lists = $service->tasklists->listTasklists($optParamLists);
if (
is_array($result_lists->getItems())
&& count($result_lists->getItems())
) {
foreach ($result_lists->getItems() as $tasklist) {
$taskListId = trim($tasklist->getId());
$taskListTitle = trim($tasklist->getTitle());
if(
$taskListId
){
$optParamsTasks = array(
'tasklist' => $taskListId,
);
$result_tasks = $service->tasks->listTasks($taskListId);
$tasks[] = $result_tasks->getItems();
}
}
return $tasks;
}
} catch (Exception $e) {
log_message('error',$e->getMessage());
}
}

Square API - invalid character 'C' looking for beginning of value

I am using Square Charge API, and following is my request object for a test card -
I am using Square provided PHP client to connect to the API. And I am receiving following response for "Charge" endpoint -
[HTTP/1.1 400 Bad Request] {"errors":[{"category":"INVALID_REQUEST_ERROR","code":"BAD_REQUEST","detail":"invalid character 'C' looking for beginning of value (line 1, character 1)"}]}
Following is my code in PHP -
public function chargeCustomerCard($userId, $custId, $cardId, $note, $billingAddres, $amount, $idempotencyKey){
$billingAddrRequest = array("address_line_1" => $billingAddres->addr1, "address_line_2" => $billingAddres->addr2, "locality" => $billingAddres->city, "administrative_district_level_1" => $billingAddres->state, "postal_code" => $billingAddres->zip, "country" => $billingAddres->country);
$billingAddressReq = new \SquareConnect\Model\Address($billingAddrRequest);
$moneyRequest = array("amount" => $amount, "currency" => "USD");
$money = new \SquareConnect\Model\Money($moneyRequest);
$request = array("idempotency_key" => $idempotencyKey, "customer_id" => $custId, "customer_card_id" => $cardId, "delay_capture" => false, "amount_money" => $money, "billing_address" => $billingAddressReq, "note" => $note, "reference_id" => $userId);
$charge = new \SquareConnect\Model\ChargeRequest($request);
$response = null;
try{
$charge_api = new \SquareConnect\Api\TransactionsApi();
$response = $charge_api->charge($this->authtoken, $this->locationId, $charge);
if($response != null && count($response->getErrors()) == 0){
$transaction = $response->getTransaction();
$data = array();
$data['transactionId'] = $transaction->getId();
$data['created'] = $transaction->getCreatedAt();
$data['referenceId'] = $transaction->getReferenceId(); //this should be equal to userid
$tender = $transaction->getTenders()[0];
$data['tenderId'] = $tender->getId();
$data['note'] = $tender->getNote();
$data['amount'] = ($tender->getAmountMoney()->getAmount())/100;
$data['currency'] = $tender->getAmountMoney()->getCurrency();
$processingFee = $tender->getProcessingFeeMoney();
if(isset($processingFee) && !empty($processingFee)){
$data['processingFee'] = $tender->getProcessingFeeMoney()->getAmount();
}else{
$data['processingFee'] = 0;
}
$data['tendertype'] = $tender->getType();
$data['cardStatus'] = $tender->getCardDetails()->getStatus();
$data['cardBrand'] = $tender->getCardDetails()->getCard()->getCardBrand();
$data['cardLast4'] = $tender->getCardDetails()->getCard()->getLast4();
$data['idempotencyKey'] = $idempotencyKey;
$data['customerPayId'] = $custId;
$data['customerCardId'] = $cardId;
return $this->generateReturnData(PAY_API_SUCCESS, '', $data);
}else{
return $this->generateReturnData(PAY_API_FAIL, '', $response->getErrors());
}
}catch(Exception $e) {
return $e->getMessage();
}
}
Can someone please point out to me what am I doing wrong here. I am really stuck here. Other API endpoints are working fine, such as, Create Customer, Create Customer Card API endpoints, using the same approach and same PHP client provided by square.
PS - this is on sandbox

How do I implement search filter query using mongodb?

i have few search filter user like the following image. User can select any one two or both
these are my filters language,format and status I have written a query but its not working
$lang_id =2;
$format = ''; //user not selected
$status = ''; //user not selected
$request = $collection->find(array
( '$and' => array(
array(
'language' => $lang_id ,
),
array(
'format' => $format,
),
array(
'status' => $status,
)
)
));
I have check with or also then also its not working
if filters are empty no need to find the empty field but if it is not empty need to find the field .
Please give me a solution I am new in mongodb
Thank you
As a solution to above mentioned issue please try executing following code snippet
$lang_id = 2;
$format = ''; //user not selected
$status = ''; //user not selected
$filter=array();
if(!empty($lang_id))
{
$filter['language']=$lang_id;
}
if(!empty($format))
{
$filter['format']=$format;
}
if(!empty($status))
{
$filter['status']=$status;
}
$request = $collection->find($filter);

GAE PHP Datastore Query

For a project I am using Google App Engine's Datastore with PHP, which does not have official documentation.
I used the following guide to successfully be able to add new entities to the datastore, but now I am struggling to get queries working so that I can retrieve data and display it on my web page.
https://gae-php-tips.appspot.com/2013/12/23/getting-started-with-the-cloud-datastore-on-php-app-engine/
Here is my current code:
try {
// test the config and connectivity by creating a test entity, building
// a commit request for that entity, and creating/updating it in the datastore
// $req = createRequest();
// $service_dataset->commit($dataset_id, $req, []);
$req = createQuery();
// printQueryResults($req);
}
catch (Google_Exception $ex) {
syslog(LOG_WARNING, 'Commit to Cloud Datastore exception: ' . $ex->getMessage());
echo "There was an issue -- check the logs.";
return;
}
function createQuery()
{
$gql_query = new Google_Service_Datastore_GqlQuery();
$gql_query->setQueryString("SELECT * FROM 'Notes' WHERE name = 'test1'");
$gql_query->setAllowLiteral(true);
$req = new Google_Service_Datastore_RunQueryRequest();
$req->setGqlQuery($gql_query);
return $req;
}
I want to be able to query my datastore and get all the entities that have a matching name.
I tested successfully this following code adapted, i assume that you are using DatastoreService.php from the guide you mentioned. There must be different ways to parse the query result but here is one ;)
config.php : replace with your credentials
<?php
$google_api_config = [
'application-id' => 'xxxxxxxxxxxxxxx',
'service-account-name' => 'xxxxx#developer.gserviceaccount.com',
'private-key' => file_get_contents('xxxxxxx.p12'),
'dataset-id' => 'xxxxxxxxxxxx'
];
your code adapted
require_once 'config.php';
require_once 'DatastoreService.php';
try {
$req = createQuery();
}
catch (Google_Exception $ex) {
syslog(LOG_WARNING, 'Commit to Cloud Datastore exception: ' . $ex->getMessage());
echo "There was an issue -- check the logs.";
return;
}
// from config.php
$options = $google_api_config;
$datastoreService = new DatastoreService($options);
$result = $datastoreService->runQuery($req, $optParams = []);
$results = $result->getBatch()->getEntityResults();
$items = array();
foreach ($results as $item) {
$item = $item->getEntity()->getProperties();
$items[] = $item['name']['stringValue'];
}
echo '<plaintext>' . print_r($items, true);
function createQuery()
{
$gql_query = new Google_Service_Datastore_GqlQuery();
$gql_query->setQueryString($query = "SELECT * FROM Notes WHERE name = 'test1'");
$gql_query->setAllowLiteral(true);
$req = new Google_Service_Datastore_RunQueryRequest();
$req->setGqlQuery($gql_query);
return $req;
}
Include google/cloud-datastore library via composer as below.
$ composer require google/cloud-datastore
and you can use Query mothod as Example below.
<?php
require 'vendor/autoload.php';
use Google\Cloud\Datastore\DatastoreClient;
$datastore = new DatastoreClient([
'projectId' => 'my_project'
]);
$query = $datastore->query();
$query->kind('Notes');
$query->filter('name ', '=', 'test1');
$res = $datastore->runQuery($query);
foreach ($res as $notes) {
echo $notes['name']; // test1
}
Or it can be build using query object
<?php
$query = $datastore->query([
'query' => [
'kind' => [
[
'name' => 'Notes'
]
],
'filter' => [
'propertyFilter' => [
'op' => 'EQUAL',
'property' => [
'name' => 'name'
],
'value' => [
'stringValue' => 'test1'
]
]
]
]
]);

PHP Arrays - How to use Multiple variables in array

I have a product import code for Magento that assigns inventory (qty) to a warehouse location (stock_id). The information is passed in an array however my working knowledge of arrays isn't that flash so I'm sure I'm not doing this correctly.
The import is currently done like this however I'm sure it's not the most efficient as I'm saving the product twice.
This will assign a qty of 100 to location 1 (stock_id 1), save the product, then assign a qty of 200 to location 2 (stock_id 2) and then save the product again.
$stocksData = $product->getStocksData();
if (!$stockData) {
$stockData = array();
}
$stockData['stock_id'] = 1;
$stockData['qty'] = 100;
$stocksData[$stockId] = $stockData;
$product->setStocksData($stocksData);
$product->setCreatedAt(strtotime('now'));
try {
$product->save();
echo "Successful";
}
catch (Exception $ex) {
echo 'There was an error :<br/>' .$ex;
}
$stocksData = $product->getStocksData();
if (!$stockData) {
$stockData = array();
}
$stockData['stock_id'] = 2;
$stockData['qty'] = 200;
$stocksData[$stockId] = $stockData;
$product->setStocksData($stocksData);
$product->setCreatedAt(strtotime('now'));
try {
$product->save();
echo "Successful";
}
catch (Exception $ex) {
echo 'There was an error :<br/>' .$ex;
}
What I'm trying to achieve is to set all of the values in the array and save once as this will take a lot of load off the script.
I've been playing around with stuff like this, however haven't got anywhere and usually end up with errors:
$stocksData = $product->getStocksData();
if (!$stockData) {
$stockData = array();
}
$stockData = array(
[$stockData['stock_id'] = 1] => $stockData['qty'] = 100,
[$stockData['stock_id'] = 2] => $stockData['qty'] = 200
);
$stocksData[$stockId] = $stockData;
$product->setStocksData($stocksData);
I'm assuming it's possible to have all of this information in one array but I'm just not sure how.
There are a lot of ways to initialize an array in php.
$stocksData = array(
'key' => 'value',
'myarr' => array(
'nested' => 'array',
1,
),
'id_copy' => $stocksData['id'],
'qty' => $stocksData['stock_id'] == 1 ? 100 : 200,
);
For a full explanation of array syntax, check out php's Array documentation. Also note my usage of the ternary operator. You can get around using this syntax by saying something like:
if ($stocksData['id'] == 1) {
$stocksData['qty'] = 100;
}
else {
$stocksData['qty'] = 200;
}
Edit:
For your specific use case of combining the requests, take a look below:
$stocksData = $product->getStocksData();
$stocksData[1] = array(
'stock_id' => 1,
'qty' => 100,
);
$stocksData[2] = array(
'stock_id' => 2,
'qty' => 200,
);
$product->setStocksData($stocksData);

Categories