| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517 | <?phpclass Model_Fedexv1 extends Lin_Model {    function __construct(){            parent::__construct();            $this->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 "<pre>";        // 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 "<pre>";            // var_dump("Bearer ".$this->getAccessToken());                        $params = $this->setData($order_info);            $this->logic_ding->sendToDing("fedex发货单请求的参数".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));            $this->logic_ding->sendToDing("fedex发货单回执参数"."【".$order_info['number']."】".json_encode($res,JSON_UNESCAPED_UNICODE));            //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'];                }            }            $end_time = time();            if( $end_time - $start_time  > 45){                $this->logic_ding->addJobs('outtime_order',['number'=>$order_info['number']]);            }            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 "<pre>";        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 "<pre>";        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 "<pre>";        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);    }}
 |