# API keys

> Use public, secret, and restricted API keys, rotate your secret keys, and create restricted keys for services that only need part of the API.

Paystack has three types of API keys. Public keys initiate payments from your frontend, secret keys call the full API from your backend, and restricted keys call only the endpoints you grant them.

## Key types

Every integration has a public key and a secret key for test mode and for live mode. Test keys start with `pk_test_` or `sk_test_`, and live keys start with `pk_live_` or `sk_live_`. Restricted keys are optional, and you create them on the dashboard when you need them.

<table>
<thead>
  <tr>
    <th>
      Type
    </th>
    
    <th>
      Prefix
    </th>
    
    <th>
      Where you use it
    </th>
    
    <th>
      What it can do
    </th>
  </tr>
</thead>

<tbody>
  <tr>
    <td>
      Public key
    </td>
    
    <td>
      <code>
        pk_
      </code>
    </td>
    
    <td>
      Frontend
    </td>
    
    <td>
      Initiate transactions with Paystack Inline and the Mobile SDKs
    </td>
  </tr>
  
  <tr>
    <td>
      Secret key
    </td>
    
    <td>
      <code>
        sk_
      </code>
    </td>
    
    <td>
      Backend
    </td>
    
    <td>
      Call every endpoint in the Paystack API, and sign the deprecated <code>
        X-Paystack-Signature
      </code>
      
       webhook header
    </td>
  </tr>
  
  <tr>
    <td>
      Restricted key
    </td>
    
    <td>
      <code>
        rk_
      </code>
    </td>
    
    <td>
      Backend
    </td>
    
    <td>
      Call only the endpoints covered by its <a href="/api/authentication#scopes">
        scopes
      </a>
    </td>
  </tr>
</tbody>
</table>

