京东电商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 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);
    }
}

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



通用接口实现类LinkJOS 扩展于:public class LinkJOS extends LinkOAuth2(LinkOAuth2 extends JspEasy) 构造函数 LinkJOS(HttpServletRequest request,HttpServletResponse response) 京东JOS接口访问函数 public String link2(String link,String method,Bag sys,Bag apps,String appSecret,String file,String FileField) 作用:访问京东JOS平台的所有接口 参数: String link,京东JOS平台接口访问地址,目前固定为:https://api.jd.com/routerjson String method,向京东JOS平台提交数据时的方法,需要应用级别参数时建议用POST方法,不需要时用GET(参见后边的实例) Bag sys,系统级别参数书包(一般只需在接口参数文件中放入接口方法即可,参见后边的实例) Bag apps,应用级别参数书包(在接口参数文件中放入必须的应用级别参数,若不需要应用级别参数时直接用new Bag(-1)构造一个空书包即可,参见后边的实例) String appSecret,应用证书中的App Secret,前边已经设置,固定用"@{pPage:app_secret}"即可 String file,调用上传文件接口上传文件(如图片)到京东JOS平台时的文件全名(含相对路径,如:images/logo.png),不是调用上传文件接口时为空字符串即可(参见后边的实例) String FileField,调用上传文件接口上传文件(如图片)到京东JOS平台时的字段名,配合前边的参数,不是调用上传文件接口时为空字符串即可(参见后边的实例) 返回为京东JOS平台接口对应的JSON格式的字符串 JSON文本解析方法 public void parseJson(String json) 作用:解析京东JOS平台接口返回的JSON格式的字符串,并根据内容生成N个对应的书包 参数:String json,京东JOS平台接口返回的JSON格式的字符串 根据JSON文本的内容在系统中生成N个书包,根书包名称为j0,下一层的josn文本内容生成的书包名称用上一层的Key放在上一层的书名中,下边用实例说明寻找对应书包的方法: 如店铺信息查询接口jingdong.vender.shop.query返回的json文本为 { "jingdong_vender_shop_query_responce": { "shop_jos_result": { "open_time": "", "shop_id": "", "category_main_name": "", "category_main": "", "vender_id": "", "brief": "", "logo_url": "", "shop_name": "" } } } 找出店铺信息书包名的方法如下 @{j0:jingdong_vender_shop_query_responce} @{@{pPage:bag}:shop_jos_result} 这时候的@{pPage:bag}即为需要的店铺信息书包名 具体用法请阅读下载包中的《京东卖家如何快速开发网店工具软件》
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值