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

# Get the access token of an internal app

> Internal apps call this API to get an access_token used for identity authentication when calling DingTalk server-side APIs, ensuring legitimate requests with proper permissions.

Call this API from an internal app to obtain an access credential (access token). When calling DingTalk Server APIs, you must use the access token for authentication to ensure that the request comes from a legitimate source and has the required permissions.

## API call description

This API is designed for internal enterprise system integration scenarios and is used to obtain the access credential required to call DingTalk open capabilities. A typical usage flow is as follows:

* Call this API to obtain an access token when the app starts or before the first API call.
* Cache the obtained access token in local storage (such as Redis or in-memory cache) to avoid repeated requests.
* Carry this access token in all subsequent API calls that require authentication.
* Set the cache expiration time slightly shorter than 7,200 seconds (for example, 7,000 seconds) to implement an automatic refresh mechanism and prevent credential expiration caused by time deviations.
* Avoid calling this API frequently within a short period. Otherwise, the rate limit policy may be triggered, affecting service stability.

## Request

| **Basic information** |                                                                                                    |
| --------------------- | -------------------------------------------------------------------------------------------------- |
| HTTP URL              | [https://api.dingtalk.io/v1.0/oauth2/accessToken](https://api.dingtalk.io/v1.0/oauth2/accessToken) |
| HTTP Method           | POST                                                                                               |
| Supported app type    | appType-Internal app                                                                               |
| Required permissions  | permission-qyapi\_base-Basic permissions required to call enterprise APIs                          |

### Request body

| Name      | Type   | Required | Example               | Description                                                                                                                                                                                                                                 |
| --------- | ------ | -------- | --------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| appKey    | String | Yes      | dingeqqpkv3xxxxxx     | The Client ID of the created internal app. For details on how to obtain it, see the [Client ID/Client Secret](/open/dingstart/basic-concepts-beta) document.                                                                                |
| appSecret | String | Yes      | GT-lsu-taDAxxxsTsxxxx | The Client Secret of the created internal app. For details on how to obtain it, see the [Client ID/Client Secret](/open/dingstart/basic-concepts-beta) document.  **Note**  Keep the Client Secret secure and prevent it from being leaked. |

### Request example

```curl theme={"theme":{"light":"github-light","dark":"github-dark"}}
curl -X POST 'https://api.dingtalk.io/v1.0/oauth2/accessToken' \
  -H 'Content-Type: application/json' \
  -d '{
    "appKey": "dingeqqpkv3xxxxxx",
    "appSecret": "GT-lsu-taDAxxxsTsxxxx"
  }'
```

Java

```java theme={"theme":{"light":"github-light","dark":"github-dark"}}
// This file is auto-generated, don't edit it. Thanks.
package com.aliyun.sample;

import com.aliyun.tea.*;

public class Sample {

    /**
     * Initialize the account Client using a Token
     * @return Client
     * @throws Exception
     */
    public static com.aliyun.dingtalkoauth2_1_0.Client createClient() throws Exception {
        com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config();
        config.protocol = "https";
        config.regionId = "central";
        return new com.aliyun.dingtalkoauth2_1_0.Client(config);
    }

    public static void main(String[] args_) throws Exception {
        java.util.List<String> args = java.util.Arrays.asList(args_);
        com.aliyun.dingtalkoauth2_1_0.Client client = Sample.createClient();
        com.aliyun.dingtalkoauth2_1_0.models.GetAccessTokenRequest getAccessTokenRequest = new com.aliyun.dingtalkoauth2_1_0.models.GetAccessTokenRequest()
                .setAppKey("dingeqqpkv3xxxxxx")
                .setAppSecret("GT-lsu-taDAxxxsTsxxxx");
        try {
            client.getAccessToken(getAccessTokenRequest);
        } catch (TeaException err) {
            if (!com.aliyun.teautil.Common.empty(err.code) && !com.aliyun.teautil.Common.empty(err.message)) {
                // err contains the code and message attributes, which help locate the issue
            }

        } catch (Exception _err) {
            TeaException err = new TeaException(_err.getMessage(), _err);
            if (!com.aliyun.teautil.Common.empty(err.code) && !com.aliyun.teautil.Common.empty(err.message)) {
                // err contains the code and message attributes, which help locate the issue
            }

        }        
    }
}
```

Python

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
# -*- coding: utf-8 -*-
# This file is auto-generated, don't edit it. Thanks.
import sys

from typing import List

from alibabacloud_dingtalk.oauth2_1_0.client import Client as dingtalkoauth2_1_0Client
from alibabacloud_tea_openapi import models as open_api_models
from alibabacloud_dingtalk.oauth2_1_0 import models as dingtalkoauth_2__1__0_models
from alibabacloud_tea_util.client import Client as UtilClient

class Sample:
    def __init__(self):
        pass

    @staticmethod
    def create_client() -> dingtalkoauth2_1_0Client:
        """
        Initialize the account Client using a Token
        @return: Client
        @throws Exception
        """
        config = open_api_models.Config()
        config.protocol = 'https'
        config.region_id = 'central'
        return dingtalkoauth2_1_0Client(config)

    @staticmethod
    def main(
        args: List[str],
    ) -> None:
        client = Sample.create_client()
        get_access_token_request = dingtalkoauth_2__1__0_models.GetAccessTokenRequest(
            app_key='dingeqqpkv3xxxxxx',
            app_secret='GT-lsu-taDAxxxsTsxxxx'
        )
        try:
            client.get_access_token(get_access_token_request)
        except Exception as err:
            if not UtilClient.empty(err.code) and not UtilClient.empty(err.message):
                # err contains the code and message attributes, which help locate the issue
                pass

    @staticmethod
    async def main_async(
        args: List[str],
    ) -> None:
        client = Sample.create_client()
        get_access_token_request = dingtalkoauth_2__1__0_models.GetAccessTokenRequest(
            app_key='dingeqqpkv3xxxxxx',
            app_secret='GT-lsu-taDAxxxsTsxxxx'
        )
        try:
            await client.get_access_token_async(get_access_token_request)
        except Exception as err:
            if not UtilClient.empty(err.code) and not UtilClient.empty(err.message):
                # err contains the code and message attributes, which help locate the issue
                pass

if __name__ == '__main__':
    Sample.main(sys.argv[1:])
```

PHP

```java theme={"theme":{"light":"github-light","dark":"github-dark"}}
<?php

// This file is auto-generated, don't edit it. Thanks.
namespace AlibabaCloud\SDK\Sample;

use AlibabaCloud\SDK\Dingtalk\Voauth2_1_0\Dingtalk;
use \Exception;
use AlibabaCloud\Tea\Exception\TeaError;
use AlibabaCloud\Tea\Utils\Utils;

use Darabonba\OpenApi\Models\Config;
use AlibabaCloud\SDK\Dingtalk\Voauth2_1_0\Models\GetAccessTokenRequest;

class Sample {

    /**
     * Initialize the account Client using a Token
     * @return Dingtalk Client
     */
    public static function createClient(){
        $config = new Config([]);
        $config->protocol = "https";
        $config->regionId = "central";
        return new Dingtalk($config);
    }

    /**
     * @param string[] $args
     * @return void
     */
    public static function main($args){
        $client = self::createClient();
        $getAccessTokenRequest = new GetAccessTokenRequest([
            "appKey" => "dingeqqpkv3xxxxxx",
            "appSecret" => "GT-lsu-taDAxxxsTsxxxx"
        ]);
        try {
            $client->getAccessToken($getAccessTokenRequest);
        }
        catch (Exception $err) {
            if (!($err instanceof TeaError)) {
                $err = new TeaError([], $err->getMessage(), $err->getCode(), $err);
            }
            if (!Utils::empty_($err->code) && !Utils::empty_($err->message)) {
                // err contains the code and message attributes, which help locate the issue
            }
        }
    }
}
$path = __DIR__ . \DIRECTORY_SEPARATOR . '..' . \DIRECTORY_SEPARATOR . 'vendor' . \DIRECTORY_SEPARATOR . 'autoload.php';
if (file_exists($path)) {
    require_once $path;
}
Sample::main(array_slice($argv, 1));
```

Go

```go theme={"theme":{"light":"github-light","dark":"github-dark"}}
// This file is auto-generated, don't edit it. Thanks.
package main

import (
  "os"
  util  "github.com/alibabacloud-go/tea-utils/v2/service"
  dingtalkoauth2_1_0  "github.com/alibabacloud-go/dingtalk/oauth2_1_0"
  openapi  "github.com/alibabacloud-go/darabonba-openapi/v2/client"
  "github.com/alibabacloud-go/tea/tea"
)

/**
 * Initialize the account Client using a Token
 * @return Client
 * @throws Exception
 */
func CreateClient () (_result *dingtalkoauth2_1_0.Client, _err error) {
  config := &openapi.Config{}
  config.Protocol = tea.String("https")
  config.RegionId = tea.String("central")
  _result = &dingtalkoauth2_1_0.Client{}
  _result, _err = dingtalkoauth2_1_0.NewClient(config)
  return _result, _err
}

func _main (args []*string) (_err error) {
  client, _err := CreateClient()
  if _err != nil {
    return _err
  }

  getAccessTokenRequest := &dingtalkoauth2_1_0.GetAccessTokenRequest{
    AppKey: tea.String("dingeqqpkv3xxxxxx"),
    AppSecret: tea.String("GT-lsu-taDAxxxsTsxxxx"),
  }
  tryErr := func()(_e error) {
    defer func() {
      if r := tea.Recover(recover()); r != nil {
        _e = r
      }
    }()
    _, _err = client.GetAccessToken(getAccessTokenRequest)
    if _err != nil {
      return _err
    }

    return nil
  }()

  if tryErr != nil {
    var err = &tea.SDKError{}
    if _t, ok := tryErr.(*tea.SDKError); ok {
      err = _t
    } else {
      err.Message = tea.String(tryErr.Error())
    }
    if !tea.BoolValue(util.Empty(err.Code)) && !tea.BoolValue(util.Empty(err.Message)) {
      // err contains the code and message attributes, which help locate the issue
    }

  }
  return _err
}

func main() {
  err := _main(tea.StringSlice(os.Args[1:]))
  if err != nil {
    panic(err)
  }
}
```

Node.js

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
// This file is auto-generated, don't edit it
import Util from '@alicloud/tea-util';
import dingtalkoauth2_1_0, * as $dingtalkoauth2_1_0 from '@alicloud/dingtalk/oauth2_1_0';
import OpenApi, * as $OpenApi from '@alicloud/openapi-client';
import * as $tea from '@alicloud/tea-typescript';

export default class Client {

  /**
   * Initialize the account Client using a Token
   * @return Client
   * @throws Exception
   */
  static createClient(): dingtalkoauth2_1_0 {
    let config = new $OpenApi.Config({ });
    config.protocol = "https";
    config.regionId = "central";
    return new dingtalkoauth2_1_0(config);
  }

  static async main(args: string[]): Promise<void> {
    let client = Client.createClient();
    let getAccessTokenRequest = new $dingtalkoauth2_1_0.GetAccessTokenRequest({
      appKey: "dingeqqpkv3xxxxxx",
      appSecret: "GT-lsu-taDAxxxsTsxxxx",
    });
    try {
      await client.getAccessToken(getAccessTokenRequest);
    } catch (err) {
      if (!Util.empty(err.code) && !Util.empty(err.message)) {
        // err contains the code and message attributes, which help locate the issue
      }

    }    
  }

}

Client.main(process.argv.slice(2));
```

C#

```java theme={"theme":{"light":"github-light","dark":"github-dark"}}
// This file is auto-generated, don't edit it. Thanks.

using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;

using Tea;
using Tea.Utils;

namespace AlibabaCloud.SDK.Sample
{
    public class Sample 
    {

        /**
         * Initialize the account Client using a Token
         * @return Client
         * @throws Exception
         */
        public static AlibabaCloud.SDK.Dingtalkoauth2_1_0.Client CreateClient()
        {
            AlibabaCloud.OpenApiClient.Models.Config config = new AlibabaCloud.OpenApiClient.Models.Config();
            config.Protocol = "https";
            config.RegionId = "central";
            return new AlibabaCloud.SDK.Dingtalkoauth2_1_0.Client(config);
        }

        public static void Main(string[] args)
        {
            AlibabaCloud.SDK.Dingtalkoauth2_1_0.Client client = CreateClient();
            AlibabaCloud.SDK.Dingtalkoauth2_1_0.Models.GetAccessTokenRequest getAccessTokenRequest = new AlibabaCloud.SDK.Dingtalkoauth2_1_0.Models.GetAccessTokenRequest
            {
                AppKey = "dingeqqpkv3xxxxxx",
                AppSecret = "GT-lsu-taDAxxxsTsxxxx",
            };
            try
            {
                client.GetAccessToken(getAccessTokenRequest);
            }
            catch (TeaException err)
            {
                if (!AlibabaCloud.TeaUtil.Common.Empty(err.Code) && !AlibabaCloud.TeaUtil.Common.Empty(err.Message))
                {
                    // err contains the code and message attributes, which help locate the issue
                }
            }
            catch (Exception _err)
            {
                TeaException err = new TeaException(new Dictionary<string, object>
                {
                    { "message", _err.Message }
                });
                if (!AlibabaCloud.TeaUtil.Common.Empty(err.Code) && !AlibabaCloud.TeaUtil.Common.Empty(err.Message))
                {
                    // err contains the code and message attributes, which help locate the issue
                }
            }
        }

    }
}
```

python2

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
# -*- coding: utf-8 -*-
# This file is auto-generated, don't edit it. Thanks.
from __future__ import unicode_literals

import sys

from alibabacloud_dingtalkoauth2_1_0.client import Client as dingtalkoauth2_1_0Client
from alibabacloud_tea_openapi import models as open_api_models
from alibabacloud_dingtalkoauth2_1_0 import models as dingtalkoauth_2__1__0_models
from alibabacloud_tea_util.client import Client as UtilClient

class Sample(object):
    def __init__(self):
        pass

    @staticmethod
    def create_client():
        """
        Initialize the account Client using a Token

        @return: Client
        @throws Exception
        """
        config = open_api_models.Config()
        config.protocol = 'https'
        config.region_id = 'central'
        return dingtalkoauth2_1_0Client(config)

    @staticmethod
    def main(args):
        client = Sample.create_client()
        get_access_token_request = dingtalkoauth_2__1__0_models.GetAccessTokenRequest(
            app_key='dingeqqpkv3xxxxxx',
            app_secret='GT-lsu-taDAxxxsTsxxxx'
        )
        try:
            client.get_access_token(get_access_token_request)
        except Exception as err:
            if not UtilClient.empty(err.code) and not UtilClient.empty(err.message):
                # err contains the code and message attributes, which help locate the issue
                pass

if __name__ == '__main__':
    Sample.main(sys.argv[1:])
```

Swift

```java theme={"theme":{"light":"github-light","dark":"github-dark"}}
#!/usr/bin/env xcrun swift

import Cocoa
import Foundation
import Tea
import TeaUtils
import AlibabacloudDingtalkoauth210
import AlibabacloudOpenApi

open class Client {
    public static func createClient() throws -> AlibabacloudDingtalkoauth210.Client {
        var config: AlibabacloudOpenApi.Config = AlibabacloudOpenApi.Config([:])
        config.protocol_ = "https"
        config.regionId = "central"
        return AlibabacloudDingtalkoauth210.Client(config)
    }

    @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
    public static func main(_ args: [String]?) async throws -> Void {
        var client: AlibabacloudDingtalkoauth210.Client = try Client.createClient()
        var getAccessTokenRequest: AlibabacloudDingtalkoauth210.GetAccessTokenRequest = AlibabacloudDingtalkoauth210.GetAccessTokenRequest([
            "appKey": "dingeqqpkv3xxxxxx",
            "appSecret": "GT-lsu-taDAxxxsTsxxxx"
        ])
        do {
            try await client.getAccessToken(getAccessTokenRequest as! AlibabacloudDingtalkoauth210.GetAccessTokenRequest)
        }
        catch {
            if error is Tea.TeaError {
                var err = error as! Tea.TeaError
                if (!TeaUtils.Client.empty(err.code) && !TeaUtils.Client.empty(err.message)) {
                }
            } else {
                throw error
            }
        }
    }
}

Client.main(CommandLine.arguments)
```

## Response

### Response body

| Name        | Type   | Example                 | Description                                                                                                                                                                                                                                                                                                                                                                                                 |
| ----------- | ------ | ----------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| accessToken | String | fw8ef8we8f76e6f7s8dxxxx | The generated access token.  **Note**  When using the access token, keep the following points in mind:   - Cache the access token on your side, and store it separately by app, because the access token of each internal app is independent. - Do not call this API frequently to obtain the credential. Use a caching mechanism to control the call frequency and avoid being rate-limited by the system. |
| expireIn    | Long   | 7200                    | The expiration time of the access token, in seconds.  **Note**  The access token is valid for 7,200 seconds (2 hours). Repeated requests within the validity period return the same result and automatically extend the validity. After expiration, a new access token is returned.                                                                                                                         |

### Response body example

```text theme={"theme":{"light":"github-light","dark":"github-dark"}}
HTTP/1.1 200 OK
Content-Type:application/json

{
  "accessToken" : "fw8ef8we8f76e6f7s8dxxxx",
  "expireIn" : 7200
}
```

### Error codes

If an error is returned when calling this API, find the solution based on the error message in the [Global error codes](/open/development/server-api-error-codes-1) document.

| HttpCode | Error code              | Error message                    | Description                      |
| -------- | ----------------------- | -------------------------------- | -------------------------------- |
| 400      | invalidClientIdOrSecret | Invalid clientId or clientSecret | Invalid clientId or clientSecret |
