<?php
/**
 * 饿了么外卖订单管理
 * @Copyright (C) 2018 汉潮 All rights reserved.
 * @License http://www.hanchao9999.com
 * @Author xiaogg <xiaogg@sina.cn>
 */
namespace Common\Vendor\Threeorder;
class Ele extends \Common\Vendor\Threeorder{
    private $config=array(
        'appkey'=>'6VZNBZxtAS',
        'appsecret'=>'a25f15a42b674e52bbea64786ee8002b14924807',
    );
    private $is_sandbox= true;//是否为测试
    private $callback_url;
    private $connectUrl="https://open-api.shop.ele.me";//平台的正式接口地址;
    public function __construct($config=array()) {
        if($config){
            $this->config=array_merge($this->config,$config);
        }
        if( $this->is_sandbox){
             $this->connectUrl="https://open-api-sandbox.shop.ele.me";//平台的测试接口地址;
             $this->config['appkey']='Vflv9DihBO';
             $this->config['appsecret']='3462fe9a2e9596cd72f8289c634da55f7d651f5a';
        }
        $this->class_name='ele';
        $this->callback_url='http://'.BASE_DOMAIN.'/saasapi.php/Threeorder/index/apitype/'.$this->class_name;
    }
    public function setConfig($venderId=''){
        if(is_array($venderId)){
            $this->config=array_merge($this->config,$venderId);
        }else{
            $config=$this->orderconfig($venderId);
            $this->config=array_merge($this->config,$config);
        }
    }
    //调取商家信息
    public function getshopinfo(){
        $return=array('status'=>0,'info'=>'');
        $param=array();
        $action='eleme.user.getUser';
        $return=$this->execute($action,$param);
        return $return;
    }
    //调取店铺信息
    public function getshop_info($request){
        $return=array('status'=>0,'info'=>'');
        $param=array(
            'shopId'=>$request['shopId'],
        );
        $action='eleme.shop.getShop';
        $return=$this->execute($action,$param);
        return $return;
    }
    /**
     * 订单已送达
     * @param $request array (ordersn =>订单号 operator 操作人姓名 mobile 配送者电话 )
     */
    public function orderend($request=''){
        $return=array('status'=>0,'info'=>'');
        if(empty($request['ordersn'])){$return['info']='请填写订单号';return $return;}        
        $param=array(
            'orderId'=>$request['ordersn'],
            'phone'=>$request['mobile']
        );
        $action='eleme.order.completeDeliveryBySelf';
        $result=$this->execute($action,$param);
        if(empty($result['error'])){
            $return['status']=1;
            $return['info']=$result['result'];
        }else{
            $return['info']=$result['error']['message'].'('.$result['error']['code'].')';
        }
        return $return;
    }
    /**
     * 订单第三方配送转商家自送
     * @param $request array (ordersn =>订单号 operator 操作人姓名)
     */
    public function orderdeliverytoself($request=''){
        $return=array('status'=>0,'info'=>'');
        if(empty($request['ordersn'])){$return['info']='请填写订单号';return $return;}        
        $action='eleme.order.startDeliveryBySelf';
        $param=array(
            'orderId'=>$request['ordersn'],
            'phone'=>$request['mobile']//配送者电话 
        );
        $result=$this->execute($action,$param);
        if(empty($result['error'])){
            $return['status']=1;
            $return['info']=$result['result'];
        }else{
            $return['info']=$result['error']['message'].'('.$result['error']['code'].')';
        }
        return $return;
    }
    /**
     * 商家订单发货
     * @param $request array (ordersn =>订单号 status=>1第三方 0自有配送 operator 操作人姓名mobile 操作人姓名)
     */
    public function orderdelivery($request=''){
        $return=array('status'=>0,'info'=>'');
        if(empty($request['ordersn'])){$return['info']='请填写订单号';return $return;}        
        
        if($request['status']){
            $action='eleme.order.setOrderPrepared';
            $param=array(
                'orderId'=>$request['ordersn'],
            );
        }else{
            $action='eleme.order.startDeliveryBySelf';
            $param=array(
                'orderId'=>$request['ordersn'],
                'phone'=>$request['mobile']//配送者电话 
            );
        }
        $result=$this->execute($action,$param);
        if(empty($result['error'])){
            $return['status']=1;
            $return['info']=$result['result'];
            if($request['status']){
                $this->ordercalldelivery($request);
            }
        }else{
            $return['info']=$result['error']['message'].'('.$result['error']['code'].')';
        }
        return $return;
    }
    //呼叫配送
    public function ordercalldelivery($request=''){
        $return=array('status'=>0,'info'=>'');
        if(empty($request['ordersn'])){$return['info']='请填写订单号';return $return;}        
        
        $action='eleme.order.callDelivery';
        $param=array(
            'orderId'=>$request['ordersn'],
        );
        $result=$this->execute($action,$param);
        if(empty($result['error'])){
            $return['status']=1;
            $return['info']=$result['result'];
        }else{
            $return['info']=$result['error']['message'].'('.$result['error']['code'].')';
        }
        return $return;
    }
    /**
     * 确认退款/驳回退款
     * @param $request array (ordersn =>订单号 status=> 1确认 0驳回 operator 操作人姓名 reason 确认退款详情)
     */
    public function orderrefund($request=''){
        $return=array('status'=>0,'info'=>'');
        if(empty($request['ordersn'])){$return['info']='请填写订单号';return $return;}
        if($request['status']){//确认
            $param=array(
                'orderId'=>$request['ordersn']
            );
            $action='eleme.order.agreeRefundLite';
        }else{//驳回
            $param=array(
                'orderId'=>$request['ordersn'],
                'reason'=>$request['reason']
            );
            $action='eleme.order.disagreeRefundLite';
        }
        $result=$this->execute($action,$param);
        if(empty($result['error'])){
            $return['status']=1;
            $return['info']=$result['result'];
        }else{
            $return['info']=$result['error']['message'].'('.$result['error']['code'].')';
        }
        return $return;
    }
    
