Java

  1. 下载样例项目 call-yidaapi-demo.zip,获取的应用accessKey和secretKey填入gateway.properties配置文件中。样例项目是独立的Spring boot项目,用户根据需求做取舍。
  2. Maven可能下载不到的包。sdk.zip

    pom依赖

    1. <dependency>
    2. <groupId>com.alibaba.platform.shared</groupId>
    3. <artifactId>xxpt.gateway.shared.client</artifactId>
    4. <version>1.1.0</version>
    5. </dependency>
    6. <dependency>
    7. <groupId>org.apache.httpcomponents</groupId>
    8. <artifactId>httpclient</artifactId>
    9. <version>4.5.2</version>
    10. </dependency>
    11. <dependency>
    12. <groupId>joda-time</groupId>
    13. <artifactId>joda-time</artifactId>
    14. <version>2.9.4</version>
    15. </dependency>
    16. <dependency>
    17. <groupId>org.apache.commons</groupId>
    18. <artifactId>commons-lang3</artifactId>
    19. <version>3.4</version>
    20. </dependency>

代码使用样例

POST模式发起客户端请求

  1. String api = "/rpc/enhancedUserQuery/findUsers/byEmpIds.json";
  2. PostClient postClient = ExecutableClient.getInstance().newPostClient(api);
  3. //加第一个工号
  4. postClient.addParameter("empIds", "xxxxx");
  5. //加第二个工号
  6. postClient.addParameter("empIds", "yyyyy");
  7. String apiResult = postClient.post();

GET 模式发起客户端请求

  1. String api = "/rpc/enhancedUserQuery/findUsers/byEmpIds.json";
  2. GetClient getClient = ExecutableClient.getInstance().newGetClient(api);
  3. //加第一个工号
  4. getClient.addParameter("empIds", "xxxxx");
  5. //加第二个工号
  6. getClient.addParameter("empIds", "yyyyy");
  7. String apiResult = getClient.get();
  1. 如果api的某些参数支持多值【数组】场景时可以多次调用addParameter方法,内部会实现追加然后组成数组

Python

SDK依赖

目前python项目调用buc的api服务,可以参照下面的api例子调用服务。
请注意:如果涉及多个参数,请对参数按照升序进行排序。

