123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138 |
- <?php
- namespace components;
- class ApiHandler
- {
- protected static $_instance = null;
- static function getInstance()
- {
- if (is_null(self::$_instance)) {
- self::$_instance = new self;
- }
- return self::$_instance;
- }
- /**
- * @param string $message
- */
- public function log($message)
- {
- if (false) {
- //Log::info($message);
- }
- }
- public function get($uri, $params = array())
- {
- return $this->_do_request($uri, $params);
- }
- public function post($uri, $params)
- {
- return $this->_do_request($uri, $params, true);
- }
- /**
- * 生成签名
- *
- * @return array
- */
- private function _generate_signature()
- {
- $timestamp = time();
- app()->configure('key');
- $private_key = config('key.apiAuthPrivateKey');
- $openssl_util = new OpensslAuth();
- $sig = $openssl_util->generate_signature($timestamp, $private_key);
- return [$timestamp, $sig];
- }
- /**
- * 订单流程唯一 key
- */
- private function _get_user_unique_key()
- {
- if(isset($_COOKIE["trade_user_unique_key"])) {
- $session_id = $_COOKIE["trade_user_unique_key"];
- } else {
- $session_id = md5(time());
- setcookie('trade_user_unique_key', $session_id, 0, '/');
- }
- return $session_id;
- }
- /**
- * 生成url
- *
- * @param $uri
- * @return string
- */
- private function _generate_url($uri)
- {
- $host = 'https://doc.33.cn';
- $url = rtrim($host, '/') . '/' . ltrim($uri, '/');
- //调试使用
- $this->log("call api: {$url}");
- return $url;
- }
- /**
- * 请求接口
- *
- * @param $uri
- * @param $params
- * @param bool $is_post
- * @return mixed
- * @throws ErrorException
- * @throws NotFoundException
- * @throws ParamException
- * @throws UserException
- * @throws UserLoglessException
- */
- private function _do_request($uri, $params, $is_post = false)
- {
- $url = $this->_generate_url($uri);
- var_dump('url:---'.$url);
- if (!$is_post) {
- if ($params) {
- $p_str = '';
- $comma = '';
- foreach ($params as $k => $v) {
- $p_str .= $comma . $k . '=' . $v;
- $comma = '&';
- }
- $url = $url . '?' . $p_str;
- }
- }
- $ch = curl_init();
- curl_setopt($ch, CURLOPT_URL, $url);
- curl_setopt($ch, CURLOPT_HEADER, 0);
- curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
- if ($is_post) {
- curl_setopt($ch, CURLOPT_POST, 1);
- curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($params));
- }
- $output = curl_exec($ch);
- return $output;
- }
- }
|