> ## Documentation Index
> Fetch the complete documentation index at: https://docs.recurso.dev/llms.txt
> Use this file to discover all available pages before exploring further.

# Complete an OAuth Login

> The redirect target the OAuth provider sends the browser back to; validates state, exchanges the code, and opens a dashboard session.

The provider redirects the browser here after the user consents. The server
validates the returned `state` against the `recurso_oauth_state` cookie set by
[`GET /auth/oauth/{provider}/start`](/api-reference/auth/oauth-start)
(constant-time compare), exchanges `code` for a token using the bound PKCE
verifier, fetches the user's profile, and requires a verified email (Google:
`email_verified` is true; GitHub: a primary, verified email).

It then finds or creates the account:

1. An existing linked identity logs in.
2. An existing user with the same verified email is linked to the new identity and logged in.
3. A brand-new email creates a tenant and its owner user, the same as [`POST /auth/register`](/api-reference/auth/register).

On success the server sets the `recurso_session` cookie — identical to a
password [login](/api-reference/auth/login) — and `302`s to the dashboard root.
On any failure other than a state mismatch it `302`s to
`{DASHBOARD_URL}/login?error=oauth`; the redirect target is always the
configured dashboard URL, never a caller-supplied one. The state cookie is
cleared whichever way the attempt ends, so each start is single-use.

You do not call this endpoint yourself — register it as the provider's
redirect URI (`https://api.recurso.dev/auth/oauth/{provider}/callback`).

## Path Parameters

| Parameter  | Type   | Required | Description                                                                                                   |
| ---------- | ------ | -------- | ------------------------------------------------------------------------------------------------------------- |
| `provider` | string | Yes      | The provider completing the login: `google` or `github`. Must match the provider bound into the state cookie. |

## Query Parameters

| Parameter | Type   | Required | Description                                                                                    |
| --------- | ------ | -------- | ---------------------------------------------------------------------------------------------- |
| `code`    | string | No       | The authorization code issued by the provider. Missing code redirects to the login error page. |
| `state`   | string | No       | The CSRF state echoed by the provider. Must equal the value bound into the state cookie.       |

## Example Request

```bash theme={null}
curl -i "https://api.recurso.dev/auth/oauth/google/callback?code=4%2F0AbCdEf...&state=Kx9v...Qm" \
  -b "recurso_oauth_state=eyJwIjoiZ29vZ2xlIi...aWQ.7hQ...Lw"
```

## Example Response

There is no response body. A successful login answers `302 Found` with the
session cookie:

```http theme={null}
HTTP/1.1 302 Found
Location: https://app.recurso.dev/
Set-Cookie: recurso_session=...; Path=/; HttpOnly; Secure; SameSite=Lax
Set-Cookie: recurso_oauth_state=; Path=/auth/oauth; Max-Age=0; HttpOnly; Secure; SameSite=Lax
```

A failed exchange, an unverified email, an expired (older than 10 minutes) or
missing state cookie, or a login error all answer
`302 Found` with `Location: https://app.recurso.dev/login?error=oauth`.

## Errors

| Status | Code        | When                                                                  | Fix                                                                                                                                 |
| ------ | ----------- | --------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------- |
| `403`  | `forbidden` | The `state` query value does not match the state bound in the cookie. | Start the flow again from [`GET /auth/oauth/{provider}/start`](/api-reference/auth/oauth-start); do not reuse an old authorize URL. |
| `404`  | `not_found` | `provider` is unknown or not configured.                              | Only route callbacks for providers listed as `enabled` by [`GET /auth/oauth/providers`](/api-reference/auth/oauth-providers).       |

Errors use the standard envelope — see [Errors](/api-reference/errors).


## OpenAPI

````yaml GET /auth/oauth/{provider}/callback
openapi: 3.1.0
info:
  title: Recurso API
  version: 1.0.0
  description: |
    The Recurso billing engine REST API.

    Authenticate by passing your API key as a bearer token:

        Authorization: Bearer <api_key>

    Obtain an API key by registering a tenant via `POST /auth/register`.
    All authenticated endpoints live under the `/v1` prefix. Mutating
    endpoints support idempotency via the `Idempotency-Key` header.
  license:
    name: MIT
    identifier: MIT
