> ## 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.

# Mendapatkan access token sebuah aplikasi

> Panggil API ini untuk mendapatkan access_token sebuah aplikasi di DingTalk guna mengautentikasi panggilan API berikutnya secara aman dan efisien.

## Deskripsi panggilan API

Jika sebelumnya Anda menggunakan:

* Aplikasi internal: Memanggil API [Mendapatkan access token aplikasi internal](/id/open/development/obtain-the-access-token-of-an-internal-app#) untuk mendapatkan kredensial guna memanggil API organisasi Anda.
* Aplikasi perusahaan pihak ketiga: Memanggil API [Mendapatkan access token perusahaan yang diberi otorisasi](https://open.dingtalk.com/document/development/obtain-the-access-token-of-the-authorized-enterprise-1#) untuk mendapatkan kredensial guna memanggil API atas nama perusahaan yang memberikan otorisasi pada aplikasi pihak ketiga.

Kedua skenario ini kini disatukan menjadi satu API. Anda tidak perlu lagi membedakan tipe aplikasi. Panggil API ini langsung untuk mendapatkan Access Token guna memanggil API yang memerlukan izin aplikasi.

## Permintaan

| **Informasi dasar**         |                                                                                  |
| --------------------------- | -------------------------------------------------------------------------------- |
| URL HTTP                    | `https://api.dingtalk.io/v1.0/oauth2/{corpId}/token`                             |
| Metode HTTP                 | POST                                                                             |
| Tipe aplikasi yang didukung | appType-Aplikasi internal, appType-Aplikasi perusahaan pihak ketiga              |
| Persyaratan izin            | permission-qyapi\_base-Izin dasar yang diperlukan untuk memanggil API perusahaan |

### Parameter jalur

| Nama   | Tipe   | Wajib | Contoh           | Deskripsi                                                                                                                                                                                                                                         |
| ------ | ------ | ----- | ---------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| corpId | String | Ya    | ding9f\*\*\*\*41 | ID Organisasi. Masukkan corpId organisasi tempat aplikasi berjalan:   - Aplikasi internal: Masukkan corpId organisasi Anda. - Aplikasi perusahaan pihak ketiga: Masukkan corpId perusahaan yang diberi otorisasi dan telah mengaktifkan aplikasi. |

### Isi permintaan

| Nama           | Tipe   | Wajib | Contoh              | Deskripsi                        |
| -------------- | ------ | ----- | ------------------- | -------------------------------- |
| client\_id     | String | Ya    | suite123            | ClientID aplikasi.               |
| client\_secret | String | Ya    | \*\*\*\*\*\*\*\*    | ClientSecret aplikasi.           |
| grant\_type    | String | Ya    | client\_credentials | grant\_type: client\_credentials |

### Contoh permintaan

HTTP

```http theme={"theme":{"light":"github-light","dark":"github-dark"}}
POST /v1.0/oauth2/ding9f****41/token HTTP/1.1
Host:api.dingtalk.io
Content-Type:application/json

{
  "client_id" : "suite123",
  "client_secret" : "********",
  "grant_type" : "client_credentials"
}
```

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 {

    /**
     * <b>description</b> :
     * <p>Initialize the account Client with a Token</p>
     * @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.GetTokenRequest getTokenRequest = new com.aliyun.dingtalkoauth2_1_0.models.GetTokenRequest()
                .setClientId("suite123")
                .setClientSecret("********")
                .setGrantType("client_credentials");
        try {
            client.getToken("ding9f****41", getTokenRequest);
        } catch (TeaException err) {
            if (!com.aliyun.teautil.Common.empty(err.code) && !com.aliyun.teautil.Common.empty(err.message)) {
                // err contains code and message attributes that help developers 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 code and message attributes that help developers 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 os
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 with 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_token_request = dingtalkoauth_2__1__0_models.GetTokenRequest(
            client_id='suite123',
            client_secret='********',
            grant_type='client_credentials'
        )
        try:
            client.get_token('ding9f****41', get_token_request)
        except Exception as err:
            if not UtilClient.empty(err.code) and not UtilClient.empty(err.message):
                # err contains code and message attributes that help developers locate the issue
                pass

    @staticmethod
    async def main_async(
        args: List[str],
    ) -> None:
        client = Sample.create_client()
        get_token_request = dingtalkoauth_2__1__0_models.GetTokenRequest(
            client_id='suite123',
            client_secret='********',
            grant_type='client_credentials'
        )
        try:
            await client.get_token_async('ding9f****41', get_token_request)
        except Exception as err:
            if not UtilClient.empty(err.code) and not UtilClient.empty(err.message):
                # err contains code and message attributes that help developers locate the issue
                pass

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

PHP

```php 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\GetTokenRequest;

class Sample {

    /**
     * Initialize the account Client with 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();
        $getTokenRequest = new GetTokenRequest([
            "clientId" => "suite123",
            "clientSecret" => "********",
            "grantType" => "client_credentials"
        ]);
        try {
            $client->getToken("ding9f****41", $getTokenRequest);
        }
        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 code and message attributes that help developers 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 (
  "encoding/json"
  "strings"
  "fmt"
  "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"
)

// Description:
// 
// Initialize the account Client with 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
  }

  getTokenRequest := &dingtalkoauth2_1_0.GetTokenRequest{
    ClientId: tea.String("suite123"),
    ClientSecret: tea.String("********"),
    GrantType: tea.String("client_credentials"),
  }
  tryErr := func()(_e error) {
    defer func() {
      if r := tea.Recover(recover()); r != nil {
        _e = r
      }
    }()
    _, _err = client.GetToken(tea.String("ding9f****41"), getTokenRequest)
    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 code and message attributes that help developers locate the issue
    }

  }
  return _err
}

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

Node.js

```javascript theme={"theme":{"light":"github-light","dark":"github-dark"}}
'use strict';
// This file is auto-generated, don't edit it
const Util = require('@alicloud/tea-util');
const dingtalkoauth2_1_0 = require('@alicloud/dingtalk/oauth2_1_0');
const OpenApi = require('@alicloud/openapi-client');
const Tea = require('@alicloud/tea-typescript');

class Client {

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

  static async main(args) {
    let client = Client.createClient();
    let getTokenRequest = new dingtalkoauth2_1_0.GetTokenRequest({
      clientId: 'suite123',
      clientSecret: '********',
      grantType: 'client_credentials',
    });
    try {
      await client.getToken('ding9f****41', getTokenRequest);
    } catch (err) {
      if (!Util.default.empty(err.code) && !Util.default.empty(err.message)) {
        // err contains code and message attributes that help developers locate the issue
      }

    }    
  }

}

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

C#

```csharp 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 
    {

        /// <term><b>Description:</b></term>
        /// <description>
        /// <para>Initialize the account Client with a Token</para>
        /// </description>
        /// 
        /// <returns>
        /// Client
        /// </returns>
        /// 
        /// <term><b>Exception:</b></term>
        /// 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.GetTokenRequest getTokenRequest = new AlibabaCloud.SDK.Dingtalkoauth2_1_0.Models.GetTokenRequest
            {
                ClientId = "suite123",
                ClientSecret = "********",
                GrantType = "client_credentials",
            };
            try
            {
                client.GetToken("ding9f****41", getTokenRequest);
            }
            catch (TeaException err)
            {
                if (!AlibabaCloud.TeaUtil.Common.Empty(err.Code) && !AlibabaCloud.TeaUtil.Common.Empty(err.Message))
                {
                    // err contains code and message attributes that help developers 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 code and message attributes that help developers locate the issue
                }
            }
        }

    }
}
```

## Respons

### Isi respons

| Nama          | Tipe    | Contoh                           | Deskripsi                                   |
| ------------- | ------- | -------------------------------- | ------------------------------------------- |
| access\_token | String  | 2bf\*\*\*\*\*\*9be361a5084f1e2b8 | Kredensial akses.                           |
| expires\_in   | Integer | 7200                             | Masa berlaku kredensial akses, dalam detik. |

### Contoh isi respons

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

{
  "access_token" : "2bf******9be361a5084f1e2b8",
  "expires_in" : 7200
}
```

### Kode error

Jika terjadi error saat Anda memanggil API ini, lihat dokumen [Kode error global](/id/open/development/server-api-error-codes-1#) untuk menemukan solusi berdasarkan pesan error.

| HttpCode | Kode error             | Pesan error            | Deskripsi                                                      |
| -------- | ---------------------- | ---------------------- | -------------------------------------------------------------- |
| 400      | invalid.client         | invalid.client         | ClientID atau ClientSecret tidak valid.                        |
| 400      | unsupported.grant.type | unsupported.grant.type | grant\_type ini tidak didukung. Periksa parameter grant\_type. |
| 401      | unauthorized.client    | unauthorized.client    | Aplikasi tidak diberi otorisasi.                               |
| 500      | server.error           | server.error           | Terjadi error server yang tidak terduga.                       |
