Stripe API: List all Charges - php

I am using https://stripe.com/docs/api?lang=php#list_charges to get List all Charges but here they specify
count optional — default is 10 A limit on the number of objects to be
returned. Count can range between 1 and 100 items.
and I have thousands of entries, now how can I get all. Though if I set count to 100 it returns 110 records.

You can use the offset argument.
Once you get the 100 transactions, then make another call by adding offset=100 in URL.
This will bring the next 100 transactions, then make offset=200 and so on.
Update:
offset parameter is partly deprecated: API changelog - 2015-09-23

$charges = \Stripe\Charge::all();
foreach ($charges->autoPagingIterator() as $charge) {
// Do something with $charge
}
Reference.

Yes I got it with offset we can get all records.

Here's a PHP example: \Stripe\Charge::all(array("limit" => 3, "offset" => 10));
A Ruby example:
Stripe::Charge.all(limit: 3, offset:3)
As good as the Stripe API docs are, they could be clearer on how to filter.
source: https://stripe.com/docs/api/php#list_charges, https://stripe.com/docs/api/ruby#list_charges

in case offset is deprecated
$result = [];
$created_at = strtotime($request->end_data);
//created_at should be today's date epoch. search google for epoch
$has_more = false;
$a = 0;
do{
print_r($a);
\Stripe\Stripe::setApiKey(env('STRIPE_SECRET'));
$temp = \Stripe\BalanceTransaction::all( array(
'limit' => 100,
'created' => array(
'lte' => $created_at,
)
));
$result = array_merge($temp->data,$result);
$created_at = $temp->data[99]->created_at;
//api returns a parameter has_more(boolean), which means there is more
//data or not so you can also put that in while condition, for ex.
// $has_more = $temp->has_more;
$a++;
}while($a < 5);
dd($result);
this worked for me i was able to get 500 records at once as $a < 5 the api hits 5 times and each time created parameter which is lte (less than equal) changes for each api request and return previous records than current request provide. also i am appending the result of each api call to another result array

Unfortunately you can't.
I can see where such a feature would be nice for accounting purposes or whatever, but it's generally a better user experience to implement some sort of paging when displaying copious amounts of data to the user.
If you need absolute control over how many records to display at a time, I would suggest setting up a webhook on the charge.succeeded event and store your charges locally.

Related

Google Cloud Storage paginate objects in a bucket (PHP)

I want to iterate over the objects in a bucket. I REALLY need to paginate this - we have 100's of thousands of objects in the bucket. Our bucket looks like:
bucket/MLS ID/file 1
bucket/MLS ID/file 2
bucket/MLS ID/file 3
... etc
Simplest version of my code follows. I know the value I'm setting into $params['nextToken'] is wrong, I can't figure out how or where to get the right one. $file_objects is a 'Google\Cloud\Storage\ObjectIterator', right?
// temp: pages of 10, out of a total of 100. I really want pages of 100
// out of all (in my test bucket, I have about 700 objects)
$params = [
'prefix' => $mls_id,
'maxResults' => 10,
'resultLimit' => 100,
'fields' => 'items/id,items/name,items/updated,nextPageToken',
'pageToken' => NULL
];
while ( $file_objects = $bucket->objects($params) )
{
foreach ( $file_objects as $object )
{
print "NAME: {$object->name()}\n";
}
// I think that this might need to be encoded somehow?
// or how do I get the requested nextPageToken???
$params['pageToken'] = $file_objects->nextResultToken();
}
So - I don't understand maxResults vs resultLimit. It would seem that resultLimit would be the total that I want to see from my bucket, and maxResults the size of my page. But maxResults doesn't seem to affect anything, while resultLimit does.
maxResults = 100
resultLimit = 10
produces 10 objects.
maxResults = 10
resultLimit = 100
spits out 100 objects.
maxResults = 10
resultLimit = 0
dumps out all 702 in the bucket, with maxResults having no effect at all. And at no point does "$file_objects->nextResultToken();" give me anything.
What am I missing?
The objects method automatically handles pagination for you. It returns an ObjectIterator object.
The resultLimit parameter limits the total number of objects to return across all pages. The maxResults parameter sets the maximum number to return per page.
If you use a foreach over the ObjectIterator object, it'll iterate through all objects, but note that there are also other methods in ObjectIterator, like iterateByPage.
Ok, I think I got it. I found the documentation far too sparse and misleading. The code I came up with:
$params = [
'prefix' => <my prefix here>,
'maxResults' => 100,
//'resultLimit' => 0,
'fields' => 'items/id,items/name,items/updated,nextPageToken',
'pageToken' => NULL
];
// Note: setting 'resultLimit' to 0 does not work, I found the
// docs misleading. If you want all results, don't set it at all
// Get the first set of objects per those parameters
$object_iterator = $bucket->objects($params);
// in order to get the next_result_token, I had to get the current
// object first. If you don't, nextResultToken() always returns
// NULL
$current = $object_iterator->current();
$next_result_token = $object_iterator->nextResultToken();
while ($next_result_token)
{
$object_page_iterator = $object_iterator->iterateByPage();
foreach ($object_page_iterator->current() as $file_object )
{
print " -- {$file_object->name()}\n";
}
// here is where you use the page token retrieved earlier - get
// a new set of objects
$params['pageToken'] = $next_result_token;
$object_iterator = $bucket->objects($params);
// Once again, get the current object before trying to get the
// next result token
$current = $object_iterator->current();
$next_result_token = $object_iterator->nextResultToken();
print "NEXT RESULT TOKEN: {$next_result_token}\n";
}
This seems to work for me, so now I can get to the actual problem. Hope this helps someone.

