优步外卖(Ubereat)接口请求封装-全球uberapix

    <?php


class Uber{

    protected $token;
    protected $scope;//token类型
    protected $redis;
    protected $uri = '';

    public $prefix = 'UBER:';
    public $times = 5;
    public $login_api = 'https://login.uber.com/oauth/v2/token';//登录验证
    public $api_host = 'https://api.uber.com';
    public $url_relation = [
        //获取店铺状态【同步】
        'getStoreStatus' => [
            'method' => 'get',
            'uri' => '/v1/eats/store/store_id/status',
            'scope' => 'eats.store'
        ],
        //获取店铺节假日休息时间【同步】
        'getHolidayHours' => [
            'method' => 'get',
            'uri' => '/v1/eats/stores/store_id/holiday-hours',
            'scope' => 'eats.store'
        ],
        //设置节假日休息时间【同步】
        'setHolidayHours' => [
            'method' => 'post',
            'uri' => '/v1/eats/stores/store_id/holiday-hours',
            'scope' => 'eats.store'
        ],
        //获取店铺菜单(全量)【定时任务】
        'getMenus' => [
            'method' => 'get',
            'uri' => '/v2/eats/stores/store_id/menus',
            'scope' => 'eats.store'
        ],
        //上传店铺菜单(全量)【异步任务】
        'putMenus' => [
            'method' => 'put',
            'uri' => '/v2/eats/stores/store_id/menus',
            'scope' => 'eats.store'
        ],
        //更新店铺的商品信息【同步】
        'setItem' => [
            'method' => 'post',
            'uri' => '/v2/eats/stores/store_id/menus/items/item_id',
            'scope' => 'eats.store'
        ],
        //更新店铺的状态【同步】
        'setStoreStatus' => [
            'method' => 'post',
            'uri' => '/v1/eats/store/store_id/status',
            'scope' => 'eats.store.status.write'
        ],
        //获取已创建的订单【数组】【定时任务】
        'getOrderList' => [
            'method' => 'get',
            'uri' => '/v1/eats/stores/store_id/created-orders',
            'scope' => 'eats.store.orders.read'
        ],
        //获取已经取消的订单【数组】【定时任务】
        'getCancelOrder' => [
            'method' => 'get',
            'uri' => '/v1/eats/stores/store_id/canceled-orders',
            'scope' => 'eats.store.orders.read'
        ],
        //获取单个订单详情【定时任务】
        'getOrderDetail' => [
            'method' => 'get',
            'uri' => '/v2/eats/order/order_id',
            'scope' => 'eats.order'
        ],
        //接单【同步】
        'acceptOrder' => [
            'method' => 'post',
            'uri' => '/v1/eats/orders/order_id/accept_pos_order',
            'scope' => 'eats.order'
        ],
        //拒单【同步】
        'denyOrder' => [
            'method' => 'post',
            'uri' => '/v1/eats/orders/order_id/deny_pos_order',
            'scope' => 'eats.order'
        ],
        //取消订单【同步】
        'cancelOrder' => [
            'method' => 'post',
            'uri' => '/v1/eats/orders/order_id/cancel',
            'scope' => 'eats.order'
        ]
    ];
    public $week = ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday'];


    /**
     * 获取token
     * Uber constructor.
     * @param $uri $url_relation 中对应的key
     * @param string $client_id
     * @param string $client_secret
     * @param string $grant_type
     */
    public function __construct($uri, $client_id = '', $client_secret = '', $grant_type = 'client_credentials')
    {
        global $_W;
        flog($name = 'loginParams', [$uri, $client_id, $client_secret], $filename = 'UberEats');
        if(!$client_id){
            $client_id = $_W["config"]["setting"]['uber']['client_id'];
        }
        if(!$client_secret){
            $client_secret = $_W["config"]["setting"]['uber']['client_secret'];
        }
        $this->uri = $uri;
        $this->redis = redis_cache(10);//redis链接

        $token = $this->getToken($uri, $client_id, $client_secret, $grant_type);
        if(!$token){
            for($i = 0; $i < $this->times; $i++){
                $token = $this->getToken($uri, $client_id, $client_secret, $grant_type);
                if($token){
                    break;
                }
            }
        }
        $this->token = $token;
    }

    /**
     * 获取请求对应的token
     * @param $uri
     * @param $client_id
     * @param $client_secret
     * @param string $grant_type
     * @return bool|string
     */
    public function getToken($uri, $client_id, $client_secret, $grant_type = 'client_credentials')
    {
        $uri_arr = $this->urlToArr($uri);
        if (empty($uri_arr)) {
            //api错误
            return false;
        }
        $this->scope = $uri_arr['scope'];

        $key = $this->prefix .$client_id.':'.$this->scope;
        $token = $this->redis->get($key);
        if (!empty($token)) {
            return $token;
        }

        $params = [
            'client_id' => $client_id,
            'client_secret' => $client_secret,
            'grant_type' => $grant_type,
            'scope' => $this->scope,
        ];
        $result = $this->requestUber($this->login_api, $query = [], 0, $params);
        if (empty($result) || !is_array($result) || empty($result['access_token'])) {
            //写日志记录,获取token失败
            return false;
        }

        $token = $result['token_type'] . ' ' . $result['access_token'];
        $this->redis->set($key, $token);
        $this->redis->expire($key, $result['expires_in'] - 24 * 3600);//设置过期时间29天
        return $token;
    }

