Square API object creation - php

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;
}

Related

Sendinblue: Invalid emails format when adding contact to list

Using Sendinblue API, I get a Bad Request response: {"code":"invalid_parameter","message":"Invalid emails format"}when I'm trying to use the functionAddContactToList`.
I have no problem when trying to create contact. Contact is sent with emails and attributes. I want now to add existing contacts in a list.
This is the code of the add contact to list page:
// Configure API key authorization: api-key
$config = SendinBlue\Client\Configuration::getDefaultConfiguration()->setApiKey('api-key', 'xxxxxxxxxxxxxxxxxx');
// Uncomment below to setup prefix (e.g. Bearer) for API key, if needed
// $config = SendinBlue\Client\Configuration::getDefaultConfiguration()->setApiKeyPrefix('api-key', 'Bearer');
// Configure API key authorization: partner-key
$config = SendinBlue\Client\Configuration::getDefaultConfiguration()->setApiKey('partner-key', 'xxxxxxxxxxxxxxxxxxxxxxx');
// Uncomment below to setup prefix (e.g. Bearer) for API key, if needed
// $config = SendinBlue\Client\Configuration::getDefaultConfiguration()->setApiKeyPrefix('partner-key', 'Bearer');
$apiInstance = new SendinBlue\Client\Api\ContactsApi(
// If you want use custom http client, pass your client which implements `GuzzleHttp\ClientInterface`.
// This is optional, `GuzzleHttp\Client` will be used as default.
new GuzzleHttp\Client(),
$config
);
$row = 0;
if (($handle = fopen("contactlist.csv", "r")) !== FALSE) {
while (($data = fgetcsv($handle, 0, ";")) !== FALSE) {
$row++;
usleep(1000);
if($row>70){
$listId = 42; // int | Id of the list
$contactEmails = new \SendinBlue\Client\Model\AddContactToList(); // \SendinBlue\Client\Model\AddContactToList | Emails addresses of the contacts
$contactEmails['emails'] =$data[1];
echo $data[1];echo '<br>';
try {
$result = $apiInstance->addContactToList($listId, $contactEmails);
print_r($result);
} catch (Exception $e) {
echo 'Exception when calling ContactsApi->addContactToList: ', $e->getMessage(), PHP_EOL;
}
echo '<br>';echo '<br>';echo '<br>';
}
if($row==400){
die();
}
}
fclose($handle);
}
?>
This is the result I get:
xxxxx#example.com
Exception when calling ContactsApi->addContactToList:
[400] Client error: POST
https://api.sendinblue.com/v3/contacts/lists/42/contacts/add resulted
in a 400 Bad Request response:
{"code":"invalid_parameter","message":"Invalid emails format"}
Thank you for your help.
Here is my working code :
require_once(__DIR__ . '/vendor/autoload.php');
$config = SendinBlue\Client\Configuration::getDefaultConfiguration()->setApiKey('api-key', 'YOUR-APIKEY');
$config = SendinBlue\Client\Configuration::getDefaultConfiguration()->setApiKey('partner-key', 'YOUR-APIKEY');
$apiInstance = new SendinBlue\Client\Api\ContactsApi(
new GuzzleHttp\Client(),
$config
);
$createAttribute = new \SendinBlue\Client\Model\CreateAttribute([
'name' => 'Your Name',
'type' => 'email' // email, sms
]);
$createContact = new \SendinBlue\Client\Model\CreateContact([
'email' => 'test#email.be',
'attributes' => $createAttribute,
'listIds' => [28], // Int() | Number of your list in your account
]); // \SendinBlue\Client\Model\CreateContact | Values to create a contact
try {
$result = $apiInstance->createContact($createContact);
print_r($result);
} catch (Exception $e) {
echo 'Exception when calling ContactsApi->createContact: ', $e->getMessage(), PHP_EOL;
}

Cannot Create Variant with SquareConnect

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);

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";
}

twilio catching error does not work

