专有钉钉sdk

python3:

import base64
import hmac
import json
import logging
import random
import time
import uuid

import requests


class ExecutableClient:
    api_server = ''
    api_key = ''
    secret_key = ''
    api_name = ''
    api_version = '1.0'
    api_timeout = 30
    headers = None
    params = {}
    nic_info = {
        "ip": "127.0.0.1",
        "mac": ""
    }
    timestamp = int(time.time()) + 28800

    def set_domain(self, domain: str):
        self.api_server = domain

    def set_access_key(self, access_key: str):
        self.api_key = access_key

    def set_secret_key(self, secret_key: str):
        self.secret_key = secret_key

    def set_api_name(self, api_name: str):
        self.api_name = api_name

    def add_parameter(self, key, value):
        if key not in self.params:
            self.params[key] = []
        self.params[key].append(value)

    def get_mac_address(self):
        mac = uuid.UUID(int=uuid.getnode()).hex[-12:]
        return ":".join([mac[e:e + 2] for e in range(0, 11, 2)])

    def get_public_ip(self):
        try:
            import public_ip as ip
            ip = ip.get(timeout=5)
        except Exception:
            ip = None
        return ip

    def get_private_ip(self):
        ip = '127.0.0.1'
        try:
            import netifaces
            # 遍历所有网络接口
            for interface in netifaces.interfaces():
                addrs = netifaces.ifaddresses(interface)
                # 获取IPv4地址
                if netifaces.AF_INET in addrs:
                    for addr_info in addrs[netifaces.AF_INET]:
                        ip = addr_info['addr']
                        # 排除回环地址和无效地址
                        if ip != '127.0.0.1' and not ip.startswith('169.254'):
                            return ip
        except Exception:
            return ip
        return ip

    def get_ip_address(self):
        ip = self.get_public_ip() or self.get_private_ip()
        return ip

    def set_nic_info(self):
        self.nic_info['mac'] = self.get_mac_address()
        self.nic_info['ip'] = self.get_ip_address()

    def get_signature(self, method: str, timestamp: str, nonce: str, uri: str, params_str: str):
        secret_key = self.secret_key.encode('utf-8')
        if params_str:
            bytes_data = f"{method}\n{timestamp}\n{nonce}\n{uri}\n{params_str}"
        else:
            bytes_data = f"{method}\n{timestamp}\n{nonce}\n{uri}"
        signature = hmac.new(secret_key, bytes_data.encode('utf-8'), 'sha256').digest()
        return base64.b64encode(signature).decode('utf-8')

    def get_headers(self, method):
        timestamp = self.timestamp

        self.set_nic_info()

        format_time = time.strftime('%Y-%m-%dT%H:%M:%S.000+08:00', time.gmtime(timestamp))
        nonce = f"{timestamp}000{random.randint(1000, 9999)}"

        param_list = []
        if self.params:
            for key in sorted(self.params.keys()):
                for value in self.params[key]:
                    param_list.append(f"{key}={value}")
        param_list.sort()
        params_str = '&'.join(param_list)

        signature = self.get_signature(method, format_time, nonce, self.api_name, params_str)
        self.headers = {
            'X-Hmac-Auth-Timestamp': format_time,
            '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.nic_info['ip'],
            'X-Hmac-Auth-MAC': self.nic_info['mac']
        }
        return self.headers

    def get(self, timeout=30, only_return_content=True):
        headers = self.get_headers('GET')
        params = self.params
        url = f"{self.api_server}{self.api_name}"

        param_list = []
        if params:
            for key in sorted(params.keys()):
                for value in params[key]:
                    param_list.append(f"{key}={value}")
        query = '&'.join(param_list)
        url = f"{url}?{query}"
        text = ""
        try:
            response = requests.get(url, headers=headers, timeout=timeout)
            response.raise_for_status()
            text = response.text
            data = response.json()
        except requests.exceptions.RequestException as e:
            logging.error(f"url:{url}\nerror: {e}")
            return None
        except json.JSONDecodeError:
            logging.error(f"url:{url}\ntext:{text}")
            return None

        if not data.get('success'):
            logging.error(f"result not success: {data} | {url}")
            return None

        return data['content'] if only_return_content else data

    def post(self, timeout=30, only_return_content=True):
        headers = self.get_headers('POST')
        params = self.params
        url = f"{self.api_server}{self.api_name}"

        param_list = []
        if params:
            for key in sorted(params.keys()):
                for value in params[key]:
                    param_list.append(f"{key}={value}")
        post_data = '&'.join(param_list)
        text = ""
        try:
            response = requests.post(url, headers=headers, data=post_data, timeout=timeout)
            response.raise_for_status()
            text = response.text
            data = response.json()
        except requests.exceptions.RequestException as e:
            logging.error(f"url:{url}\nerror: {e}")
            return None
        except json.JSONDecodeError:
            logging.error(f"url:{url}\ntext:{text}")
            return None

        if not data.get('success'):
            logging.error(f"result not success: {data} | {url}")
            return None

        return data['content'] if only_return_content else data
View Code

php:

<?php
/**
 * 开放平台调用SDK
 */
