Stripe get all customers list (example)
Fetching All Customers from Stripe: A Quick Tutorial Using Their API in Kotlin, Paginating batches of 100 until all customers are retrieved.
In this post we will share a quick tutorial on fetching all customers from Stripe using the Stripe API.
The problem
Stripe does not allow one to fetch all of one's customers in one go. Stripe returns customers in paginated lists. This means we must paginate through the list in a loop using a startingAfter
ID in batches of 100.
Code example
Here is an illustration of how to fetch all customers by paging through a list of customers from the Stripe API. It is written in Kotlin but you can apply the same logic in any programming language. We fetch batches of 100 customers and do so in a loop until a batch is returned and the hasMore
property is not true. This means we have fetched all the customers.
fun __getAllCustomers(): List<Customer> {
val allCustomers = mutableListOf<Customer>()
var count = 0
var lastId: String? = null
var hasMore: Boolean
do {
count++
val params = CustomerListParams.builder().apply {
setLimit(100L)
lastId?.let{ id -> setStartingAfter(id) }
}.build()
val req = Customer.list(params)
allCustomers.addAll(req.data)
hasMore = req.hasMore
lastId = req.data.lastOrNull()?.id
} while (hasMore && count < 1000)
return allCustomers
}