I am implementing twilio in my laravel 5 application. To use it in the framework I use aloha/laravel-twilio integration.
Sending a valid request with test-credentials works fine. I have problems when I want to implement an error-handling.
For some reason the catch does not get the error, which results in a crash of the app. The error seems to be in the twilio-sdk if I read the error message correctly.
Here is what I've done so far:
<?php namespace App;
use Illuminate\Database\Eloquent\Model;
use Aloha\Twilio\TwilioInterface;
class Activation extends Model {
protected $fillable = array( 'a', 'b', 'c');
public static function send() {
// Testaccount
// $toNumber = '+15005550006'; // valid number; works fine
$toNumber = '+15005550001'; // #todo will throw an exeption, and breaks the app
try {
\Twilio::message( $toNumber, 'Pink Elephants and Happy Rainbows');
} catch ( Services_Twilio_RestException $e ) {
elog( 'EACT', $e->getMessage( ) , __FUNCTION__ ); // this is not called when an twilio error occurs
}
}
}
This results in the following error:
Whoops, looks like something went wrong.
Services_Twilio_RestException in /path/to/my/laravel/vendor/twilio/sdk/Services/Twilio.php line 297
Exception_message: The 'To' number +15005550001 is not a valid phone number.
From the documentation this error (not valid phone numer) shall be thrown, but I should have a possiblity to catch and process it. Currently, this does not work. I do not get the error catched...
How can I get the twilio-errors catched and processed?
The class is in a namespace, so I have to reference the absolut class exception - \Services_Twilio_RestException - in the catch .
It works with this code:
try {
\Twilio::message( $toNumber, 'Pink Elephants and Happy Rainbows');
} catch ( \Services_Twilio_RestException $e ) {
elog( 'EACT', $e->getMessage( ) , __FUNCTION__ );
}
See below which is valid as of today. TwilioException is not valid and neither is Services_Twilio_RestException. You should use Exception instead.
UPDATE
You need to import Twilio\Exceptions\TwilioException for TwilioException to work.
My use case is I had to send to a database of numbers and not have an invalid phone number break my script. We did some work-around a month or two ago which involved logging when a message was sent and had a cron job checking where we left off every two minutes... not efficient when you're sending tens of thousands of text messages.
require_once '../Twilio/autoload.php'; // Loads the library
use Twilio\Rest\Client;
//some test fail numbers
$arr = array(1234567890,"11855976lend1",321619819815,198198195616516);
/* ==================================================================================
//create a function to send SMS using copilot (uses an SID instead of a phone number)
================================================================================*/
function sendSMS($to){
// Download the PHP helper library from twilio.com/docs/php/install
// These vars are your accountSid and authToken from twilio.com/user/account
$account_sid = 'xxx';
$auth_token = 'xxx';
$client = new Client($account_sid, $auth_token);
//this nifty little try/catch will save us pain when we encounter bad phone numbers
try{
$client->messages->create(
$to,
array(
'messagingServiceSid' => "MGxxx",
'body' => "This is the body we're sending."
)
);
//sent successfully
echo "sent to $to successfully<br>";
}catch(Exception $e){
echo $e->getCode() . ' : ' . $e->getMessage()."<br>";
}
}
foreach($arr as &$value){
sendSMS($value);
}
//remember to unset the pointer so you don't run into issues if re-using
unset($value);
Today (19-May-2017) the code is like this :
// Step 1: set our AccountSid and AuthToken from https://twilio.com/console
$AccountSid = "XXX";
$AuthToken = "XXX";
$client = new Client($AccountSid, $AuthToken);
try {
$sms = $client->account->messages->create(
// the number we are sending to - Any phone number
$number,
array(
// Step 2: Change the 'From' number below to be a valid Twilio number
// that you've purchased
'from' => "+XXXXXXXXXXX",
// the sms body
'body' => $sms
)
);
// Display a confirmation message on the screen
echo "Sent message to $name";
} catch (TwilioException $e) {
die( $e->getCode() . ' : ' . $e->getMessage() );
}
This is what worked for me:
$twilioCli = new \Twilio\Rest\Client(config('app.twilioAccountSID'), config('app.twilioAuthToken'));
try {
$twilioCli->messages->create(
$formattedToNum,
[
'from' => config('app.twilioFromNumber'),
'body' => "sms body goes here"
]
);
}
catch (\Twilio\Exceptions\RestException $e) {
echo "Error sending SMS: ".$e->getCode() . ' : ' . $e->getMessage()."\n";
}

