zoukankan      html  css  js  c++  java
  • 京东电商API

    大家好~~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 commonmodelscommon; 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); } }


    好了,这样就昨晚了,什么淘宝,亚马逊,苏宁,唯品会,都是差点儿相同,新年快乐~



  • 相关阅读:
    cmd常用命令
    快捷键
    leetcode:Sort List(一个链表的归并排序)
    leetcode:Merge Two Sorted Lists(有序链表的归并)
    leetcode:Search for a Range(数组,二分查找)
    leetcode:Search a 2D Matrix(数组,二分查找)
    实时操作系统与分时操作系统
    第四章函数作业题,函数模板
    第四章函数作业题,函数的重载
    第四章函数作业题,内置函数
  • 原文地址:https://www.cnblogs.com/mthoutai/p/7133626.html
Copyright © 2011-2022 走看看