What is a pagination cursor & how can I use it - php

I am trying to retrieve a list of customers using the square PHP SDK. If I leave the $cursor blank, I can see a list of all of my customer information. How do I use the pagination cursor to receive a customer by their name? Sample code below:
<?php
require_once(__DIR__ . '/vendor/autoload.php');
// Configure OAuth2 access token for authorization: oauth2
SquareConnect\Configuration::getDefaultConfiguration()->setAccessToken('YOUR_ACCESS_TOKEN');
$api_instance = new SquareConnect\Api\CustomersApi();
// string | A pagination cursor returned by a previous call to this endpoint.
//Provide this to retrieve the next set of results for your original query.
//See [Paginating results](#paginatingresults) for more information.
$cursor = "cursor_example";
try {
$result = $api_instance->listCustomers($cursor);
print_r($result);
} catch (Exception $e) {
echo 'Exception when calling CustomersApi->listCustomers: '
, $e->getMessage(), PHP_EOL;
}
?>

The pagination cursor does not allow you to query for customers by name. If you have more than one "page" of customer, then it allows for you to get more customers by providing a token representing the next page.
If you have enough customers to fill multiple pages, a cursor would be returned in the response.

Related

Google Analytics PHP client is returning empty response

I'm using the Google analytics PHP client library and implemented as described like in this documentation.
https://developers.google.com/analytics/devguides/config/mgmt/v3/quickstart/service-php.
Here is my last function which used for print the result ( other functions are exact as in the document above )
function printResults($results)
{
// Parses the response from the Core Reporting API and prints
// the profile name and total sessions.
if (count($results->getRows()) > 0) {
// Get the profile name.
$profileName = $results->getProfileInfo()->getProfileName();
// Get the entry for the first entry in the first row.
$rows = $results->getRows();
$sessions = $rows[0][0];
// Print the results.
print "First view (profile) found: $profileName\n";
print "Total sessions: $sessions\n";
} else {
print "No results found.\n";
}
}
Every other things are working perfectly. Yes I tested the credentials again.
Problem is when I run the code it ends up with this error message "
ErrorException: count(): Parameter must be an array or an object that implements Countable
When i try
dd($results->getRows());
I'm expecting the analytics data to be returned. But it gives me a NULL value.
(I'm using Laravel)
What can be the reason for these null value?

How to Return List of Project Tasks in ActiveCollab

Sorry this may be a trivial question but I am new to PHP. In the documentation to retrieve project tasks, the following code is provided to connect to an Active Collab cloud account:
<?php
require_once '/path/to/vendor/autoload.php';
// Provide name of your company, name of the app that you are developing, your email address and password.
$authenticator = new \ActiveCollab\SDK\Authenticator\Cloud('ACME Inc', 'My Awesome Application', 'you#acmeinc.com', 'hard to guess, easy to remember');
// Show all Active Collab 5 and up account that this user has access to.
print_r($authenticator->getAccounts());
// Show user details (first name, last name and avatar URL).
print_r($authenticator->getUser());
// Issue a token for account #123456789.
$token = $authenticator->issueToken(123456789);
// Did we get it?
if ($token instanceof \ActiveCollab\SDK\TokenInterface) {
print $token->getUrl() . "\n";
print $token->getToken() . "\n";
} else {
print "Invalid response\n";
die();
}
This works fine. I can then create a client to make API calls:
$client = new \ActiveCollab\SDK\Client($token);
and get the list of tasks for a given project as shown in the documentation.
$client->get('projects/65/tasks'); // PHP object
My question is, what methods/attributes are available to get the list of tasks? I can print the object using print_r() (print will obviously not work), and what I really want is in the raw_response header. This is private however and I cannot access it. How do I actually get the list of tasks (ex: the raw_response either has a string or json object)?
Thanks in advance.
There are several methods to work with body:
$response = $client->get('projects/65/tasks');
// Will output raw JSON, as string.
$response->getBody();
// Will output parsed JSON, as associative array.
print_r($response->getJson());
For full list of available response methods, please check ResponseInterface.
If you wish to loop through tasks, use something like this:
$response = $client->get('projects/65/tasks');
$parsed_json = $response->getJson();
if (!empty($parsed_json['tasks'])) {
foreach ($parsed_json['tasks'] as $task) {
print $task['name'] . "\n"
}
}

Using Service Account to access Google Analytics API doesn't work

I'm trying to access my Google Analytics data using a service account. I've created one in the Developers Console and I've enabled the Google Analytics API in that same console, but somehow, I can't manage to pull data from the API.
I've used the script on this page.
My code is as follows:
<?php
$keyfile = 'google/key.p12';
// Initialise the Google Client object
$client = new Google_Client();
$client->setApplicationName('MyNAME');
$client->setAssertionCredentials(
new Google_AssertionCredentials(
'XXXX#developer.gserviceaccount.com', array('https://www.googleapis.com/auth/analytics.readonly'), file_get_contents($keyfile)
)
);
$client->setClientId('XXXX.apps.googleusercontent.com');
$client->setAccessType('offline_access');
$analytics = new Google_AnalyticsService($client);
$analytics_id = 'ga:UA-XXXXXX-1'; // http://productforums.google.com/forum/#!topic/analytics/dRuAr1K4waI
// get data for the last 2 weeks
$lastWeek = date('Y-m-d', strtotime('-2 week'));
$today = date('Y-m-d');
// Test connection
try {
$results = $analytics->data_ga->get($analytics_id, $lastWeek, $today, 'ga:visits');
echo '<b>Number of visits this week:</b> ';
echo $results['totalsForAllResults']['ga:visits'];
} catch (Exception $e) {
echo 'There was an error : - ' . $e->getMessage();
}
?>
Note: if it says "XXXX", that means I've removed part of the string for security purposes; the proper strings are in my actual script.
It should either display the number of users or a error, but I just get a blank screen. I'm sure the URL to the keyfile is correct.
Does anybody have suggestions on how to fix this? That would be much appreciated.
It looks like you are using your property Id (UA-XXXXX-1) in place of your view (profile) id. If you go to Google Analytics Query Explorer it makes it easy to see what your actual ga:XXXX view (profile) id is. Any given property can have multiple view's (profiles). This reference guide gives a good description of the parameters that this request requires.

QBO API Add Payment error

I'm connecting to Quicbooks using IPP_V3 from my webserver.
I'm trying to implement the example_payment_add.php
I'm getting a Business validation error when adding payment by assigning it to an invoice.
I even changed the order in which the values are assigned as instructed in the below page:
https://developer.intuit.com/docs/0025_quickbooksapi/0050_data_services/030_entity_services_reference/payment
(Last point: The sequence in which the Lines are received is the sequence in which lines are preserved.)
Note: Just adding a payment to a customer, without assigning it to a customer, is working.
Error:
6000: [A business validation error has occurred while processing your request, Business Validation Error: Unexpected Internal Error. (-30035)]
Code:
require_once dirname(__FILE__) . '/config.php';
require_once dirname(__FILE__) . '/views/header.tpl.php';
?>
<pre>
<?php
// Set up the IPP instance
$IPP = new QuickBooks_IPP($dsn);
// Get our OAuth credentials from the database
$creds = $IntuitAnywhere->load($the_username, $the_tenant);
// Tell the framework to load some data from the OAuth store
$IPP->authMode(
QuickBooks_IPP::AUTHMODE_OAUTH,
$the_username,
$creds);
// Print the credentials we're using
//print_r($creds);
// This is our current realm
$realm = $creds['qb_realm'];
// Load the OAuth information from the database
if ($Context = $IPP->context())
{
// Set the IPP version to v3
$IPP->version(QuickBooks_IPP_IDS::VERSION_3);
$PaymentService = new QuickBooks_IPP_Service_Payment();
// Create payment object
$Payment = new QuickBooks_IPP_Object_Payment();
$Payment->setTxnDate('2014-04-04');
// Create line for payment (this details what it's applied to)
$Line = new QuickBooks_IPP_Object_Line();
$Line->setAmount(1);
// The line has a LinkedTxn node which links to the actual invoice
$LinkedTxn = new QuickBooks_IPP_Object_LinkedTxn();
$LinkedTxn->setTxnId('10001'); //real invoice number in quickbooks
$LinkedTxn->setTxnType('Invoice');
$Line->setLinkedTxn($LinkedTxn);
$Payment->addLine($Line);
$Payment->setCustomerRef('876');
$Payment->setPaymentRefNum('8762393');
$Payment->setTotalAmt(1);
// Send payment to QBO
if ($resp = $PaymentService->add($Context, $realm, $Payment))
{
print('Our new Payment ID is: [' . $resp . ']');
}
else
{
print($PaymentService->lastError());
}
/*
print('<br><br><br><br>');
print("\n\n\n\n\n\n\n\n");
print('Request [' . $IPP->lastRequest() . ']');
print("\n\n\n\n");
print('Response [' . $IPP->lastResponse() . ']');
print("\n\n\n\n\n\n\n\n\n");
*/
}
else
{
die('Unable to load a context...?');
}
?>
</pre>
<?php
require_once dirname(__FILE__) . '/views/footer.tpl.php';
SOLVED: Need to use Transaction Id of the Invoice instead of the Invoice Number.
This is almost certainly incorrect:
$LinkedTxn->setTxnId('10001'); //real invoice number in quickbooks
You should be using the Id value from the invoice in QuickBooks. The Id value is different from the user-visible Invoice reference # (the DocNumber field).
You need to use the Id value.
This also doesn't make a whole lot of sense:
$Line->setAmount(1);
...
$Payment->setTotalAmt(0.01);
How can the total payment amount be only 1 penny, and then you try to apply a full dollar to the invoice?
Using a httpSnooper tool(like fiddler) or by enabling the devkit logger, you should try to capture the raw request and response XML/JSON.
You can use the XML/JSON in ApiExplorer tool to debug this issue.
Otherwise, you can try to create a payment from QBO ui and retrieve the same using GetById endpoint. That way you can find out the correct structure of the payment object.
Hope it will useful.
Thanks

How do I use the twilio-php library to retrieve all calls made between two dates?

Using the following code I am able to get the logs of calls and SMS's. How do I modify this code to only search between certain dates using PHP?
// Instantiate a new Twilio Rest Client
$client = new Services_Twilio($AccountSid, $AuthToken, $ApiVersion);
// http://www.twilio.com/docs/quickstart...
try {
// Get Recent Calls
foreach ($client->account->calls as $call) {
echo "Call from $call->sid : $call->from to $call->to at $call->start_time of length $call->duration $call->price <br>";
}
}
catch (Exception $e) {
echo 'Error: ' . $e->getMessage();
}
You will want to add a code snippet that looks something like this:
$client = new Services_Twilio('AC123', '123');
foreach ($client->account->calls->getIterator(0, 50, array(
'StartTime>' => '2012-04-01',
'StartTime<' => '2012-05-01'
)) as $call) {
echo "From: {$call->from}\nTo: {$call->to}\nSid: {$call->sid}\n\n";
}
If you want to filter the list, you have to construct the iterator yourself with the getIterator command. There's more documentation here: Filtering Twilio Calls with PHP
User search terms StartTime> and StartTime< for this. First one means call start time is greater than and last one means call start time is less than.
To find every calls that started between 4th and 6th July of 2009 add search term
array(
'StartTime>' => '2009-07-04',
'StartTime<' => '2009-07-06'
)
See example 4 on the twilio doc.
Also note you can always ask twilio support. They usually help gladly.

Categories