文档

集成SDK

更新时间:
一键部署

集成阿里云SDK主要有三步:设置访问凭据、引入阿里云SDK、编写调用代码。本文将以Node.js语言调用短信服务 SMS(Short Message Service)的发送短信接口为例,讲解完整的集成步骤。

环境要求

Node.js >= 8.x

第一步:设置访问凭据

调用阿里云OpenAPI通常需要设置访问密钥(AccessKey),详情参见凭据。为了避免凭据泄露,常见的方案是将其写入到环境变量中,更多安全方案请参见凭据的安全使用方案。本案例以设置环境变量为例:

配置环境变量ALIBABA_CLOUD_ACCESS_KEY_IDALIBABA_CLOUD_ACCESS_KEY_SECRET

  • Linux和macOS系统配置方法

    命令行终端执行以下命令:

    export ALIBABA_CLOUD_ACCESS_KEY_ID=<ACCESS_KEY_ID>
    export ALIBABA_CLOUD_ACCESS_KEY_SECRET=<ACCESS_KEY_SECRET>

    <access_key_id>需替换为已准备好的AccessKey ID,<access_key_secret>替换为AccessKey Secret。

  • Windows系统配置方法

    1. 新建环境变量文件,添加环境变量ALIBABA_CLOUD_ACCESS_KEY_IDALIBABA_CLOUD_ACCESS_KEY_SECRET,并写入已准备好的AccessKey ID和AccessKey Secret。

第二步:引入SDK

阿里云SDK支持泛化与特化两种方式调用OpenAPI,详情参见泛化调用与特化调用,不同的调用方式需要引入的SDK也不同。

特化调用

您可以访问OpenAPI门户网站,搜索您需要的产品,查看产品支持的SDK语言及安装方法,然后在您的项目中引入SDK。本案例的SDK获取步骤如下:

  1. 访问短信服务SDK

  2. 所有语言栏目中选择您需要的SDK语言。

  3. 选择您需要的安装方式,将代码复制到您的项目中。

  4. 在您的项目中载入该依赖包。

其Node.js语言安装产品如下:

npm install --save @alicloud/dysmsapi20170525@2.0.24

泛化调用

泛化调用方式不依赖任何一个产品的SDK,只依赖如下核心包@alicloud/openapi-client。其Node.js语言安装配置文件如下,最新版本请参见alicloud/openapi-client

npm i @alicloud/openapi-client

第三步:调用OpenAPI

您可以根据快速开始文档下载示例代码。接下来我们以特化调用代码为例,讲解调用过程。如果您选择泛化调用方案,请打开Common模式生成示例的开关,更多信息请参见泛化调用与特化调用

初始化请求客户端

方法一:使用AK初始化

import Dysmsapi20170525, * as $Dysmsapi20170525 from '@alicloud/dysmsapi20170525';
import OpenApi, * as $OpenApi from '@alicloud/openapi-client';

static createClient(){
	let config = new $OpenApi.Config({
	// 必填,您的 AccessKey ID
	accessKeyId: process.env.ALIBABA_CLOUD_ACCESS_KEY_ID,
	// 必填,您的 AccessKey Secret
	accessKeySecret: process.env.ALIBABA_CLOUD_ACCESS_KEY_SECRET,
});
// Endpoint 请参考 https://api.aliyun.com/product/Dysmsapi
config.endpoint = `dysmsapi.aliyuncs.com`;
// 特化请求客户端
const dysmsapiClient = new Dysmsapi20170525(config);
}

方法二:使用STS Token初始化

import Dysmsapi20170525, * as $Dysmsapi20170525 from '@alicloud/dysmsapi20170525';
import OpenApi, * as $OpenApi from '@alicloud/openapi-client';

static createClient(){
	let config = new $OpenApi.Config({
	// 必填,您的 AccessKey ID
	accessKeyId: process.env.ALIBABA_CLOUD_ACCESS_KEY_ID,
	// 必填,您的 AccessKey Secret
	accessKeySecret: process.env.ALIBABA_CLOUD_ACCESS_KEY_SECRET,
  // 必填,您的STS Token
  securityToken: process.env.ALIBABA_CLOUD_SECURITY_TOKEN,
});
// Endpoint 请参考 https://api.aliyun.com/product/Dysmsapi
config.endpoint = `dysmsapi.aliyuncs.com`;
// 特化请求客户端
const dysmsapiClient = new Dysmsapi20170525(config);
}

