Java
- 下载样例项目 call-yidaapi-demo.zip,获取的应用accessKey和secretKey填入gateway.properties配置文件中。样例项目是独立的Spring boot项目,用户根据需求做取舍。
- Maven可能下载不到的包。sdk.zip
pom依赖
<dependency><groupId>com.alibaba.platform.shared</groupId><artifactId>xxpt.gateway.shared.client</artifactId><version>1.1.0</version></dependency><dependency><groupId>org.apache.httpcomponents</groupId><artifactId>httpclient</artifactId><version>4.5.2</version></dependency><dependency><groupId>joda-time</groupId><artifactId>joda-time</artifactId><version>2.9.4</version></dependency><dependency><groupId>org.apache.commons</groupId><artifactId>commons-lang3</artifactId><version>3.4</version></dependency>
代码使用样例
POST模式发起客户端请求
String api = "/rpc/enhancedUserQuery/findUsers/byEmpIds.json";PostClient postClient = ExecutableClient.getInstance().newPostClient(api);//加第一个工号postClient.addParameter("empIds", "xxxxx");//加第二个工号postClient.addParameter("empIds", "yyyyy");String apiResult = postClient.post();
GET 模式发起客户端请求
String api = "/rpc/enhancedUserQuery/findUsers/byEmpIds.json";GetClient getClient = ExecutableClient.getInstance().newGetClient(api);//加第一个工号getClient.addParameter("empIds", "xxxxx");//加第二个工号getClient.addParameter("empIds", "yyyyy");String apiResult = getClient.get();
- 如果api的某些参数支持多值【数组】场景时可以多次调用addParameter方法,内部会实现追加然后组成数组
Python
SDK依赖
目前python项目调用buc的api服务,可以参照下面的api例子调用服务。
请注意:如果涉及多个参数,请对参数按照升序进行排序。
代码示例
#!/usr/bin/env python# coding=UTF-8import urlparseimport urllibimport urllib2import datetimeimport timeimport randomimport base64import hmacimport hashlibimport uuidimport socketclass ExecutableClient(object):#API_KEY:你的应用的access_keyAPI_KEY = ''#你的应用的secret_keyAPI_SECRET_KEY = ''#API版本,默认1.0API_VERSION = '1.0'API_SERVER = ''#API nameAPI_NAME = ''API_URL = API_SERVER + API_NAMEdef __init__(self):self.ipaddress = '127.0.0.1'#self.get_ip_address()self.method = 'GET'self.params = {}@classmethoddef get_mac_address(cls):mac = uuid.UUID(int=uuid.getnode()).hex[-12:]return ":".join([mac[e:e + 2] for e in range(0, 11, 2)])@classmethoddef get_ip_address(cls):# 获取本机电脑名my_name = socket.getfqdn(socket.gethostname())# 获取本机ipmy_addr = socket.gethostbyname(my_name)return my_addrdef get_signature(self, timestamp, nonce, url_info):bytes_to_sign = '{method}\n{timestamp}\n{nonce}\n{uri}\n{params}'.format(method=self.method,timestamp=timestamp,nonce=nonce,uri=url_info.path,params=urllib.unquote(url_info.query))dig = hmac.new(self.API_SECRET_KEY, bytes_to_sign, digestmod=hashlib.sha256).digest()return base64.b64encode(dig)def set_ip_addr(self, ip):self.ipaddress = ipdef set_access_key(self, api_key):self.API_KEY = api_keydef set_secret_key(self, api_secret_key):self.API_SECRET_KEY = api_secret_keydef set_domain_name(self, domain_name):self.API_SERVER = domain_namedef set_api_name(self, api_name):self.API_NAME = api_nameself.API_URL = self.API_SERVER + self.API_NAMEdef set_api_version(self,api_version):self.API_VERSION = api_versiondef add_params(self, field, value):value = value.encode('utf-8') if type(value) is unicode else valueself.params[field] = valuedef executable_client(self, is_post=False):if is_post:self.method = 'POST'sorted_keys = [(x.lower(), x) for x in self.params.keys()]sorted_keys.sort()url_query = '&'.join(['{0}={1}'.format(sk[1], self.params[sk[1]])for sk in sorted_keys])url = self.API_URLif url_query:url += '?{QUERY}'.format(QUERY=url_query,)url_info = urlparse.urlparse(url)timestamp = datetime.datetime.now().strftime("%Y-%m-%dT%H:%M:%S.%f+08:00")nonce = '%s%s' % (int(time.time() * 1000), random.randint(1000, 9999))signature = self.get_signature(timestamp=timestamp,nonce=nonce,url_info=url_info)headers = {'X-Hmac-Auth-Timestamp': timestamp,'X-Hmac-Auth-Version': self.API_VERSION,'X-Hmac-Auth-Nonce': nonce,'apiKey': self.API_KEY,'X-Hmac-Auth-Signature': signature,'X-Hmac-Auth-IP': self.ipaddress,'X-Hmac-Auth-MAC': self.get_mac_address()}if is_post:req = urllib2.Request(self.API_URL, urllib.urlencode(self.params), headers=headers)else:req = urllib2.Request(url, headers=headers)try:result = urllib2.urlopen(req).read()print resultexcept urllib2.HTTPError, e:print e.getcode()print e.reasonprint e.geturl()print "-------------------------"print e.info()print e.read()# if __name__ == "__main__":# executableClient = ExecutableClient()# print 'Get user by empId......'# executableClient.add_params('loginWorkNo', '012662641024291838')# print '=========================='# print 'Get user by nickNameCn......'# executableClient.add_params('processCode', u'Matter-36fab45e-d8be-4ed9-9e15-f6369e595fa3')# executableClient.add_params('name', '012662641024291838')# # GET# executableClient.executable_client()# # POST# executableClient.executable_client(is_post=True)
php
SDK依赖
SDK-Demo:
epaasDemo.php
代码示例
<?php/*** handle collabration with BUC* @author: piaoyu.ddh* @date: 2015/5/10* @version: 0.0.1*/class BucBase {const API_SERVER = 'https://u-api.alibaba-inc.com';const API_SERVER_DEV = 'http://u-api.alibaba.net';const API_VERSION = '1.0';const API_TIMEOUT = 3; # unit: secondprivate static $env = 'dev'; # prod by defaultprivate static $nic = 'eth0'; # for multiple NIC host//private static $nic = 'bond0'; # 阿里云实体机器的话要把这个静态变量初始化为 bond0 ,否则下面的getNicInfo 函数无法获取IP地址private static $apiKey = 'MOCK-Ad$Un328d(t_4CE&6&0@Zve123';private static $apiSecret = 'MOCKn0Ejx_Q$2MYU6f$_&Q406l$$Q2zC&d12345_';/*** init static members per config* this function should be customized per app*/public static function init() {// normally configuration could be loaded hereby}/*** construct API signature* @param Refer to <a href="http://gitlab.alibaba-inc.com/buc/buc-security-api/blob/master/Guide.md">API开发指南</a> for details* @return signiture string*/protected static function getSignature($method,$timestamp,$nonce,$uri,$params) {$bytes = sprintf("%s\n%s\n%s\n%s\n%s",$method,$timestamp,$nonce,$uri,$params);$hash = hash_hmac('sha256',$bytes,self::$apiSecret,true);return base64_encode($hash);}/*** retrieve NIC configuration for IP & MAC* Only linux system is supported so far* @return array | false on error*/protected static function getNicInfo() {$cmd = sprintf('/sbin/ifconfig %s|/usr/bin/head -2',self::$nic);$output = `$cmd`;if ( !$output ) {return false;}$lines = explode("\n",$output);$ret = array();foreach( $lines as $line ) {$tmp = array();if ( preg_match('/HWaddr ((?:[0-9A-Fa-f]{2}:)+[0-9A-Fa-f]{2})/',$line,$tmp) ) {$ret['mac'] = $tmp[1];continue;}if ( preg_match('/inet addr:((?:[0-9]{1,3}\.)+[0-9]{1,3})/',$line,$tmp) ) {$ret['ip'] = $tmp[1];continue;}}return $ret;}/*** construct server per configuration* @return server string*/protected static function getServer() {$server = self::API_SERVER;if ( 'dev' == self::$env ) {$server = self::API_SERVER_DEV;}return $server;}/*** construct headers for BUC API request* @param $api API path to be queried (w/o server part)* @param $method HTTP method. So far only GET & POST are supported* @param $params As it is. Key & value should be UTF-8 encoded w/o url encoding* @return header array | false on error*/protected static function getHeaders($api,$method,$params) {if ( !$api || !$method || !$params ) {return false;}$addr = self::getNicInfo();if ( !$addr ) {return false;}$timestamp = strftime('%Y-%m-%dT%H:%M:%S.000+08:00');$nonce = sprintf('%d000%d',time(),rand(1000, 9999));ksort($params,SORT_STRING);$ret = array();foreach( $params as $k => $v ) {$ret[] = sprintf('%s=%s',$k,$v);}$sig = self::getSignature($method,$timestamp,$nonce,$api,implode('&',$ret));return array('X-Hmac-Auth-Timestamp' => $timestamp,'X-Hmac-Auth-Version' => self::API_VERSION,'X-Hmac-Auth-Nonce' => $nonce,'apiKey' => self::$apiKey,'X-Hmac-Auth-Signature' => $sig,'X-Hmac-Auth-IP' => $addr['ip'],'X-Hmac-Auth-MAC' => $addr['mac']);}/*** encapsulation for BUC getUserByLoginName* @param $loginName The login name of the interesed user* @return array*/protected static function getUserByLoginName($loginName) {$api = '/rpc/enhancedUserQuery/getUserByLoginName.json';$server = self::getServer();$url = sprintf('%s%s',$server,$api);$params = array('loginName' => $loginName);$headers = self::getHeaders($api,'POST',$params);return self::curlPost($url,$params,self::API_TIMEOUT,$headers);}/*** helper function for HTTP POST request*/private static function curlPost($url, $params = array(), $timeout = 1, $headerAry = array()) {$ch = curl_init( );curl_setopt( $ch, CURLOPT_URL, $url);curl_setopt( $ch, CURLOPT_POST, 1);curl_setopt( $ch, CURLOPT_POSTFIELDS, $params);curl_setopt( $ch, CURLOPT_TIMEOUT, $timeout);curl_setopt( $ch, CURLOPT_SSL_CIPHER_LIST, 'TLSv1');curl_setopt( $ch, CURLOPT_HEADER, 0);curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1);if ($headerAry) {$tmp = array();foreach( $headerAry as $k => $v ) {$tmp[] = sprintf('%s: %s',$k,$v);}curl_setopt($ch, CURLOPT_HTTPHEADER, $tmp);}$data = curl_exec( $ch);$error = curl_error( $ch );curl_close( $ch );return $data;}}/*** static member initializer*/BucBase::init();/*** BUC business logic for OPENDATA*/class BucModel extends BucBase {/*** get user detail by email prefix* @param $prefix Email prefix for query* @return false | array()*/public static function getUserDetail($prefix) {return parent::getUserByLoginName($prefix);}}BucModel::getUserDetail('piaoyu.ddh');
IOS
安装
- 使用 CocoaPods(推荐)
pod 'ALBUCSecurityGatewayHTTPClient'
Demo
demo-1
[[ALBUCSecurityGatewayHTTPClient sharedSecurityGateway] setSecurityKey:@"Y02(n0Ejx_Q$2MYU6f$_&Q406l$$Q2zC&d4W6h$_"];[[ALBUCSecurityGatewayHTTPClient sharedSecurityGateway] setApiKey:@"BUC-Ad$Un6h8d(t_4CE&6&0@ZveUry"];[[ALBUCSecurityGatewayHTTPClient sharedSecurityGateway] postPath:@"/rpc/enhancedUserQuery/getUserByEmpId.json" parameters:@{ @"empId" : workId } success:^(AFHTTPRequestOperation* operation, id responseObject) {//do stuffs when success}failure:^(AFHTTPRequestOperation* operation, NSError* error) {// do stuffs when fail}];
demo-2
在命令行输入
运行即可.git clone git@gitlab.alibaba-inc.com:xiaotian.lxt/ALBUCSecurityGatewayHTTPClient.gitcd ALBUCSecurityGatewayHTTPClientpod installopen ALBUCSecurityGatewayHTTPClient.xcworkspace
备注:
- nodejs和C#暂不支持。