代码示例

  1. #!/usr/bin/env python
  2. # coding=UTF-8
  3. import urlparse
  4. import urllib
  5. import urllib2
  6. import datetime
  7. import time
  8. import random
  9. import base64
  10. import hmac
  11. import hashlib
  12. import uuid
  13. import socket
  14. class ExecutableClient(object):
  15. #API_KEY:你的应用的access_key
  16. API_KEY = ''
  17. #你的应用的secret_key
  18. API_SECRET_KEY = ''
  19. #API版本,默认1.0
  20. API_VERSION = '1.0'
  21. API_SERVER = ''
  22. #API name
  23. API_NAME = ''
  24. API_URL = API_SERVER + API_NAME
  25. def __init__(self):
  26. self.ipaddress = '127.0.0.1'#self.get_ip_address()
  27. self.method = 'GET'
  28. self.params = {}
  29. @classmethod
  30. def get_mac_address(cls):
  31. mac = uuid.UUID(int=uuid.getnode()).hex[-12:]
  32. return ":".join([mac[e:e + 2] for e in range(0, 11, 2)])
  33. @classmethod
  34. def get_ip_address(cls):
  35. # 获取本机电脑名
  36. my_name = socket.getfqdn(socket.gethostname())
  37. # 获取本机ip
  38. my_addr = socket.gethostbyname(my_name)
  39. return my_addr
  40. def get_signature(self, timestamp, nonce, url_info):
  41. bytes_to_sign = '{method}\n{timestamp}\n{nonce}\n{uri}\n{params}'.format(
  42. method=self.method,
  43. timestamp=timestamp,
  44. nonce=nonce,
  45. uri=url_info.path,
  46. params=urllib.unquote(url_info.query)
  47. )
  48. dig = hmac.new(self.API_SECRET_KEY, bytes_to_sign, digestmod=hashlib.sha256).digest()
  49. return base64.b64encode(dig)
  50. def set_ip_addr(self, ip):
  51. self.ipaddress = ip
  52. def set_access_key(self, api_key):
  53. self.API_KEY = api_key
  54. def set_secret_key(self, api_secret_key):
  55. self.API_SECRET_KEY = api_secret_key
  56. def set_domain_name(self, domain_name):
  57. self.API_SERVER = domain_name
  58. def set_api_name(self, api_name):
  59. self.API_NAME = api_name
  60. self.API_URL = self.API_SERVER + self.API_NAME
  61. def set_api_version(self,api_version):
  62. self.API_VERSION = api_version
  63. def add_params(self, field, value):
  64. value = value.encode('utf-8') if type(value) is unicode else value
  65. self.params[field] = value
  66. def executable_client(self, is_post=False):
  67. if is_post:
  68. self.method = 'POST'
  69. sorted_keys = [(x.lower(), x) for x in self.params.keys()]
  70. sorted_keys.sort()
  71. url_query = '&'.join(['{0}={1}'.format(sk[1], self.params[sk[1]])for sk in sorted_keys])
  72. url = self.API_URL
  73. if url_query:
  74. url += '?{QUERY}'.format(
  75. QUERY=url_query,
  76. )
  77. url_info = urlparse.urlparse(url)
  78. timestamp = datetime.datetime.now().strftime("%Y-%m-%dT%H:%M:%S.%f+08:00")
  79. nonce = '%s%s' % (int(time.time() * 1000), random.randint(1000, 9999))
  80. signature = self.get_signature(
  81. timestamp=timestamp,
  82. nonce=nonce,
  83. url_info=url_info
  84. )
  85. headers = {
  86. 'X-Hmac-Auth-Timestamp': timestamp,
  87. 'X-Hmac-Auth-Version': self.API_VERSION,
  88. 'X-Hmac-Auth-Nonce': nonce,
  89. 'apiKey': self.API_KEY,
  90. 'X-Hmac-Auth-Signature': signature,
  91. 'X-Hmac-Auth-IP': self.ipaddress,
  92. 'X-Hmac-Auth-MAC': self.get_mac_address()
  93. }
  94. if is_post:
  95. req = urllib2.Request(self.API_URL, urllib.urlencode(self.params), headers=headers)
  96. else:
  97. req = urllib2.Request(url, headers=headers)
  98. try:
  99. result = urllib2.urlopen(req).read()
  100. print result
  101. except urllib2.HTTPError, e:
  102. print e.getcode()
  103. print e.reason
  104. print e.geturl()
  105. print "-------------------------"
  106. print e.info()
  107. print e.read()
  108. # if __name__ == "__main__":
  109. # executableClient = ExecutableClient()
  110. # print 'Get user by empId......'
  111. # executableClient.add_params('loginWorkNo', '012662641024291838')
  112. # print '=========================='
  113. # print 'Get user by nickNameCn......'
  114. # executableClient.add_params('processCode', u'Matter-36fab45e-d8be-4ed9-9e15-f6369e595fa3')
  115. # executableClient.add_params('name', '012662641024291838')
  116. # # GET
  117. # executableClient.executable_client()
  118. # # POST
  119. # executableClient.executable_client(is_post=True)

php

SDK依赖

SDK-Demo:
epaasDemo.php

请注意:如果涉及多个参数,请对参数按照升序进行排序。

