A PHP SDK for the Thinkific API implemented using Saloon
I wrote my original PHP library for Thinkific in ~2019 and since then there have been some major improvements in both PHP and libraries such as Saloon. With that in mind, I wanted to make the library more robust, strongly typed and easier to maintain. In addition, Saloon has inbuilt support for pagination and rate limiting, lowering technical overhead when dealing with high traffic integration scenarios.
Thinkific exposes both a REST Admin API and a GraphQL API. The GraphQL API does not replicate the complete functionality of the REST API, so this library supports both: REST for the full resource surface and GraphQL for the newer features (and anything only reachable there). The intention is to abstract the underlying API call, meaning as GraphQL matures, end points will be updated to use it where applicable with the confidence that the interface to PHP will remain the same.
Which API do you need? Community posts/replies, quizzes, surveys, assignments and teams are GraphQL only — see Data Model for the id conventions each API uses.
- This library requires PHP 8.2 and later
- The recommended way to install is using Composer
- This library is intended to speed up development time but is not a shortcut to reading the Thinkific documentation. Many endpoints require specific and required fields for successful operation. Always read the documentation before using an endpoint.
composer require mckltech/thinkific-saloon
The library makes extensive use of DTOs for entities such a Users, Courses, Products and Enrollments. Most endpoints return a DTO or a collection of DTOs. The DTOs are strongly typed and will throw exceptions if required fields are not present, in addition to the request failing if no DTO can be created.
When creating an entity, such as a User, or updating one, for example updating an enrollment, you will be required to pass a DTO. Again, these are strongly typed and will throw exceptions if required fields are not present.
Initialize your client using your access token:
$client = new \WooNinja\ThinkificSaloon\Services\ThinkificService( "XXXX428d55aabXXXXX68c0fXXXX", "example-school-123" );
- You can find your API Key by following the Thinkific API documentation: https://developers.thinkific.com/api/api-key-auth
- For your subdomain, do not include .thinkific.com. For example, if your subdomain is example.thinkific.com, then you would use 'example' in your ThinkificClient set up. If you are using a custom domain, you should retrieve your Thinkific sub-domain from your Thinkific dashboard.
The library permits the use of OAuth Access Tokens for API access, in addition to containing a helper method for refreshing. Note, the library does not implement the OAuth flow itself. I recommend using a standalone library for this e.g. Laravel Socialite
$client = new \WooNinja\ThinkificSaloon\Services\ThinkificService( "API Key OR OAuth Access Token", "example-school-123", true );
The library supports Thinkific's GraphQL stable API through ThinkificGraphQLService, with one resource service
per area: users, groups, courses, assignments, surveys, certificates, products, quizzes,
community, team, custom_roles, categories and bundles. Feel free to open a PR to add more, or request
them via issues.
Below is an example of interacting with the GraphQL API. Note the ThinkificGraphQLService class and the use of an
OAuth/private token. You cannot use an API Key with the GraphQL API.
use WooNinja\ThinkificSaloon\GraphQL\Services\ThinkificGraphQLService; $client = new ThinkificGraphQLService( "eyJrg0ZmY1O...." ); /** * Fetch all users on Site */ $users = $client->users->users(); foreach ($users->items() as $user) { /** * Fetch all groups for a user (via email) */ $groups = $client->users->groups($user->email); /** * Fetch all groups for user (via GID) */ $groups = $client->users->groups($user->gid); /** * Fetch the User by Email */ $theUser = $client->users->getByEmail($user->email); }
Thinkific's GraphQL API returns system and validation errors as HTTP 200 with a top-level errors array, and
rate-limits on a cost budget rather than a request count: 2000 points per minute, and no single request may
cost more than 1000 points. The connector treats any populated errors array as a failed request, so these
surface as exceptions instead of empty result sets:
| Exception | Thinkific code | Notes |
|---|---|---|
MaxQueryCostExceededException |
MAX_QUERY_COST_EXCEEDED |
getCost() / getMaxCost(). Not charged to the budget; shrink pages. |
GraphQLRateLimitedException |
RATE_LIMITED |
getResetAt() / getSecondsUntilReset(). Wait, then retry. |
GraphQLException |
anything else | getErrors(), getErrorCodes(), getRateLimit(). |
All three extend Saloon's RequestException (namespace WooNinja\ThinkificSaloon\GraphQL\Exceptions). Nested
connections multiply cost — e.g. quiz submissions with answers_per_page: 50 are rejected while the
per_page: 10, answers_per_page: 10 defaults are not — so size nested pages to the real question count and use the
hasMoreAnswers / answersEndCursor fields to drain overflow.
use WooNinja\ThinkificSaloon\GraphQL\Exceptions\MaxQueryCostExceededException; use WooNinja\ThinkificSaloon\GraphQL\Exceptions\GraphQLRateLimitedException; try { foreach ($client->quizzes->submissions($filter, per_page: 10, answers_per_page: 10)->items() as $submission) { // ... } } catch (MaxQueryCostExceededException $e) { // $e->getCost() > $e->getMaxCost(): reduce per_page / answers_per_page and re-run } catch (GraphQLRateLimitedException $e) { // sleep($e->getSecondsUntilReset()) and retry }
quizzes->definitions() returns a cursor-paginated list of quiz definitions (Site.quizzes →
questions → choices) and quizzes->allDefinitions() walks every page and returns them keyed by
quiz id, draining each quiz's truncated questions connection. There is no page cap: the walk
terminates on hasNextPage === false or a non-advancing cursor, so sites with thousands of quizzes
are read in full.
/* Paginated: yields QuizDefinition objects */ foreach ($client->quizzes->definitions()->items() as $quiz) { // ... } /* Assembled map: array<string, QuizDefinition>, questions drained per quiz */ $definitions = $client->quizzes->allDefinitions(); $quiz = $definitions['quiz_1'];
Cost: each request costs roughly 2 + ceil(per_page * questions_per_page * choices_per_page / 100)
points (25×25×15 measured 96 points — comfortably under the 1000-point single-request cap). The binding
limit is the 2000-points/minute budget, so size the nested pages to your needs. Choices are not
drained: a question with hasMoreChoices = true is surfaced on the DTO (with choicesEndCursor) for
the caller to treat as incomplete.
community is a read-only resource for exporting community posts and their replies:
communities(), community($id), spaces($community_id), posts($community_id, ...),
spacePosts($space_id, ...), post($id), replies($post_id, ...), thread($post_id, ...) and
postsWithReplies($community_id, ...); plus member discovery via members($community_id, ...),
searchableMembers($community_id, ..., $searchTerm), trendingPosts($community_id, ...) and
communityUser(...). There are no write operations.
Communities exist at Site.communities (there is no top-level list), and the post list queries
deliberately do not nest replies. Nesting a connection inside a paginated connection multiplies
cost, and Thinkific rejects any single request costing more than 1000 points (budget: 2000
points/minute), so replies are fetched separately per post:
/* Posts for a community (no replies; attachments bounded by $attachments_per_page) */ foreach ($client->community->posts('com_1', orderBy: ['field' => 'CREATED_AT', 'direction' => 'ASC'])->items() as $post) { // ... } /* One post with its first reply page ($post->hasMoreReplies / $post->repliesEndCursor flag overflow) */ $post = $client->community->post('post_1'); /* Recursively drain a post's reply tree, depth-first, up to $max_depth */ $thread = $client->community->thread('post_1', per_page: 25, max_depth: 3); /* Heavy export: every community post keyed by id, each with its thread attached */ $index = $client->community->postsWithReplies('com_1');
Cost caveat: thread() issues one request per post node plus one per truncated reply page and
postsWithReplies() runs a full thread() walk for every post, so both are request-heavy against
the per-minute budget — size per_page / replies_per_page / max_depth to the budget and run
large exports as a background job.
This library is unofficial and is not endorsed or supported by Thinkific.
For bugs and issues, open an issue in this repo and feel free to submit a PR. Any issues that do not contain full logs or explanations will be closed. We need you to help us help you!
use WooNinja\ThinkificSaloon\DataTransferObjects\Users\CreateUser; $client = new \WooNinja\ThinkificSaloon\Services\ThinkificService( "XXXX", "subdomain" ); /* Fetch all Users */ $users = $client->users->users(); /* Paginate through all users */ foreach ($users->items() as $user) { /* Fetch a single user */ $fetchedUser = $client->users->get($user->id); } /* Create a new User */ $newUser = new CreateUser( first_name: "John", last_name: "Doe", email: "[email protected]", password: null, skip_custom_fields_validation: true, send_welcome_email: true, custom_profile_fields: null, roles: null, bio: "An example bio for the new student", company: "WooNinja Software", headline: null, affiliate_code: null, affiliate_commission: null, affiliate_commission_type: null, affiliate_payout_email: null, external_id: null, provider: null ); $newUser = $client->users->create($newUser);
In general, the syntax for pagination is as follows:
$users = $client->users->users(); foreach ($users->items() as $user) { // Do something with the user }
To apply filters, supply them as an array. The following example, we are asking the API to return 2 results (Users) per page of results. We will start on Page 3 of the results, and we will iterate over a maximum of 4 pages. This will return 8 (2 Users x 4 Pages) results in total. It is recommend to limit your max_pages and work in batches for large result sets, as otherwise the system will iterate over all pages until the rate limit is reached.
$users = $client->users->users(['limit' => 2, 'max_pages' => 4, 'start_page' => 3]); foreach ($users->items() as $user) { // Do something with the user }
To determine page counts and total returned items, you can do the following. Assume this group has 23 users in it. Therefore there will be 3 pages of results (10, 10, 3), and the total number of results will be 23. This information can be used to avoid API timeouts e.g. Adjust job timing.
/** * Set a filter to return 50 users, starting from page one, and only one page of results. * We only retrieve one page of results as if we don't set a limit, the system will iterate over all pages until the rate limit is reached. */ $filter = ["limit" => 50, "max_pages" => 1, "start_page" => 1]; /** * Set up the API Call */ $users = $client->users->users($filter); /** * Make one API call so we can get the pagination data */ $firstAPICall = count($users); /** * Get the total number of users in the system */ $total_results = $users->getTotalAPIResults(); /** * Get the total number of pages of users in the system (based on the initial filter) */ $total_pages = $users->getTotalAPIPages(); /** * Iterate over the remaining pages (Useful for syncing large data sets via queued jobs etc) */ for($startPage = 2; $startPage <= $total_pages; $startPage++) { $filter['start_page'] = $startPage; $users = $client->users->users($filter); foreach($users->items() as $user) { // Do something with the users } }
Both paginators were exercised end-to-end against a real Thinkific site (REST:
339 users paginated at limit=3; GraphQL: 48 groups at first=5):
- REST –
limit/start_page/max_pagesbehave exactly as documented;getTotalAPIResults()andgetTotalAPIPages()reconcile with a full manualstart_pagewalk (339 = 339), a walk past the total stops early, andlimit > totalyields a single page. An empty collection returns 0 without looping. - GraphQL – cursor pagination is complete and duplicate-free: a full
first=5walk (10 pages) returns the same 48 ids as a singlefirst=100page, every page isfirstlong except the last,endCursoradvances on every page, and the final page reportshasNextPage = false. Note the GraphQL paginators take nomax_pagesargument — bound a walk with->setMaxPages(n).
Behaviours confirmed by running this SDK against a real Thinkific site (see also the notes in the Data Model section):
| Area | Behaviour |
|---|---|
Community.searchableMembers |
Requesting activatedAt / expiresAt makes the resolver return a server error — the SDK omits them for search results (use members() for those dates). |
Query.communityUser |
Requires an id or a userId; communityId alone errors, so the SDK throws InvalidArgumentException with a clear message. |
GET /users/{id}/authentications/{provider} |
provider accepts only SSO or OPENID_CONNECT; any other value is HTTP 400 "Invalid provider". |
GET /promotions/by_coupon |
Returns 404 when no promotion matches the product_id + coupon_code pair (data-dependent, not an SDK error). |
PUT /enrollments/{id} |
An omitted expiry_date keeps the current end date; only an explicit "expiry_date": null removes it (UpdateEnrollment::$clear_expiry_date). An omitted activated_at keeps the start date. Returns 204 either way. |
PUT /bundles/{id}/enrollments |
The opposite: an omitted expiry_date removes the end date, and an omitted activated_at sets it to null, on every course row. The write applies one set of dates to all rows immediately; a later course-level update to one row is not overwritten. |
GET /bundles/{id}/enrollments |
One row per course per user (ids match /enrollments); expired rows included by default. query[user_id], query[email] (exact, case-insensitive) and query[expired]=true|false work and combine. An empty query[email] is ignored and returns every user's rows. |
POST /users |
Returns 422 (e.g. "Job Title is required") when the site has a required custom profile field; pass it in custom_profile_fields. |
All endpoints follow a similar mechanism to the examples shown above. Again, please ensure you read the Thinkific API documentation prior to use as there are numerous required fields for most POST/PUT operations.
- Bundles
- Chapters
- Collections (categories and memberships)
- Contents
- Coupons
- Courses
- Course Reviews
- Custom Profile Field Definitions
- Enrollments
- External Orders (create / purchase / refund)
- Groups
- Instructors
- Orders
- Product Publish Requests (list / get / approve / deny)
- Products
- Promotions
- Site Scripts
- Users
- Webhooks
- OAuth Helper (Refresh Token Only)
This library speaks to two Thinkific APIs that share entities but use different ID conventions. Getting the IDs right is the single most common source of integration bugs, so both are documented here.
- REST Admin API v1 (
thinkific-rest-admin-api-v1.yaml): integer IDs, addressed in the path, e.g./courses/1264768. - GraphQL
stable([email protected]): every id comes back as a string. For users, courses and groups that string is the same numeric id as REST (verified live); users additionally expose agid— an opaque, non-numeric identifier (e.g.01EZZJCZHJR7W2H3Q8X6SQ4JFK), which is whatuser(gid:)expects. Community, space and post ids are numeric strings today but should be treated as opaque — pass them back verbatim.
Auth differs too. REST accepts an API key + subdomain or an OAuth token. GraphQL requires OAuth — an API key will not work there.
Two GraphQL rules, verified live. Every operation must be named (otherwise
UNNAMED_OPERATION) — the SDK already names every query and mutation. Andsite.quizSubmissionsscans the whole site, so an unfiltered (or loosely filtered) call can come back as aGATEWAY_TIMEOUT; always pass a narrowQuizSubmissionFilter(userIds/groupIds).Cap GraphQL walks explicitly. Unlike the REST paginator, the GraphQL paginators take no
max_pages; bound a walk with->setMaxPages(n). An uncappedusers()pulled all 339 users on a live site (~38s).REST and GraphQL are safe to use together. Their rate limiters are keyed separately (
{subdomain}:restvs{subdomain}:graphql), so sharing a store — or the same process — cannot let one API's usage starve the other.
| Object | ID | References (use these fields) |
|---|---|---|
| Product | id |
productable_id → Course.id or Bundle.id; productable_type = "Course"/"Bundle" |
| Course | id |
product_id → Product.id; chapter_ids[] → Chapter.id; instructor_id → Instructor.id; user_id → owner User.id |
| Bundle | id |
course_ids[] → Course.id |
| Chapter | id |
content_ids[] → Content.id |
| Content | id |
chapter_id → Chapter.id |
| Enrollment | id |
course_id → Course.id (== Product.productable_id, not Product.id); user_id → User.id |
| Group | id |
members via POST /group_users (user_ids, group_ids); analysts via POST /groups/{group_id}/analysts |
| Instructor | id |
user_id → User.id |
| Course Review | id |
course_id → Course.id; user_id → User.id |
| Coupon | id |
promotion_id → Promotion.id |
| Promotion | id |
product_ids[] → Product.id; coupon_ids[] → Coupon.id |
| Order | id |
product_id → Product.id; user_id → User.id; coupon_id → Coupon.id |
| Custom Profile Field | id |
custom_profile_field_definition_id → definition id |
| Site Script | id (string) |
— |
The classic gotcha — enrolments. An Enrollment.course_id is the Course
id, which is the same value as Product.productable_id — not Product.id:
$product = $client->products->get($productId); // Product.id $enrollment = $client->enrollments->create(new CreateEnrollment( user_id: $user->id, course_id: $product->productable_id, // == Course.id, NOT Product.id activated_at: null, expiry_date: null, ));
For a bundle, the productable_id is the Bundle id: list its courses with
$client->bundles->courses($product->productable_id) and enrol at bundle level
with $client->bundles->createEnrollment(new CreateBundleEnrollment( productable_id: $product->productable_id, ...)).
Enrollment dates: course vs bundle endpoints. These were verified against the live API and differ:
PUT /enrollments/{id} (enrollments->update()) |
PUT /bundles/{id}/enrollments (bundles->updateEnrollment()) |
|
|---|---|---|
expiry_date null |
Keeps the current end date. Set clear_expiry_date: true to remove it |
Removes the end date on every course row |
activated_at null |
Keeps the current start date | Clears the start date on every course row |
- A bundle enrollment is one ordinary course enrollment per course, with the same ids as in
/enrollments. A bundle write gives every row the same dates, immediately. For per-course dates, follow it with a course-levelenrollments->update(), which sticks. bundles->enrollments()includes expired rows by default. Filter withquery[user_id],query[email]andquery[expired](trueorfalse); the filters combine.query[email]needs the exact email (case-insensitive). An emptyquery[email]is ignored and returns every user's rows, so the SDK's user helpers throwInvalidArgumentExceptionfor an empty email instead of sending the request.bundles->isUserEnrolled()is true only when the user has rows and every row is active.hasActiveEnrollment()checks for at least one active row, andhasAnyEnrollment()for any row, expired or not.bundles->expireEnrollment()clearsactivated_aton every course row of the bundle.
| Object | Key fields | Notes |
|---|---|---|
| User | id, gid, email |
user(gid:) takes the opaque gid (not a numeric id); userByEmail(email:) takes the email. id == REST User.id |
| Course | id, slug |
course(id:) / courseBySlug(slug:). id == REST Course.id |
| Product | id, itemId / productableId, itemType / productableType, item |
itemId === REST Product.productable_id; item is the linked Course/Bundle |
| Group | id, name, users |
group(id:). id == REST Group.id |
| Community | id, slug, posts, spaces, members |
site.communities lists them; id is a numeric string (treat as opaque) |
| Space | id, community, posts |
space(id:); id is a numeric string (treat as opaque) |
| Post | id, author (User), replies (PostConnection), depth, replyCount |
replies are themselves Posts — depth marks nesting; author may be null; id is a numeric string (treat as opaque) |
| CertificateRecord | id, issuedId (= credential id), user, course |
issuedId is the credential string the SDK surfaces as Certificate::$credential_id |
| Assignment submission | id, user |
course/chapter/lesson via assignment.lesson.chapter.course.product |
| Quiz submission | id, quiz { id }, user |
— |
Casing differs between the APIs. REST returns
productable_typeas"Course", while GraphQL returns the equivalentitemType/productableTypeas"COURSE".
| Task | Use |
|---|---|
| Enrol a user in a course | REST Course.id == Product.productable_id (never Product.id) |
| Enrol a user in a bundle | the Bundle's productable_id |
| Fetch a user (GraphQL) | User.gid for user(gid:), or the email for userByEmail(email:) |
| Relate a GraphQL product to its course | Product.itemId (== REST Product.productable_id) |
| Cross-reference the two APIs | Course.id, User.id, Group.id are the same numeric value in REST and GraphQL (verified live) |
| Community post / reply / space | the opaque ID returned by GraphQL, passed straight back |
The Thinkific REST API uses a number of different IDs to link Courses, Products and Enrollments. Products, at time of writing, can either be Courses or Bundles.
Given an Enrollment:
{
"id": 479110111,
"created_at": "2024-02-22T20:32:52.726Z",
"user_email": "[email protected]",
"user_name": "Colin",
"expiry_date": "2025-01-17T20:32:52.000Z",
"user_id": 193952525,
"course_name": "Corporate Course",
"course_id": 1264768, <-- The productable_id in /products and id in /courses
"percentage_completed": "0.0",
"completed_at": null,
"expired": false,
"is_free_trial": false,
"completed": false,
"started_at": null,
"activated_at": "2024-02-22T20:32:52.000Z",
"updated_at": "2024-02-22T20:32:52.730Z"
}
You can relate this Enrollment to a Product:
{
"id": 1325780, <-- The product_id in /courses
"created_at": "2021-03-04T21:30:50.243Z",
"productable_id": 1264768 <- The course_id in /enrollments & the id in /courses
"productable_type": "Course",
"price": "1.0",
"position": 13,
"status": "published",
"name": "Corporate Course",
"private": false,
"hidden": false,
"subscription": false,
"days_until_expiry": null,
"has_certificate": false,
"collection_ids": [],
"seo_title": null,
"seo_description": null,
"keywords": null,
"related_product_ids": [],
"slug": "your-first-course",
"description": "Lorem ipsum dolor sit amet, consectetur adipisici elit, sed eiusmod tempor incidunt ut labore et dolore magna aliqua. Unam incolunt Belgae, aliam Aquitani, tertiam. Cras mattis iudicium purus sit amet fermentum.",
...
}
Which, in turn, can be related to a Course:
{
"id": 1264768, <-- The productable_id in /products and course_id in /enrollments
"name": "Corporate Course",
"slug": "your-first-course",
"subtitle": null,
"product_id": 1325780, <- The id in /products
"description": "Lorem ipsum dolor sit amet, consectetur adipisici elit, sed eiusmod tempor incidunt ut labore et dolore magna aliqua. Unam incolunt Belgae, aliam Aquitani, tertiam. Cras mattis iudicium purus sit amet fermentum.",
"intro_video_youtube": null,
"contact_information": null,
"keywords": null,
"duration": null,
...
}
For a Bundle, they can be listed via an API request to:
e.g. https://api.thinkific.com/api/public/v1/bundles/120008
Where '120008' is the productable_id from a Product
Which returns:
{
"id": 120008, <-- The productable_id in /products
"name": "Demo Bundle",
"description": null,
"banner_image_url": "/assets/tenant/default-course-banner.jpg",
"course_ids": [
1264768, <-- The productable_id in /products and id in /courses
],
"bundle_card_image_url": "/assets/defaults/default-product-card.png",
"tagline": null,
"slug": "demo-bundle"
}
When creating and updating enrollments, the productable_id from a Product should be used.
As a worked example of iteration, we can query the API for all products, and then determine the Course(s) associated with each Product:
$products = $client->products->products(); foreach ($products->items() as $product) { /** * Not required to if/else here but we'll use it to highlight the alternative method * of retrieving the course associated with a product */ if ($product->productable_type == "Course") { /** * We could also query the course directly: * * Note the use of 'productable_id' when querying the course end point */ //$courses = $client->courses->get($product->productable_id); /** * And here we will use the products service to retrieve the course * Note the use of the Product 'ID' */ $courses = $client->products->courses($product->id); } else { /** * Bundles */ $courses = $client->products->courses($product->id); } /** * $courses is an array of Course objects */ }
- Helper methods e.g. find() and findByEmail() in User endpoints
- WordPressRateLimitStore for Rate Limiting in WordPress Environments (Uses WP Transients)
- MapperTrait to transfer between DTOs e.g. CreateUser -> UpdateUser
Exceptions are handled by Saloon. Most end points for retrieving data will either return a DTO (or collection of DTOs) or fail. Further docs here: https://docs.saloon.dev/the-basics/handling-failures
The layout and methodology used in this library was inspired by Ash Allen from https://battle-ready-laravel.com/