namespace OpenplatformSDK {
    class ExecutableClient
    {
        var $configs=null;
        var $headers=null;
        var $timestamp=null;
        public function __construct(){  #初始化方法
            $this->configs['epaas'] = array(
                'api_version' => '1.0',
                'api_timeout' => 3// 超时时间,单位秒
            );
            $date = date_create();
            $timestamp = date_timestamp_get($date);
            // 注意请求epaas必须加8个小时,否则与epaas时间匹配不上
            $timestamp += 28800;
            $this->timestamp = $timestamp;
        }
        function configs(){
            return $this->configs;
        }
        function setDomain($domain)
        {
            $this->configs['epaas']['api_server']=$domain;
        }
        function setAccessKey($accessKey){
            $this->configs['epaas']['api_key'] = $accessKey;
        }
        function setSecretKey($secretKey){
            $this->configs['epaas']['api_secret'] = $secretKey;
        }
        function setApiName($apiName){
            $this->configs['epaas']['api_name'] = $apiName;
        }
        function addParameter($key,$value){
            $this->configs['epaas']['params'][$key][] = $value;
            //print_r($this->configs['epaas']);
        }

        function epaasNicInfo()
        {
            $cmd = '/sbin/ifconfig eth0|/usr/bin/head -2';
            $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;
        }

        function epaasSignature($method, $timestamp, $nonce, $uri, $params)
        {
            $init = $this->configs();
            $bytes = sprintf("%s\n%s\n%s\n%s", $method, $timestamp, $nonce, $uri);
            if(!empty($params)){
                $bytes = sprintf("%s\n%s\n%s\n%s\n%s", $method, $timestamp, $nonce, $uri, $params);
            }
            printf("bytes:%s",$bytes);
            #print_r($bytes);
            $hash = hash_hmac('sha256', $bytes, $init['epaas']['api_secret'], true);
            return base64_encode($hash);
        }

        function epaasHeaders($method)
        {
            $timestamp = $this->timestamp;
            $init = $this->configs();
            $params = $init['epaas']['params'];
            $api = $init['epaas']['api_name'];

            //这里ip和mac写的是假的,用户调用时改为自己的ip和mac
            $addr = array(
                'ip'=>'127.0.0.1',
                'mac'=>''
            );//$this->epaasNicInfo();
            if (!$addr) {
                return false;
            }

            $formatTime = strftime('%Y-%m-%dT%H:%M:%S.000+08:00', $timestamp);
            $nonce = sprintf('%d000%d', $timestamp, rand(1000, 9999));
            if(!empty($params)){
                ksort($params, SORT_STRING);
            }
            $ret = array();
            #print_r($ret);
            if(!empty($params)){
                foreach ($params as $k => $v) {
                    foreach ($v as $value)
                    {
                        $ret[] = sprintf('%s=%s', $k, $value);
                    }
                }
            }

            sort($ret);
            $sig = $this->epaasSignature($method, $formatTime, $nonce, $api, implode('&', $ret));
            $this->headers = array(
                'X-Hmac-Auth-Timestamp' => $formatTime,
                'X-Hmac-Auth-Version' => $init['epaas']['api_version'],
                'X-Hmac-Auth-Nonce' => $nonce,
                'apiKey' => $init['epaas']['api_key'],
                'X-Hmac-Auth-Signature' => $sig,
                'X-Hmac-Auth-IP' => $addr['ip'],
                'X-Hmac-Auth-MAC' => $addr['mac']
            );
            return $this->headers;
        }


        function epaasCurlGet($timeout = 1, $onlyReturnContent = true)
        {
            $headerAry = $this->epaasHeaders('GET');
            $init = $this->configs();
            $params=$init['epaas']['params'];
            $api = $init['epaas']['api_name'];
            $url=sprintf('%s%s', $init['epaas']['api_server'], $api);
            if(!empty($params)){
                ksort($params, SORT_STRING);
            }
            $ret = array();
            if(!empty($params)){
                foreach ($params as $k => $v) {
                    foreach ($v as $value)
                    {
                        $ret[] = sprintf('%s=%s', $k, $value);
                    }
                }
            }

            $getparam = implode('&', $ret);
            $url=sprintf('%s?%s', $url, $getparam);
            #print($url);
            #print("\n");
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
            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);
            if ($error) {
                $msg = "epaasCurlPost|curl error: " . $error . "|" . $url . "|";
                error_log($msg);
            }
            curl_close($ch);
            $ret = json_decode($data, true);
            if (!$ret['success']) {
                $msg = "epaasCurlPost|result not success: " . $data . "|" . $url . "|";
                error_log($msg);
            }

            if ($onlyReturnContent) {
                return $ret['content'];
            } else {
                return $ret;
            }
        }
        /**
         * 以POST方式请求epaas
         * @param int $timeout
         * @param bool $onlyReturnContent 是否只返回结果中的content
         * @return mixed
         */
        function epaasCurlPost($timeout = 1, $onlyReturnContent = true)
        {
            $headerAry = $this->epaasHeaders('POST');
            $init = $this->configs();
            $params=$init['epaas']['params'];
            $api = $init['epaas']['api_name'];
            $url=sprintf('%s%s', $init['epaas']['api_server'], $api);
            $ch = curl_init();
            $ret = array();
            if(!empty($params)){
                foreach ($params as $k => $v) {
                    foreach ($v as $value)
                    {
                        $ret[] = sprintf('%s=%s', $k, $value);
                    }
                }
            }

            $getparam = implode('&', $ret);
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $getparam);
            curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
            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);
            if ($error) {
                $msg = "epaasCurlPost|curl error: " . $error . "|" . $url . "|";
                error_log($msg);
            }
            curl_close($ch);
            $ret = json_decode($data, true);
            if (!$ret['success']) {
                $msg = "epaasCurlPost|result not success: " . $data . "|" . $url . "|";
                error_log($msg);
            }

            if ($onlyReturnContent) {
                return $ret['content'];
            } else {
                return $ret;
            }
        }
    }
}
View Code

 

posted @ 2025-04-09 18:58  NAVYSUMMER  阅读(15)  评论(0)    收藏  举报
交流群 编程书籍