An access token is a credential that you can use to call the Intelligent Speech Interaction services. This topic describes how to obtain an access token.
Prerequisites
The AccessKey ID and the AccessKey secret of your account are obtained. For more information, see Activate Intelligent Speech Interaction.
You can use Alibaba Cloud SDK to request an access token from the cloud. When you send this request, you must provide the AccessKey ID and the AccessKey secret of your Alibaba Cloud account. You can also send a token request to the server from your client to obtain an access token. For more information, see Send an HTTP or HTTPS request to obtain an access token.
Before you use an access token, you must check the ExpireTime parameter to confirm the timestamp that indicates the validity period of the access token. If the access token expires, you must obtain a new access token.
Procedure
Log on to the Intelligent Speech Interaction console.
On the Overview page, click Obtain AccessToken in the upper-right corner.
You can use the SDK to call and test the Intelligent Speech Interaction services with the access token. This access token is for testing purposes only.
The following code provides a sample response:
{ "NlsRequestId": "aed8c1af075347819118ff6bf811****", "RequestId": "0989F63E-5069-4AB0-822B-5BD2D953****", "Token": { "ExpireTime": 1527592757, "Id": "124fc7526f434b8c8198d6196b0a****", "UserId": "12345678****" } }
Parameters in the sample response:
The Id parameter indicates the ID of the access token that is specified in the request.
The ExpireTime parameter indicates a timestamp, which represents the validity period of the access token. Unit: seconds. For example, a value of
1527592757
indicates that the access token is valid before19:19:17 (UTC+8) on May 29, 2018
.
Troubleshooting
If an error occurs when you use the SDK to obtain an access token, troubleshoot the error. For more information, see List of error codes.
The most common error is
Request was denied due to user flow control.
This error indicates that the API request is rejected by Alibaba Cloud API Gateway because the frequency at which token requests are sent exceeds the upper limit. To avoid this error, do not send requests to obtain access tokens at a high frequency.After you obtain an access token, you can use it multiple times within the validity period of the access token. You can use the access token across threads, processes, or servers.
Obtain an access token on a mobile client
We recommend that you integrate Alibaba Cloud SDK for Java into your server to obtain an access token.
Integrate Alibaba Cloud SDK for Java into the server. Then, the server sends an HTTP GET request to call the */gettoken method to obtain an access token.
The client calls the */gettoken method to obtain the access token and the validity period from the server.
The client uses the access token to access the Intelligent Speech Interaction services. Before the client calls an Intelligent Speech Interaction service, it sends a request to obtain an access token.
The client stores the access token in the local cache. Before the access token expires, the client can continue to use the cached access token to access the Intelligent Speech Interaction services. If the cached access token expires, the client obtains a new access token from the server and updates the local cache.
Use the SDK to obtain an access token
Demo for Java
Download the latest version of Alibaba Cloud SDK for Java from the Maven server. Download the ZIP file of the demo.
<dependency>
<groupId>com.alibaba.nls</groupId>
<artifactId>nls-sdk-common</artifactId>
<version>2.1.6</version>
</dependency>
AccessToken token = new AccessToken("your akID", "your akSecret");
token.apply();
String accessToken = token.getToken();
long expireTime = token.getExpireTime();
Run the preceding Java code on the server. An Android user must run the code on the server or a PC client to obtain an access token. To ensure data security, we recommend that you set up a server and use the client to request an access token from the server.
Demo for C++
Install the following tools in Linux:
glibc 2.5 or later
Ccc4 or Ccc5
Install the following tool in Windows: Visual Studio 2013 or Visual Studio 2015.
Create a project in Windows.
Compile the demo.
Assume that the demo is extracted to the
path/to
directory. Run the following commands on the Linux terminal to compile and run the demo.If the operating system supports CMake:
Make sure that CMake 2.4 or later is installed in the Linux terminal.
Switch the directory:
cd path/to/sdk/lib
.Extract the file:
tar -zxvpf linux.tar.gz
.Switch the directory:
cd path/to/sdk
.Run the compilation script:
./build.sh
.Switch the directory:
cd path/to/sdk/demo
.Run the demo:
./tokenDemo <yourAccessKeySecret> <yourAccessKeyId>
.
If the operating system does not support CMake:
Switch the directory:
cd path/to/sdk/lib
.Extract the file:
tar -zxvpf linux.tar.gz
.Switch the directory:
cd path/to/sdk/demo
.Run the g++ command to compile the demo:
g++ -o tokenDemo tokenDemo.cpp -I path/to/sdk/include/ -L path/to/sdk/lib/linux -ljsoncpp -lssl -lcrypto -lcurl -luuid -lnlsCommonSdk -D_GLIBCXX_USE_CXX11_ABI=0
.Specify the library path:
export LD_LIBRARY_PATH=path/to/sdk/lib/linux/
.Run the demo:
./tokenDemo <yourAccessKeySecret> <yourAccessKeyId>
.
Obtain an access token.
The following sample code provides an example on how to obtain an access token:
#include <iostream> #include "Token.h" using std::cout; using std::endl; using namespace AlibabaNlsCommon; // Obtain the ID of the access token. int getTokenId(const char* keySecret, const char* keyId) { NlsToken nlsTokenRequest; / *Set the AccessKey secret of your Alibaba Cloud account.* / nlsTokenRequest.setKeySecret(keySecret); / *Set the AccessKey ID of your Alibaba Cloud account.* / nlsTokenRequest.setAccessKeyId(keyId); /* Obtain the access token. If a value of 0 is returned, the request is successful. If a value of -1 is returned, the request failed. * / if (-1 == nlsTokenRequest.applyNlsToken()) { cout << "Failed: " << nlsTokenRequest.getErrorMsg() << endl; / *The cause of the failure.* / return -1; } else { cout << "TokenId: " << nlsTokenRequest.getToken() << endl; / *The ID of the access token.* / cout << "TokenId expireTime: " << nlsTokenRequest.getExpireTime() << endl; / *The timestamp that indicates the validity period of the access token in seconds.* / return 0; } }
Demo for PHP
The latest version of Alibaba Cloud SDK for PHP is used in this example. For more information, see Alibaba Cloud SDK for PHP. You can continue to use an earlier version of Alibaba Cloud SDK for PHP. However, we recommend that you update to the latest version. For more information, see aliyun-openapi-php-sdk.
Before you install Alibaba Cloud SDK for PHP, make sure that the environment uses PHP V5.5 or a later version. For more information, see Install Alibaba Cloud SDK for PHP.
Procedure:
Create a global client.
Create an API request and configure parameters.
Send the API request and process the response or exception.
<?php
require __DIR__ . '/vendor/autoload.php';
use AlibabaCloud\Client\AlibabaCloud;
use AlibabaCloud\Client\Exception\ClientException;
use AlibabaCloud\Client\Exception\ServerException;
/**
* Step 1: Create a global client.
* Use the AccessKey ID and AccessKey secret of a RAM user to complete the authentication.
*/
AlibabaCloud::accessKeyClient(
"<your-access-key-id>",
"<your-access-key-secret>")
->regionId("ap-southeast-1")
->asDefaultClient();
try {
$response = AlibabaCloud::nlsCloudMeta()
->v20180518()
->createToken()
->request();
print $response . "\n";
$token = $response["Token"];
if ($token != NULL) {
print "Token obtained:\n";
print_r($token);
}
else {
print "Failed to obtain the token\n";
}
} catch (ClientException $exception) {
// Obtain the error message.
print_r($exception->getErrorMessage());
} catch (ServerException $exception) {
// Obtain the error message.
print_r($exception->getErrorMessage());
}
Use the CommonRequest method to obtain an access token
If you use Alibaba Cloud SDK to obtain an access token, we recommend that you call API operations in a remote procedure call (RPC) style. To initiate a common API request in an RPC style, you must specify the following parameters.
Parameter | Value | Description |
domain | nlsmeta.ap-southeast-1.aliyuncs.com | The endpoint of Intelligent Speech Interaction. The value is fixed. |
region_id | ap-southeast-1 | The region ID of the requested Intelligent Speech Interaction service. The value is fixed. |
action | CreateToken | The API operation that you want to call. The value is fixed. |
version | 2019-07-17 | The version number of the API. The value is fixed. |
Demo for Java
Add Java dependencies.
Add the core library (V3.7.1) and the fastjson library of Alibaba Cloud SDK for Java.
<dependency> <groupId>com.aliyun</groupId> <artifactId>aliyun-java-sdk-core</artifactId> <version>3.7.1</version> </dependency> <!-- http://mvnrepository.com/artifact/com.alibaba/fastjson --> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.83</version> </dependency>
Obtain an access token.
The following sample code provides an example on how to obtain an access token:
import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import com.aliyuncs.CommonRequest; import com.aliyuncs.CommonResponse; import com.aliyuncs.DefaultAcsClient; import com.aliyuncs.IAcsClient; import com.aliyuncs.exceptions.ClientException; import com.aliyuncs.http.MethodType; import com.aliyuncs.http.ProtocolType; import com.aliyuncs.profile.DefaultProfile; import java.text.SimpleDateFormat; import java.util.Date; public class CreateTokenDemo { // The region ID of the requested Intelligent Speech Interaction service. private static final String REGIONID = "ap-southeast-1"; // The endpoint of the requested Intelligent Speech Interaction service. private static final String DOMAIN = "nlsmeta.ap-southeast-1.aliyuncs.com"; // The version number of the API. private static final String API_VERSION = "2019-07-17"; // The API operation that you want to call. private static final String REQUEST_ACTION = "CreateToken"; // The response parameters. private static final String KEY_TOKEN = "Token"; private static final String KEY_ID = "Id"; private static final String KEY_EXPIRETIME = "ExpireTime"; public static void main(String args[]) throws ClientException { if (args.length < 2) { System.err.println("CreateTokenDemo need params: <AccessKey Id> <AccessKey Secret>"); System.exit(-1); } String accessKeyId = args[0]; String accessKeySecret = args[1]; // Create a DefaultAcsClient instance and initialize the instance. DefaultProfile profile = DefaultProfile.getProfile( REGIONID, accessKeyId, accessKeySecret); IAcsClient client = new DefaultAcsClient(profile); CommonRequest request = new CommonRequest(); request.setDomain(DOMAIN); request.setVersion(API_VERSION); request.setAction(REQUEST_ACTION); request.setMethod(MethodType.POST); request.setProtocol(ProtocolType.HTTPS); CommonResponse response = client.getCommonResponse(request); System.out.println(response.getData()); if (response.getHttpStatus() == 200) { JSONObject result = JSON.parseObject(response.getData()); String token = result.getJSONObject(KEY_TOKEN).getString(KEY_ID); long expireTime = result.getJSONObject(KEY_TOKEN).getLongValue(KEY_EXPIRETIME); System.out.println("Obtained token: " + token + ", Timestamp that indicates the validity period (unit: seconds): " + expireTime); // Convert the 10-digit timestamp to a time in UTC+8. String expireDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(expireTime * 1000)); System.out.println("Validity period of the access token in UTC+8: " + expireDate); } else { System.out.println("Failed to obtain the token.") } } }
Demo for Python
Use pip to install the SDK.
Run the following command to install Alibaba Cloud SDK for Python V2.13.3:
pip install aliyun-python-sdk-core==2.13.3 # Install the core library of Alibaba Cloud SDK for Python.
Obtain an access token.
Sample code:
# -*- coding: utf8 -*- from aliyunsdkcore.client import AcsClient from aliyunsdkcore.request import CommonRequest # Create an AcsClient instance. client = AcsClient( "<Your AccessKey ID>", "<Your AccessKey secret>", "ap-southeast-1" ); # Create a request and configure request parameters. request = CommonRequest() request.set_method('POST') request.set_domain('nlsmeta.ap-southeast-1.aliyuncs.com') request.set_version('2019-07-17') request.set_action_name('CreateToken') response = client.do_action_with_exception(request) print(response)
Demo for GO
Sample code:
package main
import (
"fmt"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk"
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
)
func main() {
client, err := sdk.NewClientWithAccessKey("ap-southeast-1", "<yourAccessKey Id>", "<yourAccessKey Secret>")
if err != nil {
panic(err)
}
request := requests.NewCommonRequest()
request.Method = "POST"
request.Domain = "nlsmeta.ap-southeast-1.aliyuncs.com"
request.ApiName = "CreateToken"
request.Version = "2019-07-17"
response, err := client.ProcessCommonRequest(request)
if err != nil {
panic(err)
}
fmt.Print(response.GetHttpStatus())
fmt.Print(response.GetHttpContentString())
}
Demo for Node.js
Install the SDK for Node.js.
We recommend that you use npm to install the dependent modules of Node.js. All official Alibaba Cloud SDKs for Node.js are stored in the @alicloud directory.
For example, the SDK for Node.js is downloaded to the
/path/to/aliyun-openapi-Node.js-sdk
folder. When you develop an application based on the SDK core library, run the following command to install the @alicloud/pop-core module.The
--save
option in the following command writes the module to the package.json file of the application as a dependent module:npm install @alicloud/pop-core --save
NoteYou can also download the SDK from GitHub. For more information, see Download the SDK from GitHub.
Obtain an access token.
Sample code:
var RPCClient = require('@alicloud/pop-core').RPCClient; var client = new RPCClient({ accessKeyId: '<yourAccessKey Id>', accessKeySecret: '<yourAccessKey Secret>', endpoint: 'http://nlsmeta.ap-southeast-1.aliyuncs.com', apiVersion: '2019-07-17' }); // => returns Promise // => request(Action, params, options) client.request('CreateToken').then((result) => { console.log(result.Token); });
Demo for .NET
Install Alibaba Cloud SDK for .NET.
In the .NET demo that is used to obtain an access token, the CommonRequest method of Alibaba Cloud SDK for. NET is used to send pctowap open platform (POP) API requests in an RPC style. For more information about Alibaba Cloud SDK for .NET, see Use the SDK for .NET.
For more information about how to use the CommonRequest method of Alibaba Cloud SDK for .NET, see Use CommonRequest to call API operations.
You need to only install the core library of Alibaba Cloud SDK for .NET. If you want to install Alibaba Cloud SDK for .NET, you can add the reference to a Dynamic Link Library (DLL) file or a project. For more information, see Use the SDK for .NET.
Obtain an access token.
Sample code:
using System; using Aliyun.Acs.Core; using Aliyun.Acs.Core.Exceptions; using Aliyun.Acs.Core.Profile; class Sample { static void Main(string[] args) { // Create a client instance to initiate a request. IClientProfile profile = DefaultProfile.GetProfile( "ap-southeast-1", "<yourAccessKey Id>", "<yourAccessKey Secret>"); DefaultAcsClient client = new DefaultAcsClient(profile); try { // Create a request. CommonRequest request = new CommonRequest(); request.Domain = "nlsmeta.ap-southeast-1.aliyuncs.com"; request.Version = "2019-07-17"; // This API request is in an RPC style. Set the Action parameter to the RPC API operation that you want to call. request.Action = "CreateToken"; // Initiate the request and obtain a response. CommonResponse response = client.GetCommonResponse(request); System.Console.WriteLine(response.Data); }sl catch (ServerException ex) { System.Console.WriteLine(ex.ToString()); } catch (ClientException ex) { System.Console.WriteLine(ex.ToString()); } } }