Quickstart
Build a small CLI that checks for a sponsorship, signs supporters in and opens the checkout, in about three minutes.
This page builds my-cli, a tiny command-line program with three behaviours:
my-clichecks whether the current user sponsors you and, if not, prints a link to contribute;my-cli loginsigns the user in with GitHub or Open Collective;my-cli sponsoropens the checkout and waits until the new contribution shows up.
Pick your language below; the choice is remembered across the docs. Every program on this page compiles as-is against the SDK.
Install#
Every SDK is on its package registry; Install lists the other ways to add it.
mkdir my-cli && cd my-cli && npm init -y
npm install @sponsorkit/sdkdotnet new console -n my-cli && cd my-cli
dotnet add package Sponsorkitpython -m pip install sponsorkitgo mod init example.com/my-cli
go get github.com/ffMathy/sponsorkit/sdks/go@v1.0.0cargo new my-cli && cd my-cli
cargo add sponsorkit
cargo add tokio --features macros,rt-multi-threadTo try an unreleased change instead, build from source covers Git dependencies, local checkouts and pinning a commit.
Write the program#
Replace octocat and my-collective with the accounts you receive sponsorships on. You need at least one of
the two.
Works in Node 20+, Bun and Deno. The file is plain JavaScript and also valid TypeScript.
import { Sponsorkit, SponsorkitError } from "@sponsorkit/sdk/node";
const sk = new Sponsorkit({
github: "octocat", // your GitHub Sponsors login
openCollective: "my-collective", // and/or your Open Collective slug
appName: "my-cli", // shown on the consent screen
});
const command = process.argv[2];
try {
if (command === "login") {
// Opens the browser (or prints a link over SSH) and waits for the supporter.
const fc = await sk.signIn();
console.log(`Signed in. Active contributions: ${fc.active().length}`);
} else if (command === "sponsor") {
// Signs in if needed, opens the checkout, then waits for the new contribution.
const result = await sk.openCheckout({ frequency: "monthly", amount: 500 });
console.log(result.status === "contributed" ? "Thank you!" : "No new contribution detected yet.");
} else {
// Never throws because of the network: it serves the local cache instead.
const fc = await sk.getFinancialContribution();
const supporter = fc.active().some((c) => c.amount.currency === "USD" && c.amount.value >= 500);
if (!supporter) {
console.error(`Enjoying my-cli? Support it: ${sk.checkoutUrl({ frequency: "monthly" })}`);
if (!fc.signedIn) console.error("Already a sponsor? Run `my-cli login`.");
}
}
} catch (e) {
// Sign-in (in `login`, or in `sponsor` when signed out) didn't complete.
if (!(e instanceof SponsorkitError)) throw e;
if (e.code === "cancelled" || e.code === "timeout") {
console.error("Sign-in was cancelled or timed out.");
} else if (e.code === "network_error") {
console.error(`Sponsorkit is unreachable; try again in ${e.retryAfter ?? 60} s.`);
} else {
console.error(`Sponsorkit error (${e.code}): ${e.message}`); // access_denied, invalid_code, disabled, ...
}
process.exitCode = 1;
}node my-cli.mjs # or: bun my-cli.mjs
node my-cli.mjs loginIn a browser app, import from @sponsorkit/sdk instead and call signIn() from a click handler: sign-in then
uses a popup, and appName isn't needed because the consent screen shows your site's origin.
Replace the generated Program.cs. The project template enables implicit usings, so System and
System.Linq are already imported.
using Sponsorkit;
var sk = new SponsorkitClient(new SponsorkitOptions
{
GitHub = "octocat", // your GitHub Sponsors login
OpenCollective = "my-collective", // and/or your Open Collective slug
AppName = "my-cli", // shown on the consent screen
});
var command = args.Length > 0 ? args[0] : null;
try
{
if (command == "login")
{
// Opens the browser (or prints a link over SSH) and waits for the supporter.
var fc = await sk.SignInAsync();
Console.WriteLine($"Signed in. Active contributions: {fc.Active().Count}");
}
else if (command == "sponsor")
{
// Signs in if needed, opens the checkout, then waits for the new contribution.
var result = await sk.OpenCheckoutAsync(new CheckoutOptions { Frequency = Frequencies.Monthly, Amount = 500 });
Console.WriteLine(result.Status == CheckoutStatus.Contributed ? "Thank you!" : "No new contribution detected yet.");
}
else
{
// Never throws because of the network: it serves the local cache instead.
var fc = await sk.GetFinancialContributionAsync();
var supporter = fc.Active().Any(c => c.Amount.Currency == "USD" && c.Amount.Value >= 500);
if (!supporter)
{
Console.Error.WriteLine($"Enjoying my-cli? Support it: {sk.CheckoutUrl(new CheckoutUrlOptions { Frequency = Frequencies.Monthly })}");
if (!fc.SignedIn) Console.Error.WriteLine("Already a sponsor? Run `my-cli login`.");
}
}
}
// Sign-in (in `login`, or in `sponsor` when signed out) didn't complete.
catch (SponsorkitError e) when (e.Code is SponsorkitErrorCodes.Cancelled or SponsorkitErrorCodes.Timeout)
{
Console.Error.WriteLine("Sign-in was cancelled or timed out.");
return 1;
}
catch (SponsorkitError e) when (e.Code == SponsorkitErrorCodes.NetworkError)
{
Console.Error.WriteLine($"Sponsorkit is unreachable; try again in {e.RetryAfter?.TotalSeconds ?? 60} s.");
return 1;
}
catch (SponsorkitError e) // access_denied, invalid_code, disabled, ...
{
Console.Error.WriteLine($"Sponsorkit error ({e.Code}): {e.Message}");
return 1;
}
return 0;dotnet run
dotnet run -- loginEvery blocking method also has an async twin with an a prefix, such as await sk.aget_financial_contribution().
import sys
from sponsorkit import Sponsorkit, SponsorkitError
sk = Sponsorkit(
github="octocat", # your GitHub Sponsors login
open_collective="my-collective", # and/or your Open Collective slug
app_name="my-cli", # shown on the consent screen
)
command = sys.argv[1] if len(sys.argv) > 1 else None
try:
if command == "login":
# Opens the browser (or prints a link over SSH) and waits for the supporter.
fc = sk.sign_in()
print(f"Signed in. Active contributions: {len(fc.active())}")
elif command == "sponsor":
# Signs in if needed, opens the checkout, then waits for the new contribution.
result = sk.open_checkout(frequency="monthly", amount=500)
print("Thank you!" if result.status == "contributed" else "No new contribution detected yet.")
else:
# Never raises because of the network: it serves the local cache instead.
fc = sk.get_financial_contribution()
supporter = any(c.amount.currency == "USD" and c.amount.value >= 500 for c in fc.active())
if not supporter:
print(f"Enjoying my-cli? Support it: {sk.checkout_url(frequency='monthly')}", file=sys.stderr)
if not fc.signed_in:
print("Already a sponsor? Run `my-cli login`.", file=sys.stderr)
except SponsorkitError as e:
# Sign-in (in `login`, or in `sponsor` when signed out) didn't complete.
if e.code in ("cancelled", "timeout"):
print("Sign-in was cancelled or timed out.", file=sys.stderr)
elif e.code == "network_error":
print(f"Sponsorkit is unreachable; try again in {e.retry_after or 60:.0f} s.", file=sys.stderr)
else: # access_denied, invalid_code, disabled, ...
print(f"Sponsorkit error ({e.code}): {e}", file=sys.stderr)
sys.exit(1)python my_cli.py
python my_cli.py loginpackage main
import (
"context"
"errors"
"fmt"
"log"
"os"
"time"
sponsorkit "github.com/ffMathy/sponsorkit/sdks/go"
)
func main() {
ctx := context.Background()
sk, err := sponsorkit.New(sponsorkit.Options{
GitHub: "octocat", // your GitHub Sponsors login
OpenCollective: "my-collective", // and/or your Open Collective slug
AppName: "my-cli", // shown on the consent screen
})
if err != nil {
log.Fatal(err) // invalid configuration only
}
command := ""
if len(os.Args) > 1 {
command = os.Args[1]
}
switch command {
case "login":
// Opens the browser (or prints a link over SSH) and waits for the supporter.
fc, err := sk.SignIn(ctx)
if err != nil {
signInFailed(err) // prints why and exits
}
fmt.Println("Signed in. Active contributions:", len(fc.Active()))
case "sponsor":
// Signs in if needed, opens the checkout, then waits for the new contribution.
res, err := sk.OpenCheckout(ctx, sponsorkit.CheckoutOptions{Frequency: sponsorkit.Monthly, Amount: 500})
if err != nil {
signInFailed(err) // prints why and exits
}
if res.Status == sponsorkit.CheckoutContributed {
fmt.Println("Thank you!")
} else {
fmt.Println("No new contribution detected yet.")
}
default:
// Network problems never return an error: the local cache is served instead.
fc, err := sk.GetFinancialContribution(ctx)
if err != nil {
log.Fatal(err)
}
supporter := false
for _, c := range fc.Active() {
if c.Amount.Currency == "USD" && c.Amount.Value >= 500 {
supporter = true
}
}
if !supporter {
link, _ := sk.CheckoutURL(sponsorkit.CheckoutOptions{Frequency: sponsorkit.Monthly})
fmt.Fprintln(os.Stderr, "Enjoying my-cli? Support it:", link)
if !fc.SignedIn {
fmt.Fprintln(os.Stderr, "Already a sponsor? Run `my-cli login`.")
}
}
}
}
// signInFailed explains why sign-in (in login, or in sponsor when signed out) didn't complete, then exits.
func signInFailed(err error) {
var e *sponsorkit.Error
switch {
case !errors.As(err, &e):
log.Fatal(err)
case e.Code == sponsorkit.CodeCancelled || e.Code == sponsorkit.CodeTimeout:
fmt.Fprintln(os.Stderr, "Sign-in was cancelled or timed out.")
case e.Code == sponsorkit.CodeNetworkError:
wait := time.Minute
if e.RetryAfter != nil {
wait = *e.RetryAfter
}
fmt.Fprintf(os.Stderr, "Sponsorkit is unreachable; try again in %s.\n", wait)
default:
fmt.Fprintln(os.Stderr, err) // access_denied, invalid_code, disabled, ...
}
os.Exit(1)
}go run .
go run . loginThe SDK is async and runs on Tokio, which is why the install step added tokio with the macros feature.
use sponsorkit::{CheckoutOptions, CheckoutOutcome, ErrorCode, Frequency, GetOptions, Options, SignInOptions, Sponsorkit};
#[tokio::main]
async fn main() -> Result<(), sponsorkit::Error> {
let sk = Sponsorkit::new(Options {
github: Some("octocat".into()), // your GitHub Sponsors login
open_collective: Some("my-collective".into()), // and/or your Open Collective slug
app_name: Some("my-cli".into()), // shown on the consent screen
..Default::default()
})?; // errors only on invalid configuration
match std::env::args().nth(1).as_deref() {
Some("login") => {
// Opens the browser (or prints a link over SSH) and waits for the supporter.
match sk.sign_in(SignInOptions::default()).await {
Ok(fc) => println!("Signed in. Active contributions: {}", fc.active().len()),
Err(e) => sign_in_failed(e),
}
}
Some("sponsor") => {
// Signs in if needed, opens the checkout, then waits for the new contribution.
let options = CheckoutOptions { frequency: Some(Frequency::Monthly), amount: Some(500), ..Default::default() };
match sk.open_checkout(options).await {
Ok(CheckoutOutcome::Contributed { .. }) => println!("Thank you!"),
Ok(CheckoutOutcome::Unknown) => println!("No new contribution detected yet."),
Err(e) => sign_in_failed(e),
}
}
_ => {
// Network problems never return an error: the local cache is served instead.
let fc = sk.get_financial_contribution(GetOptions::default()).await?;
let supporter = fc.active().iter().any(|c| c.amount.currency == "USD" && c.amount.value >= 500);
if !supporter {
let options = CheckoutOptions { frequency: Some(Frequency::Monthly), ..Default::default() };
eprintln!("Enjoying my-cli? Support it: {}", sk.checkout_url(&options)?);
if !fc.signed_in {
eprintln!("Already a sponsor? Run `my-cli login`.");
}
}
}
}
Ok(())
}
/// Explains why sign-in (in `login`, or in `sponsor` when signed out) didn't complete, then exits.
fn sign_in_failed(e: sponsorkit::Error) -> ! {
match e.code() {
ErrorCode::Cancelled | ErrorCode::Timeout => eprintln!("Sign-in was cancelled or timed out."),
ErrorCode::NetworkError => {
let wait = e.retry_after().map_or(60, |d| d.as_secs());
eprintln!("Sponsorkit is unreachable; try again in {wait} s.");
}
_ => eprintln!("{e}"), // access_denied, invalid_code, disabled, ...
}
std::process::exit(1)
}cargo run
cargo run -- loginTry it without signing in#
Mock mode returns realistic data without touching the network or the disk, in every SDK. Set
SPONSORKIT_MOCK and run the program as above:
SPONSORKIT_MOCK=signed-out node my-cli.mjs # or: dotnet run, python my_cli.py, go run ., cargo runSPONSORKIT_MOCK | The supporter | my-cli prints |
|---|---|---|
signed-out | Not signed in | The link and the login hint |
none | Signed in, no contributions | The link |
active-monthly | Signed in, an active $5/month sponsorship | Nothing |
In mock mode login and sponsor succeed
immediately, and sponsor simulates a new contribution. The mock mode guide lists every
preset and shows how to pass your own contributions in tests.
What happened#
- No network when signed out. The plain
my-clirun answers instantly for users who never signed in. - One sign-in.
loginshowed a consent screen that names your accounts andmy-cli(labelled "says it is", because a native app can't prove its name). The session token is stored in the user's config directory; see Sign-in & sessions. - Sign-in can fail.
loginandsponsor(when signed out) raise an error if the supporter closes the window, enters no code, declines, takes longer thansignInTimeout(5 minutes), or the API is unreachable; the program reports it and exits with status 1. The plain check only fails on a bad configuration. See the error contract. - Cheap checks. Later runs are answered from the local cache for an hour; see Caching & freshness.
- Your rule. "At least $5 a month on GitHub" is just one example. The result has every contribution's provider, amount, frequency and status; see the contribution shape.
Next steps#
- Show the reminder only every N runs, and never in CI: the nag helper.
- Understand checkout detection and its limits: the checkout guide.
- Need a trustworthy answer on your server? Backend verification.
- Your language's specifics: the language guides.