Cannot Create Variant with SquareConnect - php

Using SquareConnect's PHP Sdk, I am trying to create a very basic variant product using their API.
`
require('connect-php-sdk-master/autoload.php');
$access_token="SECRETACCESS TOKEN";
$location_id="LOCATION ID"; //only need the one
// Configure OAuth2 access token for authorization: oauth2
SquareConnect\Configuration::getDefaultConfiguration()->setAccessToken($access_token);
$api_instance = new SquareConnect\Api\CatalogApi();
$object_id = "OBJECTIDTHATWORKS"; // string
$include_related_objects = true; //
//print out the objectid. Works perfectly!
try {
$result = $api_instance->retrieveCatalogObject($object_id,$include_related_objects);
print_r($result);
} catch (Exception $e) {
echo 'Exception when calling CatalogApi->retrieveCatalogObject: ', $e->getMessage(), PHP_EOL;
}
//now create the variant and it will fail
$var_api = new \SquareConnect\Api\V1ItemsApi();
$variation = new \SquareConnect\Model\V1Variation(); // \SquareConnect\Model\V1Variation | An object containing the fields to POST for the request. See the corresponding object definition for field details.
$variation->setName("JERSUB");
$variation->setSku("JERSUPPERSKU");
try {
$meresult = $var_api->createVariation($location_id, $object_id, $variation);
print_r($meresult);
} catch (Exception $e) {
echo 'Exception when calling V1ItemsApi->createVariation: ', $e->getMessage(), PHP_EOL;
}
`
No matter what I do I always get a 400 Bad request.
Exception when calling V1ItemsApi->createVariation: [HTTP/1.1 400 Bad Request] {"type":"bad_request","message":"BadRequest"}
I have tried just passing in a blank variation object like the documentation, but it still does not work. How do I get around or diagnose the error?

I was using an older V1 version of the API. I found an OO way of doing it that was actually smarter. Below is a snippet that should hopefully help someone.
require('connect-php-sdk-master/autoload.php');
$access_token="SECRETACCESS TOKEN";
$location_id="LOCATION ID"; //only need the one
// Configure OAuth2 access token for authorization: oauth2
SquareConnect\Configuration::getDefaultConfiguration()->setAccessToken($access_token);
$api_instance = new SquareConnect\Api\CatalogApi();
$object_id = "OBJECTIDTHATWORKS"; // string
$include_related_objects = true; //
try {
$result = $api_instance->retrieveCatalogObject($object_id,$include_related_objects);
print_r($result);
} catch (Exception $e) {
echo 'Exception when calling CatalogApi->retrieveCatalogObject: ', $e->getMessage(), PHP_EOL;
}
$clone=$results[0];
$clone->setId("#TEMP123"); //change it to a temp id
$clone->setType("ITEM_VARIATION");
$id=$clone->getId();
$var_data=$clone->getItemVariationData();
//now clear/update the cloned object
$var_data->setName(UPC_FIELD_NAME);
$var_data->setSku("SUPPERSKU_TEST2"); //update sku
$var_data->setPricingType("VARIABLE_PRICING");
$var_data->setTrackInventory(null);
$var_data->setLocationOverrides(null); //got to remove location ovverides or it will track.
$var_data->setPriceMoney(null);
$clone->setItemVariationData($var_data);
//upsert it
$upsert=new \SquareConnect\Model\UpsertCatalogObjectRequest();
//set unique key
$upsert->setIdempotencyKey(md5(time()));
$upsert->setObject($clone);
//fire the update
$update_result=$api_instance->upsertCatalogObject($upsert);

Related

Square API object creation

