Przeglądaj źródła

添加fedex到线上

lvhao 6 miesięcy temu
rodzic
commit
5a5c45c749

+ 69 - 0
core/CoreApp/models/Model_aapeizhi.php

@@ -0,0 +1,69 @@
+<?php
+/**
+ * 此类是记录一些常用的配置数据
+ * */
+class Model_aapeizhi extends Lin_Model {
+    
+    function __construct(){
+		parent::__construct();
+    } 
+
+    public function getFedexStateCode(){
+        return [
+            'alabama'=>'To the',
+            'alaska'=>'AK',
+            'arizona'=>'THAT',
+            'arkansas'=>'AR',
+            'california'=>'CA',
+            'colorado'=>'CO',
+            'connecticut'=>'CT',
+            'delaware'=>'OF',
+            'district of columbia'=>'DC',
+            'florida'=>'FL',
+            'georgia'=>'GA',
+            'hawaii'=>'HI',
+            'idaho'=>'ID',
+            'illinois'=>'THE',
+            'indiana'=>'IN',
+            'iowa'=>'IA',
+            'kansas'=>'KS',
+            'kentucky'=>'KY',
+            'louisiana'=>'THE',
+            'maine'=>'ME',
+            'maryland'=>'MD',
+            'massachusetts'=>'BUT',
+            'michigan'=>'ME',
+            'minnesota'=>'MN',
+            'mississippi'=>'MS',
+            'missouri'=>'MO',
+            'montana'=>'MT',
+            'nebraska'=>'NE',
+            'nevada'=>'NV',
+            'new hampshire'=>'NH',
+            'new jersey'=>'NJ',
+            'new mexico'=>'NM',
+            'new york'=>'NY',
+            'north carolina'=>'NC',
+            'north dakota'=>'ND',
+            'ohio'=>'OH',
+            'oklahoma'=>'OK',
+            'oregon'=>'OR',
+            'pennsylvania'=>'PA',
+            'rhode island'=>'RE',
+            'south carolina'=>'SC',
+            'south dakota'=>'SD',
+            'tennessee'=>'TN',
+            'texas'=>'TX',
+            'utah'=>'OUT',
+            'vermont'=>'VT',
+            'virginia'=>'VA',
+            'washington'=>'WA',
+            'west virginia'=>'WV',
+            'wisconsin'=>'WI',
+            'wyoming'=>'WY',
+            'puerto rico'=>'PR',
+        ];
+    }
+    
+
+}

+ 402 - 0
core/CoreApp/models/Model_fedexv1.php

@@ -0,0 +1,402 @@
+<?php
+class 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",
+    ];
+
+    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'];
+    }
+    
+    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();
+        $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_BOX",
+                 "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"
+                        ]
+                    ]
+                 ],
+                 "labelSpecification"=>[
+                    "imageType"=>"PDF",
+                    "labelStockType"=>"STOCK_4X6",
+                    "customerSpecifiedDetail"=>[
+                        "docTabContent"=>[
+                            "docTabContentType"=>"STANDARD"
+                        ]
+                    ]
+                 ],
+
+                 "customsClearanceDetail"=>[
+                    "dutiesPayment"=>[
+                        "paymentType"=>"SENDER",
+                    ],
+                    "documentContent"=>"COMMODITY",
+                    "commodities"=>[
+                        [
+                            "description"=>$order_info['sbpm'].'-'.$order_info['ts'].'PCS',
+                            "countryOfManufacture"=> "CN",
+                             "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
+                        ]
+                    ]
+                 ]
+
+            ]
+        ];
+        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);
+            $params=json_encode($params);
+            var_dump($params);
+            $res =  $this->sendPost($url,$params,$headers);
+            var_dump(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'];
+                }
+            }
+            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){
+
+    }
+
+
+    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);
+    }
+
+}