方法三:使用Credentials工具初始化

TypeScript 版本:

import Dysmsapi20170525, * as $Dysmsapi20170525 from '@alicloud/dysmsapi20170525';
import * as $OpenApi from '@alicloud/openapi-client';
import Credential, { Config } from '@alicloud/credentials';

static async main(): Promise<void> {
	// 使用默认凭证初始化Credentials Client
	const cred = new Credential();
	let config = new $OpenApi.Config({
	// 使用Credentials配置凭证
	credential: cred,
});
// 若接入dysmsapi即短信服务,则初始化dysmsapi产品包的Client类
config.endpoint = 'dysmsapi.aliyuncs.com'
// 特化请求客户端
const dysmsapiClient = new Dysmsapi20170525(config);
}

JavaScript 版本:

const { default: Dysmsapi20170525 } = require('@alicloud/dysmsapi20170525');
const { Config } = require('@alicloud/openapi-client');
const { default: Credential } = require('@alicloud/credentials')

async function main() {
  const config = new Config({
    credential: new Credential(),
  });
  const dysmsapiClient = new Dysmsapi20170525(config);
}

创建请求对象&运行时配置

通常您需要根据业务的实际需要传入参数,您也可自定义运行时配置。

// 创建请求对象并设置入参
let sendSmsRequest = new $Dysmsapi20170525.SendSmsRequest({
  phoneNumbers: "<YOUR_VALUE>",
  signName: "<YOUR_VALUE>",
});
// 创建运行时配置对象
let runtime = new $Util.RuntimeOptions({ });

发起请求