I am using the square api to search my orders using the following code:
require '../connect-php-sdk-master/autoload.php';
// Configure OAuth2 access token for authorization: oauth2
SquareConnect\Configuration::getDefaultConfiguration()->setAccessToken('MY_AUTH_CODE');
//settings for the searchOrders
$searchOrdersSettings = ([
'location_ids'=>['MY_LOCATION_ID']
]);
$apiInstance = new SquareConnect\Api\OrdersApi();
$body = new \SquareConnect\Model\SearchOrdersRequest($searchOrdersSettings); // \SquareConnect\Model\SearchOrdersRequest | An object containing the fields to POST for the request. See the corresponding object definition for field details.
try {
$result = $apiInstance->searchOrders($body);
/* echo '<pre>';
print_r($result);
echo '<pre>'; */
} catch (Exception $e) {
echo 'Exception when calling OrdersApi->searchOrders: ', $e->getMessage(), PHP_EOL;
}
I would like to set a created_at start and end date but I have no idea how to create 'An object containing the fields to POST for the request'. Can anyone help me out?
Per the Square PHP SDK documentation, you would need to set the query and filter of the query. You can do something like this (tested and working as a small snippet):
require_once(__DIR__ . '/vendor/autoload.php');
// Configure OAuth2 access token for authorization: oauth2
SquareConnect\Configuration::getDefaultConfiguration()->setAccessToken('ACCESS_TOKEN_HERE');
$apiInstance = new \SquareConnect\Api\OrdersApi();
$body = new \SquareConnect\Model\SearchOrdersRequest();
$body->setLocationIds(['LOCATION_ID_HERE']);
// create query for searching by date
$query = new \SquareConnect\Model\SearchOrdersQuery();
$filter = new \SquareConnect\Model\SearchOrdersFilter();
$date_time_filter = new \SquareConnect\Model\SearchOrdersDateTimeFilter();
$date_time_filter->setCreatedAt([
"start_at" => "2020-03-01T00:00:00Z",
"end_at" => "2020-03-13T00:00:00Z"
]);
//pass the filter and query to the request
$filter->setDateTimeFilter($date_time_filter);
$query->setFilter($filter);
$body->setQuery($query);
try {
$result = $apiInstance->searchOrders($body);
error_log(var_dump($result));
} catch (Exception $e) {
echo 'Exception when calling OrdersApi->searchOrders: ', $e->getMessage(), PHP_EOL;
}

php rest API POST request returning null