Your public key runs on your customer's device, so it's the only key that's safe to expose. Paystack signs webhook events with your [webhook signing secret](/developer-tools/integration/webhooks#verify-webhook-signatures), not with a restricted key. Your secret key signs only the deprecated `X-Paystack-Signature` header. You also need your secret key to compute checkout hashes for Paystack Inline, and to call an [endpoint that doesn't have a scope yet](/api/authentication#scopes).

Use a restricted key when a service only needs part of the API. For example, a reporting job that reads transactions only needs `transactions:read`. A restricted key is also the safer way to give a third party access to your account: scope it to what their tool does, and delete it when you stop working with them. If a restricted key leaks, it can only call the endpoints its scopes cover.

<callout title="Keep secret and restricted keys on your server" type="danger">

Don't put a secret key or a restricted key in frontend code, a mobile app, or a code repository.

</callout>

To send a key with a request, and to set up test mode, live mode, and IP allowlisting, see [Authentication](/api/authentication).

## Rotate your secret keys

Rotate your secret keys on a regular schedule, and right away if you suspect one has leaked. You generate new keys on the dashboard, then choose how long your current keys keep working while you move your systems to the new ones.

<callout title="Before you begin!" type="info">

Generating new keys replaces your live and test secret keys together. Before you start, find every place that uses either key: your production and staging servers, background workers and scheduled jobs, CI/CD secrets and your secrets manager, and your webhook code if it verifies `X-Paystack-Signature`. Each of these needs the new key before your current key expires.

</callout>

### Generate new secret keys

1. Open the [Developers overview](https://dashboard.paystack.com/v2/developers) page on your dashboard.
2. Click **Generate new secret key**.
3. Under **How soon should your old keys expire?**, choose an [expiry time](#choose-an-expiry-time).
4. Under **Enter your account password to confirm**, enter your password, then click **Generate new secret keys**.
5. Copy your new live and test secret keys.

When your current keys expire, Paystack sends you an email. The email doesn't contain your key values.

### Choose an expiry time

Your new keys work from the moment you confirm, and your current keys keep working until the expiry time you choose.

<table>
<thead>
  <tr>
    <th>
      Option
    </th>
    
    <th>
      When to use it
    </th>
  </tr>
</thead>

<tbody>
  <tr>
    <td>
      Immediately
    </td>
    
    <td>
      You suspect a secret key has been exposed
    </td>
  </tr>
  
  <tr>
    <td>
      30 minutes
    </td>
    
    <td>
      You can update every system that uses the key within 30 minutes
    </td>
  </tr>
  
  <tr>
    <td>
      2 hours
    </td>
    
    <td>
      You're doing a planned rotation
    </td>
  </tr>
</tbody>
</table>

<callout title="If a key has been exposed" type="danger">

Choose **Immediately**. Every request made with the exposed key fails from that moment, including requests from your own servers, so have the new key ready to deploy.

</callout>

### Update your servers

Replace the secret key in each environment, then deploy or restart every service that reads it. Read the key from an environment variable or your secrets manager, not from source code, so the next rotation is a configuration change and not a code change.

To confirm a server uses the new key, call the [Fetch Balance](/api/balance#fetch) endpoint from that server. A `200` response with `"status": true` means the key works:

<request-response>
<template v-slot:curl="">

```bash
curl https://api.paystack.co/balance \
  -H "Authorization: Bearer $PAYSTACK_SECRET_KEY"
```

</template>

<template v-slot:js="">

```javascript
const https = require("https");

const options = {
  hostname: "api.paystack.co",
  port: 443,
  path: "/balance",
  method: "GET",
  headers: {
    Authorization: `Bearer ${process.env.PAYSTACK_SECRET_KEY}`,
  },
};

const req = https.request(options, (res) => {
  let data = "";
  res.on("data", (chunk) => {
    data += chunk;
  });
  res.on("end", () => {
    console.log(res.statusCode, JSON.parse(data));
  });
});

req.on("error", (error) => {
  console.error(error);
});

req.end();
```

</template>

<template v-slot:php="">

```php
<?php
$curl = curl_init();
curl_setopt_array($curl, array(
  CURLOPT_URL => "https://api.paystack.co/balance",
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => "",
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 30,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => "GET",
  CURLOPT_HTTPHEADER => array(
    "Authorization: Bearer " . getenv("PAYSTACK_SECRET_KEY"),
    "Cache-Control: no-cache",
  ),
));
$response = curl_exec($curl);
echo curl_getinfo($curl, CURLINFO_HTTP_CODE) . " " . $response;
?>
```

</template>

<template v-slot:response="">

```json
{
  "status": true,
  "message": "Balances retrieved",
  "data": [
    {
      "currency": "NGN",
      "balance": 1700000
    }
  ]
}
```

</template>
</request-response>

Repeat the check with your test secret key in your test environments. Once your current key expires, any server still using it gets a `401` response with the message `Invalid key`. If you see this, check that live systems have the new `sk_live_` key and test systems have the new `sk_test_` key, then redeploy.

<callout title="Update your webhook signature check" type="warning">

If you verify the deprecated [`X-Paystack-Signature`](/developer-tools/integration/webhooks#x-paystack-signature-deprecated) header, update that code after you rotate. Paystack signs that header with your secret key. Until your current key expires, check each event's signature against both keys and accept it if either one matches. Once the current key expires, remove it from your configuration.

</callout>

## Restricted keys

A restricted key authenticates requests with `Authorization: Bearer rk_...`. Every restricted key has a name that describes what it's for and at least one [scope](/api/authentication#scopes), such as `transactions:read`. You can also give it an expiry date, after which the key stops working.

You can change a key's name and scopes after you create it, but not its expiry date. An expiry date can be at most a year away, or you can choose **No expiration**. An integration can have up to 50 active restricted keys. Paystack asks for your dashboard password whenever you create, edit, or delete one.

<callout title="Limitations" type="info">

Restricted keys can't manage API keys or change your integration settings, apart from the payment session timeout. Any endpoint that isn't covered by a scope rejects a restricted key, so use the dashboard or your secret key for those. Restricted keys follow the same [IP allowlist](/api/authentication#ip-whitelisting) as your secret key.

</callout>

<callout title="Using a plugin?" type="warning">

If you plan to delete your secret key and you connect to Paystack through a plugin, first check that the plugin supports restricted keys and webhook signing secrets.

</callout>

### Create a restricted key

Decide which [scopes](/api/authentication#scopes) the service needs, and grant only those. Switch your dashboard to test or live mode first: a key created in test mode starts with `rk_test_` and only works with test data.

1. Open the [API configuration](https://dashboard.paystack.com/v2/developers/api-configuration) page on your dashboard, and under **Restricted API keys**, click **Create restricted key**.
2. Under **Choose permissions**, select **Read** or **Write** for each resource the key needs, then click **Continue**.
3. Under **Name and expiration**, enter a **Name** that describes what the key is for, such as `Reporting service`. Then choose an **Expiration**: 7, 30, 60, or 90 days, a custom date, or **No expiration**.
4. Click **Create restricted key**, then enter your password to confirm.
5. Copy the key and store it in your secrets manager. The dashboard shows the full key only once.

### Make a request with a restricted key

This request calls [List Transactions](/api/transaction#list) with a key that has the `transactions:read` scope. A `200` response means you set up the key and scope correctly:

<request-response>
<template v-slot:curl="">

```bash
curl "https://api.paystack.co/transaction?perPage=1" \
  -H "Authorization: Bearer $PAYSTACK_RESTRICTED_KEY"
```

</template>

<template v-slot:js="">

```javascript
const https = require("https");

const options = {
  hostname: "api.paystack.co",
  port: 443,
  path: "/transaction?perPage=1",
  method: "GET",
  headers: {
    Authorization: `Bearer ${process.env.PAYSTACK_RESTRICTED_KEY}`,
  },
};

const req = https.request(options, (res) => {
  let data = "";
  res.on("data", (chunk) => {
    data += chunk;
  });
  res.on("end", () => {
    console.log(res.statusCode, JSON.parse(data));
  });
});

req.on("error", (error) => {
  console.error(error);
});

req.end();
```

</template>

<template v-slot:php="">

```php
<?php
$curl = curl_init();
curl_setopt_array($curl, array(
  CURLOPT_URL => "https://api.paystack.co/transaction?perPage=1",
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => "",
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 30,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => "GET",
  CURLOPT_HTTPHEADER => array(
    "Authorization: Bearer " . getenv("PAYSTACK_RESTRICTED_KEY"),
    "Cache-Control: no-cache",
  ),
));
$response = curl_exec($curl);
echo curl_getinfo($curl, CURLINFO_HTTP_CODE) . " " . $response;
?>
```

</template>

<template v-slot:response="">

```json
{
  "status": true,
  "message": "Transactions retrieved",
  "data": [
    {
      "id": 4099260516,
      "domain": "test",
      "status": "success",
      "reference": "re4lyvq3s3",
      "amount": 40333,
      "currency": "NGN",
      "paid_at": "2024-08-22T09:15:02.000Z"
    }
  ],
  "meta": {
    "next": "dW5kZWZpbmVkOjQwMTM3MDk2MzU=",
    "previous": null,
    "perPage": 1
  }
}
```

</template>
</request-response>

If you get a `401`, `403`, or `400` instead, see [Restricted key errors](/api/authentication#restricted-key-errors).

### Replace or delete a restricted key

You can't rotate a restricted key on the dashboard. To replace one, create a new key with the same scopes, update the service that uses it, then delete the old key.

Delete a restricted key when nothing should use it again, such as when you stop working with the third party that held it. Find the key under **Restricted API keys**, choose **Delete**, then click **Delete key** and enter your password. Any request using the key stops working right away, and you can't undo this.
