1. 程式人生 > >京東電商API

京東電商API

sco lex trim prot exceptio pip ast font lec

大家好~~2016年了~轉眼過去三年了...一年沒有更新博客了.. ..在上一年裏,遇到了幾個好哥們,一起寫程序一起裝逼,以下給大家講述一下工作上遇到的技術問題,由於這個我開始弄的時候也比較麻煩,不知道從何下手,網上資料除了京東的手冊,其余都沒有資料,so~請看


一:首先登錄授權獲取access_token( 請填好自己的參數 )

'https://auth.360buy.com/oauth/authorize?response_type=code&client_id='.Yii::$app->params['JD_client_id'].'&redirect_uri='.Yii::$app->params['JD_callback'],


控制器(因為時間問題,我就不封裝url了)

public function actionCallBack(){

        $url = 'https://auth.360buy.com/oauth/token?grant_type=authorization_code&client_id='.Yii::$app->params['JD_client_id'];
        $url.='&redirect_uri='.Yii::$app->params['JD_callback'].'&code='.Yii::$app->request->get('code').'&client_secret='.Yii::$app->params['JD_app_secret'];

        $result = Common::CURL_GET($url);#這個哪來的呢?事實上就是一個curl操作
        echo '<pre>';
        print_r($result);
        echo '</pre>';
        exit;
    }
Common::GET

 public static function CURL_GET($url)
    {
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
        //https 請求
        if (strlen($url) > 5 && strtolower(substr($url, 0, 5)) == "https") {
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        }

        $output = curl_exec($ch);
        return $output;
    }

請登錄

技術分享


接下你會接受到返回的access_token,(請保存起來)

然後使用access_token請求接口( 事實上就用到一個curl和一個簽名 )

<span style="white-space:pre">	</span> $jd = new JdClient();//這個文件請看下
         $jd->appKey = Yii::$app->params['JD_client_id'];
         $jd->appSecret = Yii::$app->params['JD_app_secret'];
         $jd->accessToken = 'cb0ef5c2-1feb-466a-afe2-ffd5a8294cdd';
         $jd->serverUrl = 'https://api.jd.com/routerjson';
         $jd->method = 'jingdong.dsp.adkcunit.adgroup.get';
         $resp = $jd->execute(['param'=>['id'=>1]], $jd->accessToken);
         echo '<pre>';
         print_r($resp);
         exit;

JdClient文件

<?

php namespace common\models\common; use Yii; class JdClient { public $serverUrl = "http://gw.api.360buy.net/routerjson"; public $accessToken; public $connectTimeout = 0; public $readTimeout = 0; public $appKey; public $appSecret; public $method; public $version = "2.0"; public $format = "json"; private $charset_utf8 = "UTF-8"; private $json_param_key = "360buy_param_json"; protected function generateSign($params) { ksort($params); $stringToBeSigned = $this->appSecret; foreach ($params as $k => $v) { if ("@" != substr($v, 0, 1)) { $stringToBeSigned .= "$k$v"; } } unset($k, $v); $stringToBeSigned .= $this->appSecret; return strtoupper(md5($stringToBeSigned)); } public function curl($url, $postFields = null) { $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_FAILONERROR, false); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); if ($this->readTimeout) { curl_setopt($ch, CURLOPT_TIMEOUT, $this->readTimeout); } if ($this->connectTimeout) { curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $this->connectTimeout); } //https 請求 if (strlen($url) > 5 && strtolower(substr($url, 0, 5)) == "https") { curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); } if (is_array($postFields) && 0 < count($postFields)) { $postBodyString = ""; $postMultipart = false; foreach ($postFields as $k => $v) { if ("@" != substr($v, 0, 1))//推斷是不是文件上傳 { $postBodyString .= "$k=" . urlencode($v) . "&"; } else//文件上傳用multipart/form-data。否則用www-form-urlencoded { $postMultipart = true; } } unset($k, $v); curl_setopt($ch, CURLOPT_POST, true); if ($postMultipart) { curl_setopt($ch, CURLOPT_POSTFIELDS, $postFields); } else { curl_setopt($ch, CURLOPT_POSTFIELDS, substr($postBodyString, 0, -1)); } } $reponse = curl_exec($ch); if (curl_errno($ch)) { throw new Exception(curl_error($ch), 0); } else { $httpStatusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE); if (200 !== $httpStatusCode) { throw new Exception($reponse, $httpStatusCode); } } curl_close($ch); return $reponse; } public function execute($request, $access_token = null) { //組裝系統參數 $sysParams["app_key"] = $this->appKey; $sysParams["v"] = $this->version; $sysParams["method"] = $this->method; $sysParams["timestamp"] = date("Y-m-d H:i:s"); if (null != $access_token) { $sysParams["access_token"] = $access_token; } //獲取業務參數 //$apiParams = $request->getApiParas(); if (isset($request['param'])) { $apiParams = json_encode($request['param']); } else { $apiParams = ''; } $sysParams[$this->json_param_key] = $apiParams; //簽名 $sysParams["sign"] = $this->generateSign($sysParams); //系統參數放入GET請求串 $requestUrl = $this->serverUrl . "?"; foreach ($sysParams as $sysParamKey => $sysParamValue) { $requestUrl .= "$sysParamKey=" . urlencode($sysParamValue) . "&"; } //發起HTTP請求 try { $resp = $this->curl($requestUrl, $apiParams); } catch (Exception $e) { exit('請求失敗'); } //解析JD返回結果 $respWellFormed = false; if ("json" == $this->format) { $respObject = json_decode($resp); if (null !== $respObject) { $respWellFormed = true; foreach ($respObject as $propKey => $propValue) { $respObject = $propValue; } } } else if ("xml" == $this->format) { $respObject = @simplexml_load_string($resp); if (false !== $respObject) { $respWellFormed = true; } } //返回的HTTP文本不是標準JSON或者XML。記下錯誤日誌 /* if (false === $respWellFormed) { $this->logCommunicationError($sysParams["method"],$requestUrl,"HTTP_RESPONSE_NOT_WELL_FORMED",$resp); $result->code = 0; $result->msg = "HTTP_RESPONSE_NOT_WELL_FORMED"; return $result; } //假設JD返回了錯誤碼。記錄到業務錯誤日誌中 if (isset($respObject->code)) { $logger = new LtLogger; $logger->conf["log_file"] = rtrim(JD_SDK_WORK_DIR, '\\/') . '/' . "logs/top_biz_err_" . $this->appKey . "_" . date("Y-m-d") . ".log"; $logger->log(array( date("Y-m-d H:i:s"), $resp )); }*/ return $respObject; } public function exec($paramsArray) { if (!isset($paramsArray["method"])) { trigger_error("No api name passed"); } $inflector = new LtInflector; $inflector->conf["separator"] = "."; $requestClassName = ucfirst($inflector->camelize(substr($paramsArray["method"], 7))) . "Request"; if (!class_exists($requestClassName)) { trigger_error("No such api: " . $paramsArray["method"]); } $session = isset($paramsArray["session"]) ? $paramsArray["session"] : null; $req = new $requestClassName; foreach ($paramsArray as $paraKey => $paraValue) { $inflector->conf["separator"] = "_"; $setterMethodName = $inflector->camelize($paraKey); $inflector->conf["separator"] = "."; $setterMethodName = "set" . $inflector->camelize($setterMethodName); if (method_exists($req, $setterMethodName)) { $req->$setterMethodName($paraValue); } } return $this->execute($req, $session); } }


好了,這樣就昨晚了,什麽淘寶,亞馬遜,蘇寧,唯品會,都是差點兒相同,新年快樂~



京東電商API