I've created a REST API base on this tutorial - note that I am a newbie in php and REST...
Now, I am stuck when calling a POST request. The main return function is as follows:
// Requests from the same server don't have a HTTP_ORIGIN header
if (!array_key_exists('HTTP_ORIGIN', $_SERVER)) {
$_SERVER['HTTP_ORIGIN'] = $_SERVER['SERVER_NAME'];
}
try {
$API = new MyAPI($_REQUEST['request'], $_SERVER['HTTP_ORIGIN']);
$res = $API->processAPI();
echo $res; // contains my json as expected
return $res; // always empty string
} catch (Exception $e) {
echo "Exception: " . json_encode(Array('error' => $e->getMessage()));
}
EDIT
I've just tried something even simpler in the API caller method, namely following:
try {
$res = json_encode(Array('test' => "my message"));
// comment out one or the other to check output...
//echo $res;
return $res;
} catch (Exception $e) {
echo "Exception: " . json_encode(Array('error' => $e->getMessage()));
}
Result with echo is (the way I get responese is below... exact response is between # characters):
#{"test":"my message"}#
Result with return is
##
EDIT 2
Here is how I call the API from C#:
using (HttpClient client = new HttpClient()) {
JObject jo = new JObject();
jo.Add("usr", "username");
jo.Add("pwd", "password");
Uri url = new Uri(string.Format("{0}/{1}", RestUrl, "login"));
StringContent content = new StringContent(jo.ToString(), Encoding.UTF8, "application/json");
HttpResponseMessage response = await client.PostAsync(url, content);
bool isOk = response.StatusCode == System.Net.HttpStatusCode.OK;
// this is where I get the result from...
var res = response.Content.ReadAsStringAsync().Result;
}
I really don't understand this - could someone please explain in non-php expert terms??

ERROR: "Parsing WSDL: Couldn't load from" then do something

I have a SoapClient that is falling sometimes.
// send request
$client = new SoapClient("http://XXXXXXXXX.org/NowPlaying.asmx?WSDL");
$result = $client->GetNowPlaying();
// get array of items
$arr = $result->GetNowPlayingResult->PlayerItem;
In those times I would like to show something insted of the Error Message. I have done many if/else statements but anything work.
Can you help me?
Have you tried a try/catch?
try {
// send request
$client = new SoapClient("http://XXXXXXXXX.org/NowPlaying.asmx?WSDL");
$result = $client->GetNowPlaying();
// get array of items
$arr = $result->GetNowPlayingResult->PlayerItem;
} catch (Exception $e) {
echo 'Sorry, there was a problem!<br><br>';
echo 'Caught exception: ', $e->getMessage(), "\n";
}

stripe webhook test mode response "none"

I am trying to update database.
I have set up the webhook in stripe in test mode and send a "invoice.payment_succeeded" test webhook to file.but it shows response "none" in stripe output.
What have i done wrong, here is the webhook file, please someone help me, i am very stuck at this. any help will be appreciate...
<?php
include '../admin/include/functions.php';
require_once('Stripe/lib/Stripe.php');
require_once 'stripe_secret.php';
// Retrieve the request's body and parse it as JSON
$input = #file_get_contents("php://input");
$event_json = json_decode($input);
$event_id = $event_json->id;
if(isset($event_json->id)) {
try {
Stripe::setApiKey($stripe['secretkey']);
$event = Stripe_Event::retrieve($event_id);
var_dump($event);
$invoice = $event->data->object;
if($event->type == 'invoice.payment_succeeded') {
$customer = Stripe_Customer::retrieve($invoice->customer);
$email = $customer->email;
$customerid = $customer->id;
/*$amount = $invoice->amount / 100;*/
$expiry = $invoice->period->end;
$expiredate = date('Y-d-m', $expiry);
$userup = $obj->run_query("UPDATE users SET Expiry_Date = '$expiredate' WHERE user_stripe_id = '$customerid' ");
if ($userup) {
echo "User Date extended";
}
// send a invoice notice email here
}
if($event->type == 'invoice.payment_failed') {
$obj->run_query("UPDATE users SET Status = '0' WHERE user_stripe_id = '$customerid' ");
echo "User membership expired";
}
}
catch(Stripe_CardError $e) {
}
catch (Stripe_InvalidRequestError $e) {
// Invalid parameters were supplied to Stripe's API
} catch (Stripe_AuthenticationError $e) {
// Authentication with Stripe's API failed
// (maybe you changed API keys recently)
} catch (Stripe_ApiConnectionError $e) {
// Network communication with Stripe failed
} catch (Stripe_Error $e) {
// Display a very generic error to the user, and maybe send
// yourself an email
} catch (Exception $e) {
// Something else happened, completely unrelated to Stripe
}
}
http_response_code(200);
?>
The test webhooks from the test webhook button sends a webhook with the right format but all the values are null / zero / etc. Thus your line that does $obj->run_query("UPDATE users SET Expiry_Date = '$expiredate' WHERE user_stripe_id = '$customerid' "); will return a falsey result. This means you don't echo anything and just send back an empty 200 response.

PHP SOAP issue feeding in results

I'm trying to create a page that displays current results from CA Lottery using PHP. I've used XML before, but am having issues with SOAP. I found this page, but its not a lot of help.
I've put together the code below, and was able to get it to return an object. But I can't get it to feed in the results I need. Any help would be amazing.
try {
$options = array(
'soap_version'=>SOAP_1_1,
'exceptions'=>true,
'trace'=>1,
'cache_wsdl'=>WSDL_CACHE_NONE
);
$client = new SoapClient('http://services.calottery.com/CALotteryService.asmx?WSDL', $options);
} catch (Exception $e) {
echo "<p>Exception Error!</p>";
echo $e->getMessage();
}
echo '<p>Connection: Success;</p>';
try {
$response = $client->GetCurrentGameInfo();
} catch (Exception $e) {
echo 'Caught exception: ', $e->getMessage(), "\n";
}
$x = simplexml_load_string("<?xml version=\"1.0\"?>".$response->GetCurrentGameInfoResult->any);
var_dump($x);
Try this
var_dump($response);
$x = simplexml_load_string("<?xml version=\"1.0\"?>".$response->GetCurrentGameInfoResult->any);
var_dump($x);
at the end of your script. Kind of odd, but calottery is returning a fragment of XML in the response that needs to be further processed ( the simplexml_load_string ).

Categories