load->_model('Model_aapeizhi','aapeizhi'); $this->load->_model("Model_logic_ding",'logic_ding'); } public $base_url = "https://apis.fedex.com.cn"; public $f_config = [ "account"=>"692362136", "key"=>"l7c6ae3d27cce34bdca31cf6e0ff4af125", 'secret' =>'475eb390bf334bda8b5f44f1c07b7c10', "client_id"=>"l7c6ae3d27cce34bdca31cf6e0ff4af125", "client_secret"=>"475eb390bf334bda8b5f44f1c07b7c10", //追物流轨迹的 'track_key'=>"l71bded23966b144df9fc01956f6dd655d", 'track_secret'=>"61730ddbae764dcba70f4737cdaaa6e7" ]; public function getAccessToken(){ $res = $this->setting->find("skey='fedex_v1_access_token'"); if($res){ if(time() > $res['expiretime']){ $this->setting->query("DELETE FROM `crowd_setting` WHERE `skey`='fedex_v1_access_token'"); return $this->makeAccessToken(); } return $res['svalue']; }else{ return $this->makeAccessToken(); } } public function makeAccessToken(){ $url = "/oauth/token"; $headers = [ "Content-Type:application/x-www-form-urlencoded", ]; $params = [ "grant_type"=>"client_credentials", "client_id"=> $this->f_config['client_id'], "client_secret"=> $this->f_config['client_secret'], ]; $params=http_build_query($params); $res = $this->sendPost($url,$params,$headers); if(isset($res['access_token'])){ $this->setting->insert([ 'skey'=>"fedex_v1_access_token", 'svalue' => $res['access_token'], 'expiretime' => time() + 3600 -10 ]); } return $res['access_token']; } public function getTrackToken(){ $res = $this->setting->find("skey='fedex_v1_track_access_token'"); if($res){ if(time() > $res['expiretime']){ $this->setting->query("DELETE FROM `crowd_setting` WHERE `skey`='fedex_v1_track_access_token'"); return $this->makeTrackToken(); } return $res['svalue']; }else{ return $this->makeTrackToken(); } } public function makeTrackToken(){ $url = "/oauth/token"; $headers = [ "Content-Type:application/x-www-form-urlencoded", ]; $params = [ "grant_type"=>"client_credentials", "client_id"=> $this->f_config['track_key'], "client_secret"=> $this->f_config['track_secret'], ]; $params=http_build_query($params); $res = $this->sendPost($url,$params,$headers); if(isset($res['access_token'])){ $this->setting->insert([ 'skey'=>"fedex_v1_track_access_token", 'svalue' => $res['access_token'], 'expiretime' => time() + 3600 -10 ]); } return $res['access_token']; } private function setData($order_info){ $customer_streets = []; $customer_streets[] = $order_info['address']; if(!empty($order_info['address2'])){ $customer_streets[] = $order_info['address2']; } $state_codes = $this->aapeizhi->getFedexStateCode(); $hgbm = 67041900; if(isset($order_info['hgbm'])) { if($order_info['hgbm'] != '') { $hgbm = $order_info['hgbm']; } } $params = [ "labelResponseOptions"=>"URL_ONLY", "accountNumber"=>[ "value"=> (int)$this->f_config['account'] ], "requestedShipment"=>[ "shipper"=>[ "contact"=>[ "personName"=>"LONGYI", "phoneNumber"=>"18539006340", "companyName"=>"LONGYI", ], "address"=>[ "streetLines"=> [ "1403, Buliding C, Bodi Center", "NingWei Street, XiaoShan" ], "city"=>"Hangzhou", "stateOrProvinceCode"=>"", "postalCode"=>310000,//杭州邮编 "countryCode"=>$order_info['warehouse']['lb'] ], ], "recipients"=>[ [ "contact" => [ "personName"=>$order_info['name'], "phoneNumber"=>$order_info['phone'], "companyName"=>$order_info['client'] ], "address"=>[ "streetLines" =>$customer_streets, "city"=>$order_info['city'], "stateOrProvinceCode"=>strlen($order_info['province'])==2?strtoupper($order_info['province']):$state_codes[strtolower($order_info['province'])], "postalCode"=>(string)$order_info['zipcode'], "countryCode"=>$order_info['lb'], ], ] ], "shipDatestamp"=>date("Y-m-d"), "serviceType"=>($order_info['js'] == 3)?"FEDEX_INTERNATIONAL_PRIORITY":"FEDEX_INTERNATIONAL_CONNECT_PLUS", "packagingType"=> "FEDEX_PAK", "pickupType"=>"DROPOFF_AT_FEDEX_LOCATION", "blockInsightVisibility"=>false, "shippingChargesPayment"=>[ "paymentType"=>"SENDER" //运费承担人 ], "shipmentSpecialServices"=>[ "specialServiceTypes"=>[ "ELECTRONIC_TRADE_DOCUMENTS", ], "etdDetail"=>[ "requestedDocumentTypes"=>[ "COMMERCIAL_INVOICE" ] ] ], "shippingDocumentSpecification"=>[ "shippingDocumentTypes"=>[ "COMMERCIAL_INVOICE" ], "commercialInvoiceDetail"=>[ "documentFormat"=>[ "docType"=>"PDF", "stockType"=>"PAPER_LETTER" ], "customerImageUsages"=>[ [ "id"=> "IMAGE_1", "type"=> "SIGNATURE", "providedImageType"=> "SIGNATURE" ], [ "id"=> "IMAGE_2", "type"=> "LETTER_HEAD", "providedImageType"=> "LETTER_HEAD" ] ] ] ], "rateRequestType"=>['LIST'], "labelSpecification"=>[ "imageType"=>"PDF", "labelStockType"=>"STOCK_4X6", "customerSpecifiedDetail"=>[ "docTabContent"=>[ "docTabContentType"=>"STANDARD" ] ] ], "customsClearanceDetail"=>[ "dutiesPayment"=>[ "paymentType"=>"SENDER",//税费承担方 ], "documentContent"=>"COMMODITY", "commodities"=>[ [ "numberOfPieces"=>$order_info['zjs'], "description"=>"CNHLT1403HAN/".$order_info['sbbm']."/".$order_info['sbpm'].'-'.$order_info['ts'].'PCS', "countryOfManufacture"=> "CN", 'harmonizedCode'=> $hgbm,//海关编码 "quantity"=> $order_info['ts'], "quantityUnits"=> "cm", "unitPrice"=> [ "amount"=> $order_info['dtsbjz'], "currency"=> "USD" ], "customsValue"=> [ "amount"=>$order_info['zsbjz'], "currency"=> "USD" ], "weight"=> [ "units"=> "KG", "value"=> 0.4 ] ] ] ], "requestedPackageLineItems"=>[ [ "weight"=>[ "units"=>"KG", "value"=>0.4 ], "customerReferences"=>[ [ "customerReferenceType"=>"CUSTOMER_REFERENCE", "value"=>$order_info['number'] ] ], // "packageSpecialServices"=>[ // // "signatureOptionType"=>($order_info['qm']==1)?"ADULT":"", // ] ], ] ] ]; if($order_info['qm']==1){ $params['requestedShipment']['requestedPackageLineItems'][0]["packageSpecialServices"]= [ "signatureOptionType"=>"ADULT", ]; } // echo "
";
        // var_dump($params);
        // die;
        return $params;
    }

    //上传货物信息 获取运单    托运
    public function get_data($order_info){
        try{
            $url = "/ship/v1/shipments";
            $headers = [
                "x-customer-transaction-id"=>$order_info['number'],
                "Content-Type:application/json",
                "Authorization: Bearer ".$this->getAccessToken(),
                "x-locale" => "en_US",//这个是语种加国家
                "Accept: application/json",
            ];
            // echo "
";
            // var_dump("Bearer ".$this->getAccessToken());
            
            $params = $this->setData($order_info);
            $this->logic_ding->sendToDing("发货单请求的参数".json_encode($params));
            //var_dump($params);
            $params=json_encode($params);
            //var_dump($params);
            $start_time = time();
            $res =  $this->sendPost($url,$params,$headers);
            //var_dump(json_encode($res,JSON_UNESCAPED_UNICODE));
            $end_time = time();
            if( $end_time - $start_time  > 15){
                $this->logic_ding->addJobs('outtime_order',['number'=>$order_info['number']]);
            }
            //var_dump($res);
            //die;
            if(isset($res['code']) && $res['code'] == -1){
                return array('x'=>'0','Description'=>$res['msg']);
            }
            if(!isset($res["transactionId"])){
                return array('x'=>'0','Description'=>'请求异常');
            }
            if(isset($res["errors"])){
    
                return array('x'=>'0','Description'=>json_encode($res["errors"]));
            }
            $invoice_url = "";
            foreach($res['output']['transactionShipments'][0]['shipmentDocuments'] as $v){
                if($v['contentType'] == "COMMERCIAL_INVOICE"){
                    $invoice_url = $v['url'];
                }
            }
            return 
                [   
                    'x'=>'1',
                    'waybill'=>$res['output']['transactionShipments'][0]['masterTrackingNumber'],
                    'label'=>$res['output']['transactionShipments'][0]['pieceResponses'][0]['packageDocuments'][0]['url'],
                    'invoice'=>$invoice_url,
                ];
        }catch(Exception $e){
            $error_msg = "error:[fedexv1]创建发货单出错".$e->getMessage()."|".$e->getLine()."|".$e->getFile()."|请求参数".json_encode($order_info,JSON_UNESCAPED_UNICODE);
            $this->logic_ding->sendToDing($error_msg);
            if(isset($res)){
                $error_msg = "error:[fedexv1]创建发货单出错".$e->getMessage()."|".$e->getLine()."|".$e->getFile()."|返回参数".json_encode($res,JSON_UNESCAPED_UNICODE);
                $this->logic_ding->sendToDing($error_msg);
            }
        }
        
    }

    //根据单号获取 快递信息
    public function  get_logistics($number){
        $url = "/track/v1/trackingnumbers";
        $params = [
           "includeDetailedScans"=>false,
           "trackingInfo"=>[
                [
                    "trackingNumberInfo"=>[
                        "trackingNumber"=> $number['waybill']
                    ]
                ]
           ]
        ];
        $headers = [
            "Content-Type:application/json",
            "Authorization: Bearer ".$this->getTrackToken(),
            "x-locale" => "en_US",//这个是语种加国家
            "Accept: application/json",
        ];
        $params=json_encode($params);
        var_dump(json_encode($headers));
        var_dump($params);
        var_dump($this->getTrackToken());
        $res =  $this->sendPost($url,$params,$headers);
        var_dump(json_encode($res));
        echo "
";
        var_dump($res);
    }


    public function sendPost($url,$params,$headers){
       
        // var_dump($bodyString);
      
        // 设置请求的URL
        $all_url = $this->base_url.$url;
       
        //var_dump($all_url);
        // 初始化cURL会话
        $ch = curl_init($all_url);
        // 设置cURL选项 
        $options = array(
            CURLOPT_SSL_VERIFYPEER=>false,
            CURLOPT_SSL_VERIFYHOST=>false,
            CURLOPT_RETURNTRANSFER => true,   
            CURLOPT_POST => true,             
            CURLOPT_POSTFIELDS => $params,  
            CURLOPT_HTTPHEADER => $headers,
            CURLOPT_ENCODING => "gzip,deflate"
        );

        
        // 应用这些选项到cURL会话
        curl_setopt_array($ch, $options);

        // 执行cURL会话并获取响应
        $response = curl_exec($ch);
        // 检查是否有错误发生
        if ($response === false) {
            $error = curl_error($ch);
            curl_close($ch);
            return [
                "code"=> -1,
                "msg"=> $error
            ];
        }

        // 关闭cURL会话
        curl_close($ch);
        
        // 输出响应内容
        return json_decode($response,true);
    }


    //上传数字签名 和 信头  接口在 文件上传api    主要就传一次 用postman传就行 不费事了  etd 必须先传
    public function upload_img(){
         $all_url = "https://documentapitest.prod.fedex.com/sandbox/documents/v1/lhsimages/upload";
       
    }
    public function send_sign(){
        $params = [
            "document"=>[
                "referenceId"=>"1234",
                "name"=>"sign.png",
                "contentType"=>"image/png",
                "meta"=>[
                    "imageType"=>"SIGNATURE",
                    "imageIndex"=>"IMAGE_1"
                ]
            ],
            "rules"=>[
               "workflowName"=> "LetterheadSignature"
            ]
        ];

        $body = [
            'document'=>json_encode($params),
            'attachment'=>new CURLFile("D:\wwwroot\cerp.wepolicy.cn\sign.png")
        ];
        $headers = [
            "x-customer-transaction-id"=>time(),
            "Content-Type:multipart/form-data",
            "Authorization: Bearer ".$this->getAccessToken(),
            "x-locale" => "en_US",//这个是语种加国家
            "Accept: application/json",
        ];
        $r = $this->send_img_post($body,$headers);
        echo "
";
        var_dump($r);
    }
    public function send_xintou(){
        $params = [
                    "document"=>[
                        "referenceId"=>"1234",
                        "name"=>"Logo.png",
                        "contentType"=>"image/png",
                        "meta"=>[
                            "imageType"=>"LETTERHEAD",
                            "imageIndex"=>"IMAGE_2"
                        ]
                    ],
                    "rules"=>[
                       "workflowName"=> "LetterheadSignature"
                    ]
                ];
        $body = [
            'document'=>json_encode($params),
            'attachment'=>new CURLFile("D:\wwwroot\cerp.wepolicy.cn\Logo.png")
        ];
        $headers = [
            "x-customer-transaction-id"=>time(),
            "Content-Type:multipart/form-data",
            "Authorization: Bearer ".$this->getAccessToken(),
            "x-locale" => "en_US",//这个是语种加国家
            "Accept: application/json",
        ];
        $r = $this->send_img_post($body,$headers);
        echo "
";
        var_dump($r);
    }
    public function send_img_post($body,$headers){
        $upload_img_url = "/documents/v1/lhsimages/upload";
        $all_url = "https://documentapi.prod.fedex.com/documents/v1/lhsimages/upload";
       
        var_dump($all_url);
        var_dump($body);
        // 初始化cURL会话
        $ch = curl_init($all_url);
        // 设置cURL选项 
        $options = array(
            CURLOPT_SSL_VERIFYPEER=>false,
            CURLOPT_SSL_VERIFYHOST=>false,
            CURLOPT_RETURNTRANSFER => true,   
            CURLOPT_POST => true,             
            CURLOPT_POSTFIELDS => $body,  
            CURLOPT_HTTPHEADER => $headers,
            CURLOPT_ENCODING => "gzip,deflate"
        );

        
        // 应用这些选项到cURL会话
        curl_setopt_array($ch, $options);

        // 执行cURL会话并获取响应
        $response = curl_exec($ch);
        // 检查是否有错误发生
        if ($response === false) {
            $error = curl_error($ch);
            curl_close($ch);
            return [
                "code"=> -1,
                "msg"=> $error
            ];
        }

        // 关闭cURL会话
        curl_close($ch);
        
        // 输出响应内容
        return json_decode($response,true);
    }

}