Sign in with Leanpub
Sign in with Leanpub lets a partner site sell its customers a Leanpub book alongside its own products. The buyer signs in with their Leanpub account, you check which of your Leanpub books they already own, and you send them to a short Leanpub checkout for the ones they don't. The book lands in their Leanpub library, and you confirm the outcome from your server.
This guide is for the partner's developer. It covers the whole integration: signing in, the ownership check, the checkout, the return to your site, and the sandbox on staging.
It is a standard OAuth 2.0 authorization code flow with PKCE (S256), one scope, and no refresh tokens. If you have built "Sign in with Google" or a similar server-side integration, nothing here will surprise you.
Before you start
A Leanpub admin registers your site as a client. Send us:
- your redirect URIs: where Leanpub sends the buyer back after they sign in (for example
https://example.com/leanpub/callback); - your checkout return URIs: where Leanpub sends the buyer back after a checkout (for example
https://example.com/leanpub/return); - the Leanpub books you want to sell (their slugs), which must be books your Leanpub author account is an accepted author of;
- any coupon codes of yours you want to use for those books.
Every URI must be https, with no wildcard, fragment, username or password. Leanpub compares what you send with what is registered byte for byte: a trailing slash, a different case or an extra query parameter counts as a different URI and is refused.
You receive a client_id (it starts lpc_) and a client_secret. The secret is shown once. Keep it on your server, never in a browser, an app or a repository. If it leaks, ask us to rotate it: the old secret stops working the moment the new one is issued, so put the new one in place as soon as you receive it.
We issue staging credentials first, so you can build against the sandbox (see "The sandbox" below) before you go live.
| Production | Staging (sandbox) | |
|---|---|---|
| Host | https://leanpub.com | https://staging.leanpub.com |
| Credentials | production client | staging client |
Use the staging host and credentials everywhere this guide says leanpub.com while you test.
1. Sign the buyer in
For each sign-in, generate on your server:
- a
code_verifier: 43 to 128 characters fromA-Z a-z 0-9 - . _ ~(32 random bytes, base64url-encoded, is 43 characters); - its
code_challenge:base64url(sha256(code_verifier)), without padding; - a random
stateof up to 512 characters.
Store the verifier and the state in the buyer's session on your site, then send the buyer's browser to Leanpub with a top-level redirect: a link or an HTTP redirect, never a form POST, an iframe or a popup.
https://leanpub.com/oauth/authorize
?response_type=code
&client_id=YOUR_CLIENT_ID
&redirect_uri=https%3A%2F%2Fexample.com%2Fleanpub%2Fcallback
&scope=owns%3Aclient_products
&state=YOUR_STATE
&code_challenge=YOUR_CODE_CHALLENGE
&code_challenge_method=S256
Leanpub asks the buyer to sign in (or create an account), shows them your site's name and the books you sell, and asks them to approve. They see which Leanpub account they are using and can switch.
The callback
When the buyer approves, Leanpub sends them to your redirect URI:
https://example.com/leanpub/callback?code=AUTHORIZATION_CODE&state=YOUR_STATE
Check that state equals the one in the buyer's session before doing anything else, then exchange the code (step 2). The code works once, and only for 60 seconds.
If the callback arrives in a browser that has no session with that state, the buyer has most likely opened Leanpub's sign-in email on another device. Show them a message asking them to finish on the device they started on, rather than an error.
If the buyer declines, or the request can't be accepted, you get an error instead of a code, with your state:
error | Meaning |
|---|---|
access_denied | The buyer chose not to approve. |
invalid_request | A parameter is missing or malformed (for example the code_challenge, the code_challenge_method, or a state over 512 characters). |
unsupported_response_type | response_type was not code. |
invalid_scope | scope was not owns:client_products. |
An unknown client_id, or a redirect_uri that isn't registered, is never redirected anywhere: Leanpub shows the buyer an error page. Check your client id and URIs if a buyer reports one.
2. Exchange the code for an access token
From your server, within 60 seconds of the callback:
curl -X POST https://leanpub.com/api/oauth/token \
-u "YOUR_CLIENT_ID:YOUR_CLIENT_SECRET" \
-d grant_type=authorization_code \
-d code=AUTHORIZATION_CODE \
-d redirect_uri=https://example.com/leanpub/callback \
-d code_verifier=YOUR_CODE_VERIFIER
Authenticate with HTTP Basic (as above), or send client_id and client_secret in the form body instead, but not both. Never put them in the query string. The redirect_uri must be the same one you sent to the authorize URL.
Response:
{
"access_token": "lpat_...",
"token_type": "Bearer",
"expires_in": 900,
"scope": "owns:client_products"
}
The access token lasts 15 minutes and there is no refresh token. Use it for the ownership check and to create checkouts straight away. A 401 invalid_token later means it has expired: send the buyer through sign-in again rather than retrying.
| Status | error | Meaning |
|---|---|---|
| 401 | invalid_client | Unknown client, wrong secret, or the client has been revoked. |
| 400 | invalid_grant | The code is unknown, expired or already used; the redirect_uri or code_verifier doesn't match; or the account can't be used. |
| 400 | unsupported_grant_type | grant_type was not authorization_code. |
| 400 | invalid_request | A parameter is missing, or credentials were sent both ways. |
A code is single-use. If the same code is exchanged a second time, Leanpub treats it as stolen and revokes the access token the first exchange produced.
3. Check which books the buyer owns
curl https://leanpub.com/api/oauth/owned_products \
-H "Authorization: Bearer ACCESS_TOKEN"
Response:
{
"sub": "f3a9c2...",
"products": [
{ "slug": "your-first-book", "title": "Your First Book", "owned": true },
{ "slug": "your-second-book", "title": "Your Second Book", "owned": false }
],
"checked_at": "2026-11-09T18:02:11Z"
}
productslists only the books registered for your client, owned or not. It answers for nothing else.subidentifies this Leanpub account to your site. It is the same every time the same buyer signs in with your client, and it means nothing to any other site. Store it against your customer. Leanpub never sends you the buyer's email address, name or username.- Ownership is by Leanpub account. A buyer who owns the book through another Leanpub account will show
"owned": false.
Remove owned books from your cart. For the others, create a checkout.
4. Create a checkout
Create it right after the ownership check, while the access token is fresh. A checkout costs nothing until the buyer opens it, and it lasts 24 hours, so you can create it before the buyer has finished the rest of your checkout.
curl -X POST https://leanpub.com/api/oauth/checkouts \
-H "Authorization: Bearer ACCESS_TOKEN" \
-H "Content-Type: application/json" \
-d '{
"product_slug": "your-second-book",
"coupon_code": "YOUR_COUPON",
"return_uri": "https://example.com/leanpub/return",
"cancel_uri": "https://example.com/leanpub/return",
"state": "cart_8812"
}'
product_slug: one of your registered books.coupon_code(optional): one of your registered coupons for that book. The buyer never sees the code; Leanpub shows the discount as yours.return_uriandcancel_uri: each one of your registered checkout return URIs. They may be the same.state(optional): up to 512 characters of your own, handed back to you on the return.
Send these fields in the JSON body (or a form body), never in the query string: a create with any of them in the query string is refused with invalid_request.
You can't set the price. Leanpub works it out from the book's pricing and your coupon, and ignores any amount, price or currency you send.
Response (201 Created):
{
"checkout_id": "lpck_...",
"status": "not_owned",
"checkout_url": "https://leanpub.com/oauth/checkout/lpck_...",
"minimum_price": "9.99",
"suggested_price": "14.99",
"coupon_price": "4.99",
"currency": "USD",
"expires_at": "2026-11-10T18:02:11Z"
}
Prices are US dollars, as strings. Without a coupon the buyer chooses what to pay, from minimum_price up, with suggested_price (never below minimum_price) as the default: show something like "from $9.99". With a coupon, coupon_price is the price. Store the checkout_id.
If your coupon makes the book free, there is nothing to pay and no checkout page: the call adds the book to the buyer's Leanpub library at once (the buyer agreed to that when they approved your sign-in) and answers, with no checkout_url:
{ "checkout_id": "lpck_...", "status": "owned", "library_url": "https://leanpub.com/library" }
Show success, with a link to library_url. The status call (step 7) answers owned, with amount "0.00" and payment_method free, and creating another checkout of the book answers already_owned.
If the buyer already owns the book, no checkout is created:
{ "status": "already_owned", "library_url": "https://leanpub.com/library" }
| Status | error | Meaning |
|---|---|---|
| 422 | unknown_product | The book isn't registered for your client. |
| 422 | product_not_for_sale | The book is no longer for sale (for example it was unpublished). |
| 422 | invalid_coupon | The coupon isn't registered for your client and this book, or it isn't valid for this buyer now (suspended, expired or ending within the checkout's lifetime, limited to a number of uses, or with conditions the buyer doesn't meet). |
| 422 | invalid_return_uri | return_uri or cancel_uri isn't a registered checkout return URI. |
| 422 | state_too_long | state is over 512 characters. |
| 422 | purchase_refused | Leanpub can't sell to this buyer. No detail is given. |
| 422 | claim_failed | Free checkouts only: the buyer has a guest copy of the book that couldn't be added to their account, so Leanpub didn't add another copy. They can add their guest purchases from their Leanpub account. |
| 422 | order_invalid | Free checkouts only: the book couldn't be added to the buyer's library. Try again later. |
| 409 | checkout_in_progress | The buyer already has a checkout for this book open, or one they have paid for that isn't finished yet (pending). Wait for it to finish or expire, or, if they haven't paid, send the buyer to that checkout's checkout_url, where they can cancel it, and then create a new one. |
| 400 | invalid_request | A field is not a string, or a field (product_slug, coupon_code, return_uri, cancel_uri or state) was sent in the query string instead of the body. |
| 401 | invalid_token | The access token has expired or been revoked: sign the buyer in again. |
5. Send the buyer to the checkout
When you're ready, send the buyer to checkout_url by top-level navigation: a link or a redirect, never an iframe, a popup or a POST.
The buyer must be signed in to Leanpub as the account they approved with; if they aren't, Leanpub asks them to sign in, or to switch account. They see the book, choose a price (or get your coupon price), and pay by card or PayPal. A free checkout has no checkout page: the create call (step 4) already added the book to their library.
6. Handle the return
When the buyer has paid (or turns out to own the book already), Leanpub sends them to your return_uri; when they cancel, or the checkout expires unpaid, to your cancel_uri. Either way it adds two parameters:
https://example.com/leanpub/return?lp_checkout_id=lpck_...&lp_state=cart_8812
That is all the return carries: no status, no amount. The browser redirect proves nothing, because anyone can type that URL. Match lp_state to your own record, then ask Leanpub for the status (step 7) before you show the buyer any outcome.
7. Confirm the outcome
From your server, with your client credentials:
curl https://leanpub.com/api/oauth/checkouts/lpck_... \
-u "YOUR_CLIENT_ID:YOUR_CLIENT_SECRET"
Response:
{
"checkout_id": "lpck_...",
"status": "owned",
"amount": "9.99",
"currency": "USD",
"payment_method": "stripe",
"completed_at": "2026-11-09T18:09:40Z",
"refunded_at": null,
"cancel_reason": null,
"state": "cart_8812"
}
This call is the contract: it always answers the current truth, and you can call it as often as you need.
status | Meaning | What to do |
|---|---|---|
owned | The buyer owns the book. | Show success, with a link to https://leanpub.com/library. |
pending | Payment was taken and the purchase is being completed. | Check again in a minute. If it stays pending, Leanpub support is on it. |
not_owned | Anything else: the buyer hasn't paid (yet), cancelled, let the checkout expire, or was refunded. | Treat as not bought. |
The other fields tell you more:
amountis what the buyer was charged, in US dollars, tax included, once they have paid;currencyis thenUSD.payment_methodisstripeorpaypalonce the buyer has chosen, orfreewhen your coupon made the book free.completed_atis when the purchase was made, once the buyer owns the book (and still after a refund).refunded_atis when the purchase was refunded.cancel_reasonis set once the buyer cancelled:buyer,already_owned(they turned out to own it) orclaim_failed.
A buyer who paid and closed the tab before returning still shows owned the next time you check, and a buyer who cancelled and then paid anyway shows owned, beside the cancel_reason.
A checkout the buyer opened but didn't pay for can be paid for 40 minutes after they opened it, and while it can, you can't create another checkout of the same book for the buyer, so they can't pay twice. Cancelling it from the checkout page ends it straight away, unless the buyer has already paid: then it isn't cancelled, the buyer comes back to your return_uri, and the checkout turns pending, then owned. A checkout that is pending also blocks another checkout of the same book, however long ago it was opened, until the buyer owns the book or is refunded. If a payment ever reaches Leanpub after those 40 minutes (a long outage at the payment provider), the checkout turns owned, and Leanpub support refunds a second copy the buyer paid for.
Refunds: there is no webhook yet. To learn about refunds, check the status of recent owned checkouts from time to time and look for not_owned with a refunded_at.
| Status | error | Meaning |
|---|---|---|
| 404 | not_found | No such checkout for your client. |
| 401 | invalid_client | Unknown client, wrong secret, or the client has been revoked. |
Errors and limits
Every error from the /api/oauth/ endpoints is JSON in the same shape, and no response may be cached:
{ "error": "invalid_token", "error_description": "The access token is invalid, expired or revoked." }
Branch on error; error_description is for your logs and may change.
The endpoints are rate-limited per server IP address, at limits well above what one site's normal traffic needs. Over a limit you get 429 rate_limited with a Retry-After header saying how many seconds to wait.
The sandbox
The sandbox is Leanpub's staging site, https://staging.leanpub.com. It runs the same code as production, with Stripe in test mode and PayPal's sandbox, so you can run the whole flow, payment included, without real money.
- Credentials. For the integration days we agree with you, we register a staging client and send you its
client_idandclient_secret, registered with the redirect and checkout return URIs you ask for (they can point at your own staging or development site), a test book's slug, and two coupon codes for it: one that makes it free and one that discounts it. - The site password. Every page of staging sits behind a password. We give you the username and password; your browser asks for them the first time it opens a staging page. Your server's calls to
/api/oauth/don't need it: send only your own client credentials or access token, as in production. - Test buyers. Create Leanpub accounts on staging for your test buyers. Pay with Stripe's test cards (for example
4242 4242 4242 4242, any future expiry date, any CVC) or a PayPal sandbox account. - Every Sunday at 00:00 UTC staging is wiped and rebuilt. Accounts, purchases, checkouts and tokens you created there are deleted, and so is your staging client: after a wipe we register a new one and send you its new
client_idandclient_secretbefore your next integration day. Your test buyers have to sign up again. - Staging sleeps when nobody uses it. A sleeping staging answers with an HTML holding page instead of JSON, and a payment made while it sleeps may not complete until we step in. Agree your integration days with us and we'll keep it awake for them.
Going live
When your integration works on staging, we register your production client with your production URIs, books and coupons, and send you its credentials. Switch the host, the client id and the secret, and you're live. Nothing else changes.
Questions: hello@leanpub.com.