ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

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

2021-07-03 12:00:50  阅读:346  来源: 互联网

标签:ch setopt uri eats 外卖 curl 优步 Ubereat CURLOPT


<?php


class Uber{

    protected $token;
    protected $scope;//token类型
    protected $redis;

    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' => 'post',
            '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'
        ]
    ];


    /**
     * 获取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')
    {
        $this->redis = redis_cache(10);//redis链接,公共方法
        $token = $this->getToken($uri, $client_id, $client_secret, $grant_type);
        if(!$token){
            $token = $this->getToken($uri, $client_id, $client_secret, $grant_type);
            if(!$token){
                //token获取失败
                return false;
            }
        }
        $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'];
        $token = $this->redis->get($this->scope);
        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 = [], $params);
        if(empty($result) || !is_array($result) || empty($result['access_token'])){
            //写日志记录,获取token失败
            return false;
        }

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

    /**
     * 向uber发送请求
     * @param $uri 登录为玩这个url,其他为$url_arr
     * @param array $query
     * @param array $params
     * @return array|mixed
     */
    public function requestUber($uri, $query = [], $params = []){
        if(strpos($uri, 'login')){//登录
            $res = $this->curlData($uri, $params, $header = [], $method = 'post', $type = '');
            if(!empty($res['data'])){
                return json_decode($res['data'], 1);
            }
            //写日志,请求返回的数据
        }else{//重组url
            $header = ['authorization:'.$this->token];
            $uri_arr = $this->url_relation[$uri];
            $uri = $uri_arr['uri'];
            if(count($query) > 0){
                foreach ($query as $key=>$item){
                    if(strpos($uri, $key)){
                        $uri = str_replace($key, $item, $uri);
                    }
                }
            }

            $url = $this->api_host.$uri;

            $res = $this->curlData($url, $params, $header, $uri_arr['method']);
            if($res){
                if(!empty($res['data'])){
                    $res['data'] = json_decode($res['data'], 1);
                }
                return $res;
            }
        }

        return false;

    }


    /**
     * 获取当前的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];
    }


    /**
     * 发送post请求
     * @param $url
     * @param $data
     * @param $header
     * @param string $method
     * @param string $type
     * @return array
     */
    public function curlData($url, $data, $header, $method = 'get', $type = 'json')
    {
        $ch = curl_init();
        if ($type == 'json') {
            $headers = ['Content-Type: application/json'];
        } else {
            $headers = ['Content-Type: application/x-www-form-urlencoded'];
        }
        $headers = array_merge($headers, $header);

        if ($method == 'GET' && !empty($data)) {
            if ($type != 'json') {
                $querystring = http_build_query($data);
                $url = $url . '?' . $querystring;
            } else {
                $url = $url . '?' . $this->arrToStr($data);
            }
        }

        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_HEADER, false);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // 执行后不直接打印出来
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($ch, CURLOPT_AUTOREFERER, 1);
        curl_setopt($ch, CURLOPT_TIMEOUT, 10);

        switch ($method) {
            case 'post':
                $data = json_encode($data);
                if ($type == 'json') {
                    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST'); // 请求方式
                    curl_setopt($ch, CURLOPT_POST, 1); // post提交
                    curl_setopt($ch, CURLOPT_POSTFIELDS, $data); // post的变量
                } else {
                    curl_setopt($ch, CURLOPT_POST, 1); // post提交
                    $querystring = http_build_query($data);
                    curl_setopt($ch, CURLOPT_POSTFIELDS, $querystring); // post的变量
                }
                break;
            case 'put':
                $data = json_encode($data);
                curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
                curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
                break;
            case 'delete':
                curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE");
                curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
                break;
            default:
                curl_setopt($ch, CURLOPT_HTTPGET, true);
                break;
        }
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        //curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); // 模拟用户使用的浏览器

        if (!empty($cookie)) {
            curl_setopt($ch, CURLOPT_COOKIE, $cookie);
        }
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 跳过证书检查
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); // 不从证书中检查SSL加密算法是否存在
        $output = curl_exec($ch);
        $return_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);

        return array('err_code' => $return_code, 'data' => $output);
    }

    /**
     * 拼接get数据
     * @param array $data
     * @return false|string
     */
    public function arrToStr($data = [])
    {
        ksort($data);
        $str = '';
        foreach ($data as $key => $item) {
            $str .= $key . '=' . $item . '&';
        }
        $str = substr($str, 0, strlen($str) - 1);
        return $str;
    }




}


if(!function_exists('redis_cache')){
    /**
     * 连接redis
     * @param int $db 数据库
     * @return Redis
     */
    function redis_cache($db = 0){
        global $_W;
        $redis_server = '127.0.0.1';
        $redis_port = '3306';
        $redis_auth = '';
        $client = new Redis();
        $client->connect($redis_server, $redis_port);
        if(!empty($redis_auth)){
            $client->auth($redis_auth);
        }
        if($db){
            $client->select($db);
        }
        return $client;
    }
}

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

标签:ch,setopt,uri,eats,外卖,curl,优步,Ubereat,CURLOPT
来源: https://blog.csdn.net/weixin_31501115/article/details/118437838

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有