I want to fetch all API data from data.gov.in it is only fetching 10 data

I'm using data.gov.in dataset API with the following link,
https://api.data.gov.in/resource/9ef84268-d588-465a-a308-a864a43d0070?api-key=579b464db66ec23bdd000001cdd3946e44ce4aad7209ff7b23ac571b&format=json&offset=0
This link is only fetching 10 records I've tried to add a limit parameter at the end of the link but it is still not showing all records.
You are using sample api key. Register using your email and phone number and get your api key. You can get as many result you wish.
You'll need to call the function repeatedly, specifying a new offset each time. It looks like this particular API will only return a maximum of 10 records.
If you try setting the limit parameter to 5, for example it works but with 10 or greater you will only get 10 records.
e.g.
https://api.data.gov.in/resource/386ce542-8e39-4c4c-98e0-ddc28c2b5c56?api-key=579b464db66ec23bdd000001cdd3946e44ce4aad7209ff7b23ac571b&format=json&offset=1&limit=5
If you call the API repeatedly, increasing offset each time (e.g. +1), you'll get a list of records 10 at a time.
e.g.
function getData(offset,limit) {
fetch('https://api.data.gov.in/resource/386ce542-8e39-4c4c-98e0-ddc28c2b5c56?api-key=579b464db66ec23bdd000001cdd3946e44ce4aad7209ff7b23ac571b&format=json&offset=' + offset + '&limit=' + limit).then(response => {
return response.json();
}).then(json => {
console.log(`Data length from offset #${offset}: `, JSON.stringify(json).length);
});
}
// Call for a few offsets.
let offsets = [0,1,2,3,4];
offsets.forEach(offset => getData(offset, 10));
If you are using python then here is the code other wise the concept is to first get the data count which the API key returns itself if you run this code
Note: Use your own API key which you can get by registering to the data.gov.in and put it in place of < YOUR API KEY HERE >
import requests
response = requests.get('https://api.data.gov.in/resource/3b01bcb8-0b14-4abf-b6f2-c1bfd384ba69?api-key=< YOUR API KEY HERE >&format=json&limit=1')
data = eval(response.text)
total_count = eval(response.text)['total']
then pass the total_count as variable in again in new response:
new_response = requests.get('https://api.data.gov.in/resource/3b01bcb8-0b14-4abf-b6f2-c1bfd384ba69?api-key=< YOUR API KEY HERE >&format=json&limit=%s'%total_count)
new_data = eval(new_response.text)
print (len(new_data['records']))
print (new_data['total'])

Get Individual phone number outbound sms usage/ logs

I am trying to get outbound sms logs against each individual phone number configured in twilio sub-account. I am using PHP programming language and looked into the api console:
https://www.twilio.com/docs/api/rest/usage-records
But according to my exploration, usage-record api only returns total usage information against my twilio account. i.e. 500 outbound sms against all the three subscribed numbers in my account say N1, N2 and N3. What I want here is to retrieve the number of sms sent and received individually against each number N1, N2 and N3. Please help me in this regard.
Thanks
I have already did like this.
$sub_acc = $client->accounts->get($sub_account->sid);
$numbers = $sub_acc->incoming_phone_numbers;
$phone_sms_count = array();
foreach ($numbers as $number) {
$sms_count = 0;
foreach ($sub_acc->messages->getIterator(0, 50, array(
"From" => $number->phone_number,
"DateSent" => $last_six_months_date)) as $sms)
{
$sms_count++;
}
$phone_sms_count[$number->phone_number] = $sms_count;
}
But it takes too much time to calculate sms counts for each number. I have configured 5 numbers in single subaccount and I have 10 subaccounts
this will break the limits.
Is there any way to get sms counts for each phone number without iterating messages?
I'm not sure why you received downvotes but to me the question is legit so I'll try to help.
You can use the Message API List Resource. Just filter the date range and from phone number. So to get records for last month (May 2016) just filter like:
// Set options
$from_number="XXXXXXXXXX";
$start_date="2016-05-01";
$end_date="2016-05-31";
// Build the option array
$get_iterator_options = array(
'from' => $from_number,
'DateSent' => $start_date,
'DateSent' => $end_date
);
// Make the call with our options
foreach ($client->account->message->getIterator(
0,
50,
$get_iterator_options
) as $message
) {
$msg_ids[] = $message->sid; //
}
echo count($msg_ids);
Twilio provides a List Resource for Messages, Calls, Recordings, etc..
Keep in mind this is almost certainly slower than what you were trying to do originally especially if there are a lot of messages.
You can create a subaccount for each subscribed number (documentation). You can then retrieve total usage per subaccount.