Salesforce error: Element {}item invalid at this location

i am using the below code to connect to salesforce using php
require_once ('SforcePartnerClient.php');
require_once ('SforceHeaderOptions.php');
require_once ('SforceMetadataClient.php');
$mySforceConnection = new SforcePartnerClient();
$mySforceConnection->createConnection("cniRegistration.wsdl");
$loginResult = $mySforceConnection->login("username", "password.token");
$queryOptions = new QueryOptions(200);
try {
$sObject = new stdclass();
$sObject->Name = 'Smith';
$sObject->Phone = '510-555-5555';
$sObject->fieldsToNull = NULL;
echo "**** Creating the following:\r\n";
$createResponse = $mySforceConnection->create($sObject, 'Account');
$ids = array();
foreach ($createResponse as $createResult) {
print_r($createResult);
array_push($ids, $createResult->id);
}
} catch (Exception $e) {
echo $e->faultstring;
}
But the above code is connect to salesforce database.
But is not executing the create commands. it's giving me the below error message
Creating the following: Element {}item invalid at this location
can any one suggest me to overcome the above problem
MAK, in your sample code SessionHeader and Endpoint setup calls are missing
$mySforceConnection->setEndpoint($location);
$mySforceConnection->setSessionHeader($sessionId);
after setting up those, if you still see an issue, check the namespace urn
$mySforceConnection->getNamespace
It should match targetNamespace value in your wsdl
the value of $mySforceConnection should point to the xml file of the partner.wsdl.xml.
E.g $SoapClient = $sfdc->createConnection("soapclient/partner.wsdl.xml");
Try adding the snippet code below to reference the WSDL.
$sfdc = new SforcePartnerClient();
// create a connection using the partner wsdl
$SoapClient = $sfdc->createConnection("soapclient/partner.wsdl.xml");
$loginResult = false;
try {
// log in with username, password and security token if required
$loginResult = $sfdc->login($sfdcUsername, $sfdcPassword.$sfdcToken);
}
catch (Exception $e) {
global $errors;
$errors = $e->faultstring;
echo "Fatal Login Error <b>" . $errors . "</b>";
die;
}
// setup the SOAP client modify the headers
$parsedURL = parse_url($sfdc->getLocation());
define ("_SFDC_SERVER_", substr($parsedURL['host'],0,strpos($parsedURL['host'], '.')));
define ("_SALESFORCE_URL_", "https://test.salesforce.com");
define ("_WS_NAME_", "WebService_WDSL_Name_Here");
define ("_WS_WSDL_", "soapclient/" . _WS_NAME_ . ".wsdl");
define ("_WS_ENDPOINT_", 'https://' . _SFDC_SERVER_ . '.salesforce.com/services/wsdl/class/' . _WS_NAME_);
define ("_WS_NAMESPACE_", 'http://soap.sforce.com/schemas/class/' . _WS_NAME_);
$urlLink = '';
try {
$client = new SoapClient(_WS_WSDL_);
$sforce_header = new SoapHeader(_WS_NAMESPACE_, "SessionHeader", array("sessionId" => $sfdc->getSessionId()));
$client->__setSoapHeaders(array($sforce_header));
} catch ( Exception $e ) {
die( 'Error<br/>' . $e->__toString() );
}
Please check the link on Tech Thought for more details on the error.

Categories