    /**
     * 确认接单/不接单
     * @param $request array (ordersn =>订单号 status=> 1接单 0 不接单 operator 操作人姓名 reason 不接单详情)
     */
    public function orderconfirm($request=''){
        $return=array('status'=>0,'info'=>'');
        if(empty($request['ordersn'])){$return['info']='请填写订单号';return $return;}        
        if($request['status']){//确认
            $param=array(
                'orderId'=>$request['ordersn']
            );
            $action='eleme.order.confirmOrderLite';
        }else{//驳回
            $reasons=$this->getreasons();
            if(empty($request['reason'])){$request['reason']='其他原因';}
            $key=array_search($request['reason'],$reasons);
            if(empty($key))$key='others';
            $param=array(
                'orderId'=>$request['ordersn'],
                'type'   =>$key,
                'remark' =>$request['reason']
            );
            $action='eleme.order.cancelOrderLite';
        }
        $result=$this->execute($action,$param);
        if(empty($result['error'])){
            $return['status']=1;
            $return['info']=$result['result'];
        }else{
            $return['info']=$result['error']['message'].'('.$result['error']['code'].')';
        }
        return $return;
    }
    /**
     *  商家审核用户取消申请接口
     * @param $request array (ordersn =>订单号)
     */
    public function orderCancelConfirm($request=''){
        $return=array('status'=>0,'info'=>'');
        if(empty($request['ordersn'])){$return['info']='请填写订单号';return $return;}
        $param=array(
            'orderId'=>$request['ordersn']
        );
        $action='eleme.order.agreeRefundLite';
        $result=$this->execute($action,$param);
        if(empty($result['error'])){
            $return['status']=1;
            $return['info']=$result['result'];
        }else{
            $return['info']=$result['error']['message'].'('.$result['error']['code'].')';
        }
        return $return;
    }
    /**
     * 订单列表
     * @param $request array (ordersn =>订单号)
     */
    public function orderlist($request='',$date=''){
        $return=array('status'=>0,'info'=>'');
        $shopId=$this->config['venderId'];
        if(empty($shopId)){$return['info']='店铺id';return $return;}
        if(empty($date))$date=NOW_TIME;
        $param=array(
            'shopId'   =>$shopId,
            'pageNo'   =>1,
            'pageSize' =>20,
            'date'     =>time_format($date,'Y-m-d'),
        );
        $action='eleme.order.getAllOrders';
        $result=$this->execute($action,$param);
        if(empty($result['error'])){
            $return['status']=1;
            $return['info']=$result['result'];
        }else{
            $return['info']=$result['error']['message'].'('.$result['error']['code'].')';
        }
        return $return;
    }
    /**
     * 查看订单详情
     * @param $orderNo 订单号
     */
    public function orderdetail($orderNo){
        $return=array('status'=>0,'info'=>'');
        if(empty($orderNo)){$return['info']='请填写订单号';return $return;}        
        $param=array(
            'orderId'=>$orderNo
        );
        $action='eleme.order.getOrder';
        $result=$this->execute($action,$param);
        if(empty($result['error'])){
            $return['status']=1;
            $return['info']=$result['result'];
        }else{
            $return['info']=$result['error']['message'].'('.$result['error']['code'].')';
        }
        return $return;
    }
    /**
     * 通过授权码获取token
     * @param $code 授权码
     * @param $callback_url 回调地址
     * @return mixed
     */
    public function get_token_by_code($code){
        $body = array(
            "grant_type" => "authorization_code",
            "code" => $code,
            "redirect_uri" => $this->callback_url,
            "client_id" => $this->config['appkey']
        );
        $body= http_build_query($body);
        $header=$this->get_headers();
        $response = $this->post($this->connectUrl."/token",$body,$header);
        return json_decode($response,1);
    }
    /**
     * 通过refresh_token兑换新的token
     * @param $refresh_token 刷新的token
     * @param $scope 授权范围，默认情况下填写"all"
     * @return mixed
     */
    public function get_token_by_refresh_token($refresh_token='', $scope='all'){
        if(empty($refresh_token))$refresh_token=$this->config['refresh_token'];
        $body = array(
            "grant_type" => "refresh_token",
            "refresh_token" => $refresh_token,
            "scope" => $scope
        );//print_r($body);exit;
        $body= http_build_query($body);
        $header=$this->get_headers();
        $response = $this->post($this->connectUrl."/token",$body,$header);
        $result=json_decode($response,1);        
        if($result['access_token']){
            $appid=$this->config['venderId'];
            $result['access_token_expires']=NOW_TIME+$result['expires_in']-3600;
            $this->orderconfig($appid,$result);
        }
        return $result;
    }
    /**
     * 响应回调入口文件
     */
    public function notify($postdata=''){
        if(empty($postdata))$postdata=I('post.');
        if(empty($postdata))$postdata=file_get_contents("php://input");
        
        
        $get=I('get.');
        $request=$this->format_param($postdata);
        $log=var_export($request,1);
        $log.=var_export($get,1);
        //file_put_contents('uploads/'.$this->class_name.NOW_TIME.'.txt',$log);/**/
        if(!empty($get['code'])){
            $appid=intval($get['state']);
            if(empty($appid)){
                $return=array('status'=>0,'error'=>'state is error','info'=>'state is error');$this->ajaxReturn($return);
            }
            $result=$this->get_token_by_code($get['code']);
            if($result['access_token']){
                $result['venderId']=$appid;
                $result['access_token_expires']=NOW_TIME+$result['expires_in']-3600;
                $this->orderconfig($appid,$result);
            }else{
                $this->https(400);
                $this->ajaxReturn($result);
            }
        }
        if($request['type']){//订单状态回调
           return $this->change_order_status($request['type'],$request);
        }
        if($get['apimethod']=='return'){
            return array('status'=>1,'info'=>"操作成功");
        }else{
            $return=array('message'=>'ok');
            $this->ajaxReturn($return);
        }
        
    }
    /**
     * 返回code
     */
    private function change_order_status($type,$request){
        $return=array('message'=>'ok');
        // if(!$this->verifySign($request)){$return['message']='sign error';$this->ajaxReturn($return);}   //验签
        $info=$request['message'];$orderid=$info['orderId'];
        if(!empty($info['shopId']))$this->setConfig($info['shopId']);
        if(empty($orderid)){$return['message']='orderid error';$this->ajaxReturn($return);}
        $order_status='';$delivery_mark='';
        
        $timestamp=empty($param_json['timestamp'])?NOW_TIME:strtotime($param_json['timestamp']);
        $savedata=array();
        $type=intval($type);//待接单＝1 待取货＝2 配送中＝3 已完成＝4 已取消＝5 已过期＝7
        if($type>=57 && $type<=70){//配送失败
            $order_status=7;$delivery_mark='配送失败'.$type;
        }else{
            switch($type){
                case 10:$order_status=1;$delivery_mark='订单生效';break;
                case 12:$order_status=2;$delivery_mark='商户接单';break;
                case 14:$order_status=5;$delivery_mark='订单被取消';break;
                case 15:$order_status=7;$delivery_mark='订单置为无效';break;
                case 17:$order_status=7;$delivery_mark='订单强制无效';break;
                case 18:$order_status=4;$delivery_mark='订单完结';break;
                case 20:$order_status=6;$delivery_mark='用户申请取消单';break;
                case 21:$order_status=6;$delivery_mark='用户取消取消单申请';break;
                case 22:$delivery_mark='商户拒绝取消单';break;
                case 23:$order_status=5;$delivery_mark='商户同意取消单';break;
                case 24:$delivery_mark='用户申请仲裁取消单';break;
                case 25:$order_status=5;$delivery_mark='客服仲裁取消单申请有效';break;
                case 26:$delivery_mark='客服仲裁取消单申请无效';break;
                case 30:$delivery_mark='用户申请退单';break;
                case 31:$delivery_mark='用户取消退单';break;
                case 32:$delivery_mark='商户拒绝退单';break;
                case 33:$order_status=5;$delivery_mark='商户同意退单';break;
                case 34:$delivery_mark='用户申请仲裁';break;
                case 35:$order_status=5;$delivery_mark='客服仲裁退单有效';break;
                case 36:$delivery_mark='客服仲裁退单无效';break;
                case 45:$delivery_mark='用户催单';break;
                case 51:$order_status=2;$delivery_mark='订单待分配配送商';break;
                case 52:$order_status=2;$delivery_mark='订单待分配配送员';break;
                case 53:$order_status=2;$delivery_mark='配送员取餐中';break;
                case 54:$order_status=2;$delivery_mark='配送员已到店';break;
                case 55:$order_status=3;$delivery_mark='配送员配送中';break;
                case 56:$order_status=1;$delivery_mark='配送成功';break;
                case 57:$order_status=5;$delivery_mark='配送取消，商户取消';break;
                case 58:$order_status=5;$delivery_mark='配送取消，用户取消';break;
                case 59:$order_status=5;$delivery_mark='配送取消，物流系统取消';break;
                case 71:$delivery_mark='自行配送';break;
                case 72:$order_status=5;$delivery_mark='不再配送';break;
                case 73:$delivery_mark='物流拒单，仅支持在线支付';break;
                case 74:$order_status=5;$delivery_mark='物流拒单，超出服务范围';break;
                case 75:$order_status=5;$delivery_mark='物流拒单，请求配送晚';break;
                case 76:$order_status=5;$delivery_mark='物流拒单，系统异常';break;
                case 91:$delivery_mark='店铺营业状态通知';break;
                case 93:$delivery_mark='店铺信息修改通知';break;
                case 100:$delivery_mark='应用授权解除通知';break;
                case 105:$delivery_mark='服务市场订单订购通知';break;
            }
        }
        $mod=M('ThreeOrder');$map=array();
        $map['ordersn']=$orderid;
        $check=$mod->where($map)->count('id');
        if(empty($check)){
            $adddata=array();            
            $adddata['ordersn']=$orderid;
            $adddata['shop_id']=$this->config['shop_id'];
            $adddata['code']=$this->class_name;
            $adddata['addtime']=$adddata['updatetime']=NOW_TIME;
            if($order_status)$adddata['order_status']=$order_status;
            $mod->add($adddata);
            $map=array();
            $map['order_status']=array('elt',2);
            $map['shop_id']=$this->config['shop_id'];
            $count=M('ThreeOrder')->where($map)->count();
            //极光推送（app/pad）
            $content="您有新的饿了么订单请及时处理";
            $paramdata=array('type'=>99,'txt'=>$count);
            $ids=getpushids(3,$this->config['shop_id']);
            if(!empty($ids[1]))$result = pushSend($ids[1],$content,'app',1,$paramdata);
            if(!empty($ids[2]))$result = pushSend($ids[2],$content,'app',2,$paramdata);    
        }
        if(!empty($info['reason']))$delivery_mark.=$info['reason'];
        if(!empty($info['userId']))$savedata['buyer_name']=$info['userId'];
        if(!empty($info['shopId']))$savedata['seller_id']=$info['shopId'];
        if(!empty($info['name']))$savedata['delivery_name']=$info['name'];
        if(!empty($info['phone']))$savedata['delivery_mobile']=$info['phone'];
        if(!empty($info['deliverFee']))$savedata['delivery_fee']=$info['deliverFee'];
        if(!empty($info['groups'])){
            $goods_info=array();$total=0;
            foreach ($info['groups'][0]['items'] as $key => $value) {
                $total+=$value['total'];  
                $goods_info[$key]['goodssn']=$value['skuId'];
                $goods_info[$key]['goods_name']=$value['name'];  
                $goods_info[$key]['goods_number']=$value['quantity']; 
                $goods_info[$key]['count']=$value['quantity'];
                $goods_info[$key]['shop_price']=$value['price']; 
                $goods_info[$key]['org_parce']=$value['total'];
                if($value['newSpecs'])$goods_info[$key]['newSpecs']=$value['newSpecs']; 
                if($value['attributes'])$goods_info[$key]['attributes']=$value['attributes'];              
            }
            $savedata['goods_amount']=$total;
            $savedata['goods_allmoney']=$total;
            if($goods_info)$savedata['goods_info']=serialize($goods_info);
        }

        if(!empty($info['address']))$savedata['address']=$info['address'];
        if(!empty($info['description']))$savedata['temp']=$info['description'];
        if($info['invoiced']){$invoice=array();if(!empty($info['invoiceType']))$invoice['invoice_type']=$info['invoiceType'];if(!empty($info['invoice']))$invoice['invoice_title']=$info['invoice']; if($invoice)$savedata['invoice_info']=serialize($invoice);}
        if(!empty($info['phoneList']))$savedata['mobile']=$info['phoneList'][0];
        if(!empty($info['totalPrice']))$savedata['order_amount']=$info['totalPrice'];
        if(!empty($info['totalPrice']))$savedata['order_money']=$info['totalPrice'];
        if(!empty($info['packageFee']))$savedata['lunch_box_price']=$info['packageFee'];
        if(!empty($info['consignee']))$savedata['consignee']=$info['consignee'];
        if(!empty($info['deliveryGeo'])){$xy=explode(',', $info['deliveryGeo']);$savedata['xpoint']=$xy[0];$savedata['ypoint']=$xy[1];}
        if($delivery_mark)$savedata['delivery_mark']=$delivery_mark;
        if($order_status)$savedata['order_status']=$order_status;
        if($order_status==4)$savedata['order_endtime']=NOW_TIME;
        if($order_status==2 || $order_status==3)$savedata['order_endtime']=NOW_TIME;
        if($order_status==5)$savedata['order_canceltime']=NOW_TIME;
        if($order_status==7)$savedata['order_closetime']=NOW_TIME;
        $savedata['updatetime']=NOW_TIME;
        if($info['createdAt'])$savedata['creattime']=strtotime($info['createdAt']);
        $map=array();
        $map['ordersn']=$orderid;
        $mod->where($map)->save($savedata);
        $id=idtoname($orderid,'ThreeOrder','id','ordersn',false);
        D('Pad/ThreeOrder')->change_goods_num($id);
        $this->ajaxReturn($return);
    }
    /**
     * 生成授权url
     * @param $state 状态码，通常是随机的UUID，授权成功后会原样返回，可以用于校验
     * @param $scope 授权范围，默认情况下填写"all"
     * @param $callback_url 回调地址
     * @return string
     */
    public function get_auth_url($state, $scope='all'){
        if(empty($state))$state=C('APPID');
        if(empty($state))return false;
        $url = $this->connectUrl. "/authorize";
        $response_type = "code";
        $client_id = $this->config['appkey'];
        $callback = urlencode($this->callback_url.'/apimethod/return');
        return $url . "?response_type=" . $response_type . "&client_id=" . $client_id . "&redirect_uri=" . $callback . "&scope=" . $scope . "&state=" . $state;
    }
    //请求服务端
    public function execute($action,$parameters) {
       $access_token=$this->getToken();//var_dump($access_token);exit;
	   $protocol = array(
            "nop" => '1.0.0',
            "id" => $this->create_uuid(),
            "action" => $action,
            "token" => $access_token,
            "metas" => array(
                "app_key" => $this->config['appkey'],
                "timestamp" => NOW_TIME,
            ),
            "params" => $parameters,
        );
        $protocol['signature'] = $this->generate_signature($protocol);
        //如果没有参数，赋值为一个空对象
        if (count($parameters) == 0) {$protocol["params"] = (object)array();}
        $protocol =   json_encode($protocol);
        $result = $this->post($this->connectUrl."/api/v1", $protocol);
        if($result && substr($result,0,6)=='error:')$return = array('status'=>0,'info'=>$result);
        else $return =json_decode($result,1);
        return $return;
	}
    //获取token
    private function getToken(){
        $access_token=$this->config['access_token'];
        if($access_token && $this->config['access_token_expires']<NOW_TIME){//授权过期刷新
            $refresh_token=$this->get_token_by_refresh_token();if($refresh_token['access_token'])$access_token=$refresh_token['access_token'];
        }
        return $access_token;
    }
    private function verifySign($params){
        ksort($params);
        $params['message']=json_encode($params['message']);
        $sign=$params['signature'];unset($params['signature']);print_r($params);
        $sign_str= str_replace('&','',urldecode(http_build_query($params))).$this->config['appsecret'];
        return $sign==strtoupper(md5($sign_str));
    }
    //签名
    private function generate_signature($protocol){
        $merged = array_merge($protocol['metas'], $protocol['params']);
        ksort($merged);$string = "";
        foreach ($merged as $key => $value) {
            $string .= $key . "=" . json_encode($value, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
        }
        $access_token=$this->getToken();
        $splice = $protocol['action'] . $access_token . $string . $this->config['appsecret'];
        $encode = mb_detect_encoding($splice, array("ASCII", 'UTF-8', "GB2312", "GBK", 'BIG5'));
        if ($encode != null) {
            $splice = mb_convert_encoding($splice, 'UTF-8', $encode);
        }
        return strtoupper(md5($splice));
    }
    private function create_uuid(){
        return sprintf('%04x%04x-%04x-%04x-%04x-%04x%04x%04x',
            mt_rand(0, 0xffff), mt_rand(0, 0xffff),
            mt_rand(0, 0xffff),
            mt_rand(0, 0x0fff) | 0x4000,
            mt_rand(0, 0x3fff) | 0x8000,
            mt_rand(0, 0xffff), mt_rand(0, 0xffff), mt_rand(0, 0xffff)
        );
    }
    //获取拒单原因
    public function getreasons(){
        return array('others'=>'其他原因', 
                           'fakeOrder'=>'用户信息错误', 
                           'contactUserFailed'=>'联系不上用户', 
                           'foodSoldOut'=>'商品已经售完', 
                           'restaurantClosed'=>'商家已经打烊', 
                           'distanceTooFar'=>'超出配送范围', 
                           'restaurantTooBusy'=>'商家现在太忙', 
                           'forceRejectOrder'=>'用户要求取消', 
                           'deliveryFault'=>'暂时无法配送', 
                           'notSatisfiedDeliveryRequirement'=>'不满足起送要求');
    }
    //获取订单状态
    public function getorderstatus($type=1){
        $return_1= array('pending'=>'未生效订单', 
                         'unprocessed'=>'未处理订单', 
                         'refunding'=>'退单处理中', 
                         'valid'=>'已处理的有效订单', 
                         'invalid'=>'无效订单', 
                         'settled'=>'已完成订单');
        $return_2= array('noRefund'=>'未申请退单', 
                         'applied'=>'用户申请退单', 
                         'rejected'=>'店铺拒绝退单', 
                         'arbitrating'=>'客服仲裁中', 
                         'failed'=>'退单失败', 
                         'successful'=>'退单成功');
        if($type=='all'){return $return_1+$return_2;}
        $returnname='return_'.$type;
        if(empty($$returnname))return false;
    }
    private function post($url, $data,$headers='') {
        if(empty($headers)){$headers=array("Content-type: application/json; charset=utf-8", "Accept-Encoding: gzip");}
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt($ch, CURLOPT_USERAGENT, "eleme-openapi-php-sdk");
        curl_setopt($ch, CURLOPT_TIMEOUT, 10);
        curl_setopt($ch, CURLOPT_ENCODING, "gzip");
        $response = curl_exec($ch);
        if (curl_errno($ch)) {return '{"error":"'.curl_error($ch).'"}';}
        curl_close($ch);
        return $response;
    }
    private function get_headers(){
        return array(
            "Authorization: Basic " . base64_encode(urlencode($this->config['appkey']) . ":" . urlencode($this->config['appsecret'])),
            "Content-Type: application/x-www-form-urlencoded; charset=utf-8",
            "Accept-Encoding: gzip");
    }
    /** 
     * HTTP Protocol defined status codes
     * HTTP协议状态码,调用函数时候只需要将$num赋予一个下表中的已知值就直接会返回状态了。
     * @param int $num
     */ 
    private function https($num) { 
        $http = array ( 
            200 => "HTTP/1.1 200 OK",
            400 => "HTTP/1.1 400 Bad Request", 
            401 => "HTTP/1.1 401 Unauthorized", 
            402 => "HTTP/1.1 402 Payment Required", 
            403 => "HTTP/1.1 403 Forbidden", 
            404 => "HTTP/1.1 404 Not Found", 
            500 => "HTTP/1.1 500 Internal Server Error",
        ); 
        header($http[$num]); 
    }
}
?>