Rust API reference

Every public type, function and constant of the sponsorkit crate 1.0.0, generated from its source and doc comments.

On this page

API reference for the sponsorkit crate, version 1.0.0. It's generated from the crate's source and doc comments; for a guided tour, start with Sponsorkit for Rust.

Pre-release

The crate hasn't been published to crates.io yet. Until it is, depend on the repository:

Cargo.toml
[dependencies]
sponsorkit = { git = "https://github.com/ffMathy/sponsorkit", branch = "main" }

See installing the Rust SDK for a local path and the Cargo.toml line to use once the crate is released.

Build GitHub Sponsors and Open Collective contributions into your Rust app or CLI. No account, no API key: name the account(s) you receive contributions on, ask what the current user contributes, and send them to contribute.

use sponsorkit::{CheckoutOptions, Frequency, GetOptions, Options, Sponsorkit};

let sk = Sponsorkit::new(Options {
    github: Some("octocat".into()),
    open_collective: Some("sponsorkit".into()),
    app_name: Some("my-cli".into()),
    ..Default::default()
})?;

let fc = sk.get_financial_contribution(GetOptions::default()).await?;
let supports = fc.active().iter().any(|c| c.amount.currency == "USD" && c.amount.value >= 500);
if fc.signed_in && !supports {
    println!("Support my-cli: {}", sk.checkout_url(&CheckoutOptions::default())?);
}

// Interactive: sign in (if needed), open the checkout, wait for the contribution.
let outcome = sk
    .open_checkout(CheckoutOptions { frequency: Some(Frequency::Monthly), amount: Some(500), ..Default::default() })
    .await?;

Guarantees#

  • Sponsorkit::get_financial_contribution never fails because Sponsorkit, a provider or the network is down; it serves the local cache instead . Its only error is invalid_config from the dev-time check.
  • SPONSORKIT_DISABLE=1 turns the SDK into a no-op without network or disk access.
  • Mock mode (Options::mock or SPONSORKIT_MOCK) gives deterministic data for tests.

Cancellation#

Sponsorkit::sign_in accepts a CancellationToken in SignInOptions::cancel; cancelling fails with ErrorCode::Cancelled. Sponsorkit::open_checkout accepts one in CheckoutOptions::cancel; cancelling (in the sign-in or the polling phase) resolves CheckoutOutcome::Unknown. Dropping either future (e.g. through tokio::time::timeout or select!) also stops it, without a result.

Errors#

Every error is an Error whose Error::code is one of the codes shared by all Sponsorkit SDKs: invalid_config, disabled, popup_blocked, access_denied, invalid_state, provider_error, invalid_code, cancelled, timeout, network_error (with Error::retry_after), session_invalid and targets_mismatch.

Runtime#

The SDK needs a Tokio runtime (current-thread or multi-thread). Local storage uses small synchronous file operations.

Modules#

NameDescription
serverBackend verification: check a session token your frontend sent you.

Structs#

NameDescription
CheckoutOptionsOptions for Sponsorkit::open_checkout and Sponsorkit::checkout_url.
ContributionOne sponsorship (GitHub) or order (Open Collective), normalized.
ContributionResultThe result of crate::Sponsorkit::get_financial_contribution.
DueOptionsOptions for Nag::due_with.
ErrorThe error type of this crate (SponsorkitError in the other SDKs).
GetOptionsOptions for Sponsorkit::get_financial_contribution.
IdentityA provider identity of the signed-in supporter.
MoneyAn amount of money in minor units (cents).
NagA nag created by Sponsorkit::nag.
NagOptionsConfiguration for Sponsorkit::nag.
OptionsConfiguration for Sponsorkit::new.
SignInOptionsOptions for Sponsorkit::sign_in.
SponsorEntityWho actually pays.
SponsorkitA Sponsorkit client for one target set.
SupporterThe signed-in supporter.
TargetOne normalized target.
TargetSetA canonical target set: deduplicated, sorted by string form, non-empty, at most one target per provider.
TargetsThe accounts to check, as given by the maintainer ({ github, open_collective }).
TierA tier reference on a contribution.

Enums#

NameDescription
CheckoutOutcomeThe outcome of crate::Sponsorkit::open_checkout.
ErrorCodeA stable, machine-readable error code.
FlagContribution flags.
FrequencyHow often a contribution is charged.
KindRecurring or one-time.
MockMock data for crate::Options::mock.
MockPresetA built-in mock preset.
ProviderA contribution provider.
SignInMethodHow sign_in (and open_checkout when signed out) gets the sign-in code.
SponsorTypeThe type of a sponsor entity.
StatusContribution status.
ViaWhether the supporter paid directly or through an organization.

Type aliases#

NameDescription
BoxFutureA boxed, sendable future, used by the hook types.
OpenBrowserHookReplacement for opening the system browser: receives the URL to open.
PromptForCodeHookReplacement for reading the paste-back code from stdin: receives the <site_base_url>/connect/?…&delivery=paste URL the user has to open and returns the code.
ResultShorthand for std::result::Result<T, sponsorkit::Error>.

Functions and constants#