升级版 SDK 中每个产品的 Client 包含了所有的 OpenAPI,所以可以指定 OpenAPI 请求方法来请求,其方法名对应 OpenAPI 首字母小写,一般有三个:

  • <接口名称>:使用默认的运行时配置发起接口调用,可以不用传入运行参数的请求方法。

    • TypeScript 版:

      import * as $OpenApi from '@alicloud/openapi-client';
      // 引入 Credentials
      import Credential from '@alicloud/credentials';
      import Dysmsapi20170525, * as $Dysmsapi20170525 from '@alicloud/dysmsapi20170525';
      
      export default class Client {
        static async main(): Promise<void> {
          // 使用默认凭证初始化Credentials Client
          const credentialClient = new Credential();
          const smsConfig = new $OpenApi.Config({
            // 使用Credentials配置凭证
            credential: credentialClient,
            // 访问的区域
            regionId: 'cn-hangzhou'
          });
          const smsClient = new Dysmsapi20170525(smsConfig)
          // 构造请求对象
          const sendSmsRequest = new $Dysmsapi20170525.SendSmsRequest([])
          // 获取响应对象
          const request = smsClient.sendSms(sendSmsRequest)
          console.log(request);
        }
      }
    • JavaScript 版:

      const { default: Ecs20140526, ModifySecurityGroupRuleRequest } = require('@alicloud/ecs20140526');
      const { Config } = require('@alicloud/openapi-client');
      const { default: Credential } = require('@alicloud/credentials')
      
      async function main() {
           const smsConfig = new Config({
             // 使用Credentials配置凭证
             credential: new Credential(),
            // 访问的区域
            regionId: 'cn-hangzhou'
          });
          const smsClient = new Ecs20140526(smsConfig);
          const request = new ModifySecurityGroupRuleRequest({
            resourceOwnerAccount: 'test',
            resourceOwnerId: 1,
            ownerAccount: 'test',
            regionId: 'test',
          });
          const resp = await smsClient.modifySecurityGroupRule(request);
          console.log(resp.headers);
          console.log(resp.body);
      }
  • <接口名称>WithOptions:可配置自定义运行时参数发起接口调用,更多运行时参数配置请参见进阶配置

    • TypeScript 版:

      import * as $OpenApi from '@alicloud/openapi-client';
      // 引入 Credentials
      import Credential from '@alicloud/credentials';
      import Dysmsapi20170525, * as $Dysmsapi20170525 from '@alicloud/dysmsapi20170525';
      import * as Util from '@alicloud/tea-util';
      
      export default class Client {
        static async main(): Promise<void> {
          // 使用默认凭证初始化Credentials Client
          const credentialClient = new Credential();
          const smsConfig = new $OpenApi.Config({
            // 使用Credentials配置凭证
            credential: credentialClient,
            // 访问的区域
            regionId: 'cn-hangzhou'
          });
          const smsClient = new Dysmsapi20170525(smsConfig)
          // 创建RuntimeObject实例并设置运行参数。
          const runtime = new Util.RuntimeOptions({});
          // 构造请求对象
          const sendSmsRequest = new $Dysmsapi20170525.SendSmsRequest([])
          // 获取响应对象
          const request = smsClient.sendSmsWithOptions(sendSmsRequest,runtime)
          console.log(request);
        }
      }
    • JavaScript 版

      const { default: Ecs20140526, ModifySecurityGroupRuleRequest } = require('@alicloud/ecs20140526');
      const { Config } = require('@alicloud/openapi-client');
      const { RuntimeOptions } = require('@alicloud/tea-util');
      const { default: Credential } = require('@alicloud/credentials')
      
      async function main() {
        const smsConfig = new Config({
          credential: new Credential(),
          // 访问的区域
          regionId: 'cn-hangzhou'
        });
        const smsClient = new Ecs20140526(smsConfig);
        const request = new ModifySecurityGroupRuleRequest({
          resourceOwnerAccount: '<test>',
          resourceOwnerId: 1,
          ownerAccount: '<test>',
          regionId: '<test>',
        });
        // 创建RuntimeObject实例并设置运行参数。
        const runtime = new RuntimeOptions({});
        const resp = await smsClient.modifySecurityGroupRuleWithOptions(request, runtime);
        console.log(resp.headers);
        console.log(resp.body);
      }
  • <接口名称>Advance:专门用于应对直接上传Object 的场景,该方法默认需要传入运行时参数。下述示例以视觉智能开放平台人体人脸产品为例介绍SDK如何使用本地文件上传调用 API。

    // 人体人脸依赖信息
    npm install @alicloud/facebody20191230@4.0.8
    • TypeScript 版:

      import Facebody20191230, * as $Facebody20191230 from '@alicloud/facebody20191230';
      import * as $OpenApi from '@alicloud/openapi-client';
      import * as $Util from '@alicloud/tea-util';
      import {createReadStream} from 'fs';
      import Credential from '@alicloud/credentials';
      
      export default class Client {
        static async main(): Promise<void> {
          // 使用默认凭证初始化Credentials Client
          const credentialClient = new Credential();
          const facebodyConfig = new $OpenApi.Config({
            // 使用Credentials配置凭证
            credential: credentialClient,
            // 访问的区域,facebody目前仅开通上海地域
            regionId: 'cn-shanghai',
          });
          const facebodyClient = new Facebody20191230(facebodyConfig);
          const request = new $Facebody20191230.DetectBodyCountAdvanceRequest({
            imageURLObject: createReadStream('<YOUR-FILE-PATH>'),
          });
          // 创建RuntimeObject实例并设置运行参数。
          const runtime = new $Util.RuntimeOptions({});
          const resp = await facebodyClient.DetectBodyCountAdvance(request, runtime);
          console.log(resp.headers);
          console.log(resp.body);
        }
      }
    • JavaScript 版

      const { default: Facebody20191230, DetectBodyCountAdvanceRequest } = require('@alicloud/facebody20191230');
      const { Config } = require('@alicloud/openapi-client');
      const { RuntimeOptions } = require('@alicloud/tea-util');
      const { createReadStream } = require('fs');
      const { default: Credential } = require('@alicloud/credentials')
      
      async function main() {
        const facebodyConfig = new Config({
          credential: new Credential(),
          // 访问的区域,facebody目前仅开通上海地域
          regionId: 'cn-shanghai'
        });
        const facebodyClient = new Facebody20191230(facebodyConfig);
        const request = new DetectBodyCountAdvanceRequest({
          imageURLObject: createReadStream('<YOUR-FILE-PATH>'),
        });
        // 创建RuntimeObject实例并设置运行参数。
        const runtime = new RuntimeOptions({});
        const resp = await facebodyClient.detectBodyCountAdvance(request, runtime);
        console.log(resp.headers);
        console.log(resp.body);
      }
      main()
  • 本页导读 (1)
文档反馈