How to get more than 10 events for Outlook calendar API?

I've modified the official PHP example to get more than 10 calendar events
Here is the original OData query:
$getEventsParameters = array (
// Only return Subject, Start, and End fields
"\$select" => "Subject,Start,End,Location,Attendees,Organizer",
// Sort by Start, oldest first
"\$orderby" => "Start/DateTime",
// Return at most 10 results
"\$top" => "10"
);
I changed into:
$getEventsParameters = array (
// Only return Subject, Start, and End fields
"\$select" => "Subject,Start,End,Location,Attendees,Organizer",
// Sort by Start, oldest first
"\$orderby" => "Start/DateTime"
);
But I'm still only getting 10 events returned. Why?
10 is the default page size. To get more, put the $top parameter back in and increase it. The maximum is 50.
Since April 2017, the maximum is 1000 see Microsoft Blog

FB Ads API (#17) User request limit reached

I am working on Facebook ads api to get the account Campaign data.What I am doing here is I get list of all campaigns and doing forloop of each campaign get Campaign stat
$campaignSets = $account->getCampaigns(array(
CampaignFields::ID,
CampaignFields::NAME
));
foreach ($campaignSets as $campaign) {
$campaign = new Campaign($campaign->id);
$fields = array(
InsightsFields::CAMPAIGN_NAME,
InsightsFields::IMPRESSIONS,
InsightsFields::UNIQUE_CLICKS,
InsightsFields::REACH,
InsightsFields::SPEND,
InsightsFields::TOTAL_ACTIONS,
InsightsFields::TOTAL_ACTION_VALUE
);
$params = array(
'date_preset' => InsightsPresets::TODAY
);
$insights = $campaign->getInsights($fields, $params);
}
when executing above code I am getting error as (#17) User request limit reached.
Can anyone help me how to solve this kind of error?
Thanks,
Ronak Shah
You should consider generating a single report against the adaccount which returns insights for all of your campaigns, this should reduce the number of requests required significantly.
Cursor::setDefaultUseImplicitFetch(true);
$account = new AdAccount($account_id);
$fields = array(
InsightsFields::CAMPAIGN_NAME,
InsightsFields::CAMPAIGN_ID,
InsightsFields::IMPRESSIONS,
InsightsFields::UNIQUE_CLICKS,
InsightsFields::REACH,
InsightsFields::SPEND,
InsightsFields::TOTAL_ACTIONS,
InsightsFields::TOTAL_ACTION_VALUE,
);
$params = array(
'date_preset' => InsightsPresets::TODAY,
'level' => 'ad',
'limit' => 1000,
);
$insights = $account->getInsights($fields, $params);
foreach($insights as $i) {
echo $i->campaign_id.PHP_EOL;
}
If you run into API limits, your only option is to reduce calls. You can do this easily by delaying API calls. I assume you are already using a Cron Job, so implement a counter that stores the last campaign you have requested the data for. When the Cron Job runs again, request the data of the next 1-x campaign data (you have to test how many are possible per Cron Job call) and store the last one again.
Also, you should batch the API calls - it will not avoid limits, but it will be a lot faster. As fast as the slowest API call in the batch.
Add this to your code and you'll never have to worry about FB's Rate Limiting/User Limit Reached.
Your script will automatically sleep as soon as you approach the limit, and then pick up from where it left after the cool down. Enjoy :)
import logging
import requests as rq
#Function to find the string between two strings or characters
def find_between( s, first, last ):
try:
start = s.index( first ) + len( first )
end = s.index( last, start )
return s[start:end]
except ValueError:
return ""
#Function to check how close you are to the FB Rate Limit
def check_limit():
check=rq.get('https://graph.facebook.com/v3.3/act_'+account_number+'/insights?access_token='+my_access_token)
call=float(find_between(check.headers['x-business-use-case-usage'],'call_count":','}'))
cpu=float(find_between(check.headers['x-business-use-case-usage'],'total_cputime":','}'))
total=float(find_between(check.headers['x-business-use-case-usage'],'total_time":',','))
usage=max(call,cpu,total)
return usage
#Check if you reached 75% of the limit, if yes then back-off for 5 minutes (put this chunk in your loop, every 200-500 iterations)
if (check_limit()>75):
print('75% Rate Limit Reached. Cooling Time 5 Minutes.')
logging.debug('75% Rate Limit Reached. Cooling Time 5 Minutes.')
time.sleep(300)

Categories