Skip to main content

API call description

If you previously used: These two scenarios are now unified into a single API. You no longer need to distinguish between app types. Call this API directly to obtain the Access Token for calling APIs that require app permissions.

Request

Basic information
HTTP URLhttps://api.dingtalk.io/v1.0/oauth2/{corpId}/token
HTTP MethodPOST
Supported app typesappType-Internal app, appType-Third-party enterprise app
Permission requirementspermission-qyapi_base-Basic permission required to call enterprise APIs

Path parameter

NameTypeRequiredExampleDescription
corpIdStringYesding9f****41Organization ID. Enter the corpId of the organization in which the app runs: - Internal app: Enter the corpId of your organization. - Third-party enterprise app: Enter the corpId of the authorized enterprise that has enabled the app.

Request body

NameTypeRequiredExampleDescription
client_idStringYessuite123The ClientID of the app.
client_secretStringYes********The ClientSecret of the app.
grant_typeStringYesclient_credentialsGrant type: client_credentials

Request example

HTTP
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
// 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
# -*- 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

// 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
// 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
'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#
// 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
                }
            }
        }

    }
}

Response

Response body

NameTypeExampleDescription
access_tokenString2bf******9be361a5084f1e2b8Access credential.
expires_inInteger7200Validity period of the access credential, in seconds.

Response body example

HTTP/1.1 200 OK
Content-Type:application/json

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

Error codes

If an error occurs when you call this API, refer to the Global error codes document to find a solution based on the error message.
HttpCodeError codeError messageDescription
400invalid.clientinvalid.clientInvalid ClientID or ClientSecret.
400unsupported.grant.typeunsupported.grant.typeThis grant type is not supported. Check the grant type parameter.
401unauthorized.clientunauthorized.clientThe app is not authorized.
500server.errorserver.errorUnexpected server error.