代码示例

  1. <?php
  2. /**
  3. * handle collabration with BUC
  4. * @author: piaoyu.ddh
  5. * @date: 2015/5/10
  6. * @version: 0.0.1
  7. */
  8. class BucBase {
  9. const API_SERVER = 'https://u-api.alibaba-inc.com';
  10. const API_SERVER_DEV = 'http://u-api.alibaba.net';
  11. const API_VERSION = '1.0';
  12. const API_TIMEOUT = 3; # unit: second
  13. private static $env = 'dev'; # prod by default
  14. private static $nic = 'eth0'; # for multiple NIC host
  15. //private static $nic = 'bond0'; # 阿里云实体机器的话要把这个静态变量初始化为 bond0 ,否则下面的getNicInfo 函数无法获取IP地址
  16. private static $apiKey = 'MOCK-Ad$Un328d(t_4CE&6&0@Zve123';
  17. private static $apiSecret = 'MOCKn0Ejx_Q$2MYU6f$_&Q406l$$Q2zC&d12345_';
  18. /**
  19. * init static members per config
  20. * this function should be customized per app
  21. */
  22. public static function init() {
  23. // normally configuration could be loaded hereby
  24. }
  25. /**
  26. * construct API signature
  27. * @param Refer to <a href="http://gitlab.alibaba-inc.com/buc/buc-security-api/blob/master/Guide.md">API开发指南</a> for details
  28. * @return signiture string
  29. */
  30. protected static function getSignature($method,$timestamp,$nonce,$uri,$params) {
  31. $bytes = sprintf("%s\n%s\n%s\n%s\n%s",$method,$timestamp,$nonce,$uri,$params);
  32. $hash = hash_hmac('sha256',$bytes,self::$apiSecret,true);
  33. return base64_encode($hash);
  34. }
  35. /**
  36. * retrieve NIC configuration for IP & MAC
  37. * Only linux system is supported so far
  38. * @return array | false on error
  39. */
  40. protected static function getNicInfo() {
  41. $cmd = sprintf('/sbin/ifconfig %s|/usr/bin/head -2',self::$nic);
  42. $output = `$cmd`;
  43. if ( !$output ) {
  44. return false;
  45. }
  46. $lines = explode("\n",$output);
  47. $ret = array();
  48. foreach( $lines as $line ) {
  49. $tmp = array();
  50. if ( preg_match('/HWaddr ((?:[0-9A-Fa-f]{2}:)+[0-9A-Fa-f]{2})/',$line,$tmp) ) {
  51. $ret['mac'] = $tmp[1];
  52. continue;
  53. }
  54. if ( preg_match('/inet addr:((?:[0-9]{1,3}\.)+[0-9]{1,3})/',$line,$tmp) ) {
  55. $ret['ip'] = $tmp[1];
  56. continue;
  57. }
  58. }
  59. return $ret;
  60. }
  61. /**
  62. * construct server per configuration
  63. * @return server string
  64. */
  65. protected static function getServer() {
  66. $server = self::API_SERVER;
  67. if ( 'dev' == self::$env ) {
  68. $server = self::API_SERVER_DEV;
  69. }
  70. return $server;
  71. }
  72. /**
  73. * construct headers for BUC API request
  74. * @param $api API path to be queried (w/o server part)
  75. * @param $method HTTP method. So far only GET & POST are supported
  76. * @param $params As it is. Key & value should be UTF-8 encoded w/o url encoding
  77. * @return header array | false on error
  78. */
  79. protected static function getHeaders($api,$method,$params) {
  80. if ( !$api || !$method || !$params ) {
  81. return false;
  82. }
  83. $addr = self::getNicInfo();
  84. if ( !$addr ) {
  85. return false;
  86. }
  87. $timestamp = strftime('%Y-%m-%dT%H:%M:%S.000+08:00');
  88. $nonce = sprintf('%d000%d',time(),rand(1000, 9999));
  89. ksort($params,SORT_STRING);
  90. $ret = array();
  91. foreach( $params as $k => $v ) {
  92. $ret[] = sprintf('%s=%s',$k,$v);
  93. }
  94. $sig = self::getSignature($method,$timestamp,$nonce,$api,implode('&',$ret));
  95. return array(
  96. 'X-Hmac-Auth-Timestamp' => $timestamp,
  97. 'X-Hmac-Auth-Version' => self::API_VERSION,
  98. 'X-Hmac-Auth-Nonce' => $nonce,
  99. 'apiKey' => self::$apiKey,
  100. 'X-Hmac-Auth-Signature' => $sig,
  101. 'X-Hmac-Auth-IP' => $addr['ip'],
  102. 'X-Hmac-Auth-MAC' => $addr['mac']
  103. );
  104. }
  105. /**
  106. * encapsulation for BUC getUserByLoginName
  107. * @param $loginName The login name of the interesed user
  108. * @return array
  109. */
  110. protected static function getUserByLoginName($loginName) {
  111. $api = '/rpc/enhancedUserQuery/getUserByLoginName.json';
  112. $server = self::getServer();
  113. $url = sprintf('%s%s',$server,$api);
  114. $params = array('loginName' => $loginName);
  115. $headers = self::getHeaders($api,'POST',$params);
  116. return self::curlPost($url,$params,self::API_TIMEOUT,$headers);
  117. }
  118. /**
  119. * helper function for HTTP POST request
  120. */
  121. private static function curlPost($url, $params = array(), $timeout = 1, $headerAry = array()) {
  122. $ch = curl_init( );
  123. curl_setopt( $ch, CURLOPT_URL, $url);
  124. curl_setopt( $ch, CURLOPT_POST, 1);
  125. curl_setopt( $ch, CURLOPT_POSTFIELDS, $params);
  126. curl_setopt( $ch, CURLOPT_TIMEOUT, $timeout);
  127. curl_setopt( $ch, CURLOPT_SSL_CIPHER_LIST, 'TLSv1');
  128. curl_setopt( $ch, CURLOPT_HEADER, 0);
  129. curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1);
  130. if ($headerAry) {
  131. $tmp = array();
  132. foreach( $headerAry as $k => $v ) {
  133. $tmp[] = sprintf('%s: %s',$k,$v);
  134. }
  135. curl_setopt($ch, CURLOPT_HTTPHEADER, $tmp);
  136. }
  137. $data = curl_exec( $ch);
  138. $error = curl_error( $ch );
  139. curl_close( $ch );
  140. return $data;
  141. }
  142. }
  143. /**
  144. * static member initializer
  145. */
  146. BucBase::init();
  147. /**
  148. * BUC business logic for OPENDATA
  149. */
  150. class BucModel extends BucBase {
  151. /**
  152. * get user detail by email prefix
  153. * @param $prefix Email prefix for query
  154. * @return false | array()
  155. */
  156. public static function getUserDetail($prefix) {
  157. return parent::getUserByLoginName($prefix);
  158. }
  159. }
  160. BucModel::getUserDetail('piaoyu.ddh');