    /**
     * 向uber发送请求
     * @param $uri 登录为玩这个url,其他为$url_arr
     * @param array $query
     * @param int $store_id 本地店铺id
     * @param array $params
     * @return array|mixed
     */
    public function requestUber($uri, $query = [], $store_id = 0, $params = [])
    {
        $time_start = microtime(true);
        if(empty($uri)){
            return $this->errFormat();
        }
        if (strpos($uri, 'login')) {//登录
            $res = $this->curlData($uri, $params, $header = [], $method = 'post', '');

            $log = [
                'plat_store_id' => $this->scope,
                'status' => $res['err_code'],
                'url' => 'login',
                'host_url' => $this->login_api,
                'method' => $method,
                'request_data' => json_encode(['header' => [], 'body' => $params]),
                'return_data' => json_encode($res),
                'add_time' => time()
            ];
            //pdo_insert('tiny_wmall_sync_api_log', $log);
            flog($name = 'loginData', $log, $filename = 'uberEats');

            if (!empty($res['data'])) {
                return json_decode($res['data'], 1);
            }
            //写日志,请求返回的数据
        } else {//重组url
            $time_start1 = microtime(true);
            $ori_uri = $uri;
            $header = ['authorization:' . $this->token];
            $uri_arr = $this->url_relation[$uri];
            $uri = $uri_arr['uri'];
            if (count($query) > 0) {
                foreach ($query as $key => $item) {
                    if ($key == 'item_id') {
                        $item = 'Item-' . $item;
                    }
                    if (strpos($uri, $key)) {
                        $uri = str_replace($key, $item, $uri);
                    }
                }
            }

            $url = $this->api_host . $uri;
            $body = $params;
            if (!empty($params)) {
                $params = json_encode($params);
            }
            $time_req_start = microtime(true);
            $res = $this->curlData($url, $params, $header, $uri_arr['method']);
            $time_req_end = microtime(true);
            if (!$res['err_code']) {
                for ($i = 0; $i < $this->times; ++$i) {//测试重连
                    $res = $this->curlData($url, $params, $header, $uri_arr['method']);
                    if ($res['err_code']) {
                        break;
                    }
                }
            }


            $aid = 0;
            if ($store_id) {
                $store = pdo_get('ims_tiny_wmall_store', array('id' => $store_id), ['agentid', 'title']);
                $aid = $store ? $store['agentid'] : $aid;
            }
            /** @var 写日志 $log */
            $log = [
                'plat_store_id' => $query['store_id'],
                'status' => $res['err_code'] ?? 0,
                'url' => $ori_uri,
                'host_url' => $url,
                'method' => $uri_arr['method'] ?? 'post',
                'request_data' => json_encode(['header' => $header, 'body' => $body]),
                'return_data' => json_encode($res),
                'add_time' => time()
            ];
            $time_insert_start = microtime(true);
            flog($name = 'req_data', $log, $filename = 'uberEats');
          
            if ($res) {
                if (!empty($res['data'] && $res['err_code'])) {
                    $res['data'] = json_decode($res['data'], 1);
                }
                $time_end = microtime(true);
                $log_info = [
                    'time_start' => $time_start,
                    'time_start1' => $time_start1,
                    'time_req_start' => $time_req_start,
                    'time_req_end' => $time_req_end,
                    'time_insert_start' => $time_insert_start,
                    'time_end' => $time_end
                ];
                flog($name = 'req_time', $log_info, $filename = 'uberEats');
                return $this->errFormat($res['err_code'], $res['data']);
            }
        }

        return $this->errFormat($res['err_code']);

    }


    /***
     * 错误处理
     * @param int $code
     * @param array $data
     * @return array
     */
    public function errFormat($code = 0, $data = []){
        $err_code = [0, 200, 204, 400, 401, 403, 404, 409, 429, 500, 503];
        $err_msg = [
            0 => 'unknown',
            200 => 'success',
            204 => 'success',
            400 => 'data_error or config_error',
            401 => 'unauthorized',
            403 => 'user_not_allowed or resource_update_not_allowed',
            404 => 'resource_not_found(store or item or order)',
            409 => 'resource_status_conflict',
            429 => 'Exceeded rate limit',
            500 => 'internal_server_error',
            503 => 'service_unavailable'
        ];

        if(!in_array($code, $err_code)){
            $code = 0;
        }

        $err_data = [
            'err_code' => $code,
            'err_msg' => $err_msg[$code],
            'data' => $data
        ];

        if($code == 400 && !empty($data)){
        }
        return $err_data;

    }


    /**
     * 获取当前的url
     * @param $uri
     * @return array|string[]
     */
    public function urlToArr($uri)
    {
        $api = [];
        foreach ($this->url_relation as $key => $item) {
            array_push($api, $key);
        }
        if (!in_array($uri, $api)) {
            return [];
        }
        return $this->url_relation[$uri];
    }


}

大佬看以上代码即可!!!

uber接口文档:https://developer.uber.com/docs/eats/api/v1/post-eats-store-storeid-status

菜鸟代码请绕到此地:https://download.csdn.net/download/weixin_31501115/20005098?spm=1001.2014.3001.5501

Guess you like

Origin blog.csdn.net/weixin_31501115/article/details/118437838