NameKindDescription
DEFAULT_API_BASE_URLconstantThe default API origin, used for every API call (/api/v1/…).
DEFAULT_CACHE_TTLconstantThe default cache TTL (1 hour).
DEFAULT_CHECKOUT_POLL_INTERVALconstantThe default interval at which open_checkout polls for a new contribution (60 s).
DEFAULT_CHECKOUT_TIMEOUTconstantThe default time open_checkout waits for a contribution (10 minutes).
DEFAULT_REQUEST_TIMEOUTconstantThe default Options::request_timeout for every HTTP request (30 s).
DEFAULT_SIGN_IN_TIMEOUTconstantThe default Options::sign_in_timeout (300 s).
DEFAULT_SITE_BASE_URLconstantThe default site base URL (origin plus base path), used for every page URL: /connect/, /checkout/ and Sponsorkit::checkout_url.
MAX_RETRY_AFTERconstantThe longest Retry-After the SDK honours (24 h); longer values are clamped.
MIN_CACHE_TTLconstantThe minimum cache TTL accepted by Options::cache_ttl (60 s).
MOCK_PRESETS_JSONconstantThe embedded preset file (identical to sdks/conformance/fixtures/mock-presets.json).
base64urlfunctionEncodes bytes as base64url without padding.
code_challengefunctioncode_challenge = base64url(sha256(ascii(code_verifier))), without padding.
generate_verifierfunctionGenerates a fresh code verifier: 32 random bytes, base64url (43 characters).
mock_resultfunctionExpands a mock configuration into a result (rules 1–4 of mock-presets.json).
parse_iso_durationfunctionParses an ISO-8601 duration such as P7D, PT12H, P1W or P1DT2H30M.

Re-exports#

NameRe-exported from
CancellationTokentokio_util::sync::CancellationToken

Functions#

base64url#

pub fn base64url(bytes: &[u8]) -> String

Encodes bytes as base64url without padding.

ParameterType
bytes&[u8]

Returns: String

code_challenge#

pub fn code_challenge(verifier: &str) -> String

code_challenge = base64url(sha256(ascii(code_verifier))), without padding.

ParameterType
verifier&str

Returns: String

generate_verifier#

pub fn generate_verifier() -> Result<String>

Generates a fresh code verifier: 32 random bytes, base64url (43 characters).

Returns: Result<String> (see Result)

mock_result#

pub fn mock_result(targets: &TargetSet, mock: &Mock) -> ContributionResult

Expands a mock configuration into a result (rules 1–4 of mock-presets.json).

ParameterType
targets&TargetSet
mock&Mock

Returns: ContributionResult

parse_iso_duration#

pub fn parse_iso_duration(s: &str) -> Result<Duration>

Parses an ISO-8601 duration such as P7D, PT12H, P1W or P1DT2H30M.

Years and months are not supported (they have no fixed length); use days. Returns an invalid_config error for anything else.

ParameterType
s&str

Returns: Result<Duration> (see Result)

Constants#

DEFAULT_API_BASE_URL#

pub const DEFAULT_API_BASE_URL: &str = "https://api.sponsorkit.io";

The default API origin, used for every API call (/api/v1/…).

DEFAULT_CACHE_TTL#

pub const DEFAULT_CACHE_TTL: Duration = Duration::from_secs(3600);

The default cache TTL (1 hour).

DEFAULT_CHECKOUT_POLL_INTERVAL#

pub const DEFAULT_CHECKOUT_POLL_INTERVAL: Duration = Duration::from_secs(60);

The default interval at which open_checkout polls for a new contribution (60 s).

DEFAULT_CHECKOUT_TIMEOUT#

pub const DEFAULT_CHECKOUT_TIMEOUT: Duration = Duration::from_secs(600);

The default time open_checkout waits for a contribution (10 minutes).

DEFAULT_REQUEST_TIMEOUT#

pub const DEFAULT_REQUEST_TIMEOUT: Duration = Duration::from_secs(30);

The default Options::request_timeout for every HTTP request (30 s).

DEFAULT_SIGN_IN_TIMEOUT#

pub const DEFAULT_SIGN_IN_TIMEOUT: Duration = Duration::from_secs(300);

The default Options::sign_in_timeout (300 s).

DEFAULT_SITE_BASE_URL#

pub const DEFAULT_SITE_BASE_URL: &str = "https://ffmathy.github.io/sponsorkit";

The default site base URL (origin plus base path), used for every page URL: /connect/, /checkout/ and Sponsorkit::checkout_url.

MAX_RETRY_AFTER#

pub const MAX_RETRY_AFTER: Duration = Duration::from_secs(86_400);

The longest Retry-After the SDK honours (24 h); longer values are clamped.

MIN_CACHE_TTL#

pub const MIN_CACHE_TTL: Duration = Duration::from_secs(60);

The minimum cache TTL accepted by Options::cache_ttl (60 s).

MOCK_PRESETS_JSON#

pub const MOCK_PRESETS_JSON: &str = include_str!("mock-presets.json");

The embedded preset file (identical to sdks/conformance/fixtures/mock-presets.json).