IOS

安装

  • 使用 CocoaPods(推荐)
    1. pod 'ALBUCSecurityGatewayHTTPClient'

    Demo

    demo-1

    1. [[ALBUCSecurityGatewayHTTPClient sharedSecurityGateway] setSecurityKey:@"Y02(n0Ejx_Q$2MYU6f$_&Q406l$$Q2zC&d4W6h$_"];
    2. [[ALBUCSecurityGatewayHTTPClient sharedSecurityGateway] setApiKey:@"BUC-Ad$Un6h8d(t_4CE&6&0@ZveUry"];
    3. [[ALBUCSecurityGatewayHTTPClient sharedSecurityGateway] postPath:@"/rpc/enhancedUserQuery/getUserByEmpId.json" parameters:@{ @"empId" : workId } success:
    4. ^(AFHTTPRequestOperation* operation, id responseObject) {
    5. //do stuffs when success
    6. }
    7. failure:^(AFHTTPRequestOperation* operation, NSError* error) {
    8. // do stuffs when fail
    9. }];

    demo-2

    在命令行输入
    1. git clone git@gitlab.alibaba-inc.com:xiaotian.lxt/ALBUCSecurityGatewayHTTPClient.git
    2. cd ALBUCSecurityGatewayHTTPClient
    3. pod install
    4. open ALBUCSecurityGatewayHTTPClient.xcworkspace
    运行即可.

备注:

  1. nodejs和C#暂不支持。