servers:
  - url: https://billing.example.com
    description: >-
      Example deployment — substitute the base URL of your own Recurso
      deployment.
security:
  - bearerAuth: []
tags:
  - name: System
    description: Health, version, and API metadata
  - name: Auth
    description: Tenant registration
  - name: Plans
    description: Product catalog plans
  - name: Customers
    description: Customer management
  - name: Subscriptions
    description: Subscription lifecycle
  - name: Invoices
    description: Invoices, PDFs, and Indian GST e-invoicing
  - name: Coupons
    description: Discounts
  - name: Usage
    description: Metered usage events
  - name: Credit Notes
    description: Customer credits
  - name: Quotes
    description: Quote-to-invoice lifecycle
  - name: Webhooks
    description: Webhook endpoint management and event feed
  - name: Analytics
    description: Revenue analytics
  - name: Checkout
    description: Public hosted checkout for invoices
  - name: Payments
    description: Payment order creation
  - name: Inbound Webhooks
    description: Receivers for payment-gateway callbacks (Razorpay, Stripe)
  - name: Customer Portal
    description: Customer-facing portal — magic-link auth and session-scoped data
  - name: Developer
    description: API key management
  - name: Account
    description: Tenant account settings
  - name: Finance
    description: Ledger accounts, entries, reconciliation, and revenue recognition
  - name: Settings
    description: Tax (GST) and e-invoicing (IRP) configuration
  - name: Consents
    description: Consent records for RBI-compliant recurring billing
  - name: Referrals
    description: Customer referral program
  - name: Gifts
    description: Gift subscriptions
  - name: Mandates
    description: UPI Autopay mandates
  - name: Offline Payments
    description: Virtual accounts and manually recorded payments
  - name: Organizations
    description: Multi-entity organizations grouping several tenants
  - name: Accounting
    description: QuickBooks / Xero accounting integrations
  - name: Churn
    description: Churn risk scoring and alerts
  - name: Cancel Flows
    description: Configurable retention flows shown at cancellation time
  - name: Dunning
    description: Dunning analytics and multi-channel dunning campaigns
paths:
  /auth/oauth/{provider}/callback:
    get:
      tags:
        - Auth
      summary: OAuth callback (provider redirects here)
      description: >
        Validates `state` against the cookie (constant-time), exchanges the code
        with PKCE, fetches userinfo and requires a verified email (Google:
        email_verified==true; GitHub: a primary verified email). Then
        find-or-create: (1) an existing identity logs in; (2) a matching
        verified email links a new identity and logs in; (3) a brand-new email
        creates a tenant + owner user. On success sets the `recurso_session`
        cookie and 302s to `{DASHBOARD_URL}/`. On failure 302s to
        `{DASHBOARD_URL}/login?error=oauth` (never an open redirect). A state
        mismatch returns 403.
      operationId: oauthCallback
      parameters:
        - name: provider
          in: path
          required: true
          schema:
            type: string
            enum:
              - google
              - github
        - name: code
          in: query
          required: false
          schema:
            type: string
        - name: state
          in: query
          required: false
          schema:
            type: string
      responses:
        '302':
          description: >-
            Redirect to the dashboard on success, or to the login error page on
            failure. Sets the session cookie on success.
        '403':
          $ref: '#/components/responses/Forbidden'
        '404':
          $ref: '#/components/responses/NotFound'
      security: []
components:
  responses:
    Forbidden:
      description: Authenticated but not permitted (insufficient role).
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/Error'
    NotFound:
      description: The requested resource does not exist.
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/Error'
  schemas:
    Error:
      type: object
      required:
        - error
      properties:
        error:
          type: object
          description: Structured error detail.
          required:
            - code
            - message
          properties:
            code:
              type: string
              description: Stable machine-readable error code.
              examples:
                - validation_failed
                - unauthorized
                - forbidden
                - not_found
                - conflict
                - rate_limited
                - internal_error
                - invalid_api_key
                - key_mode_mismatch
                - over_refund
                - invoice_not_paid
                - invoice_already_paid
            message:
              type: string
              description: Human-readable explanation.
  securitySchemes:
    bearerAuth:
      type: http
      scheme: bearer
      bearerFormat: API key
      description: >-
        Tenant API key obtained from `POST /auth/register` or `POST
        /v1/developer/keys`.

````