京东电商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);
- }
- }
好了,这样就昨晚了,什么淘宝,亚马逊,苏宁,唯品会,都是差点儿相同,新年快乐~
京东电商API的更多相关文章
- Laravel 教程 - 实战 iBrand 开源电商 API 系统
iBrand 简介 IYOYO 公司于2011年在上海创立.经过8年行业积累,IYOYO 坚信技术驱动商业革新,通过提供产品和服务助力中小企业向智能商业转型升级. 基于社交店商的核心价值,在2016年 ...
- 北京望京SOHO-电商墨镜面试题
我去面试,boos 给出了个.动态规划的题目: ‘’‘’‘’ A = "asdf" B = "axazxcv" S = "axasazdxfcv&qu ...
- TOP100summit:【分享实录】京东1小时送达的诞生之路
本篇文章内容来自2016年TOP100summit 京东WMS产品负责人李亚曼的案例分享. 编辑:Cynthia 李亚曼:京东 WMS产品负责人.从事电商物流行业近10年,有丰富的物流行业经验,独立打 ...
- HTTP结构
HTTP结构 转载请注明出处:HTTP结构简介 HTTP通信过程包括从客户端发往服务器的请求和服务器返回客户端的响应,这篇文章就简单的了解一下HTTP请求和响应的结构与协议本身的状态管理. 用户HTT ...
- Kubernetes 之上的架构应用
规划并运转一个兼顾可扩展性.可移植性和健壮性的运用是一件很有应战的事情,尤其是当体系杂乱度在不断增长时.运用或体系 本身的架构极大的影响着其运转办法.对环境的依靠性,以及与相关组件的耦合强弱.当运用在 ...
- (转)Terraform,自动化配置与编排必备利器
本文来自作者 QingCloud实践课堂 在 GitChat 上分享 「Terraform,自动化配置与编排必备利器」 Terraform - Infrastructure as Code 什么是 T ...
- SourceTree Win10 安装过程及配置
SourceTree 是一款拥有可视化界面的项目版本控制软件,适用于git项目管理,同时它集成了 git flow 工作流程,对于不熟悉 git 命令的初学者来说,可以通过 SourceTree 快速 ...
- iPhone换电池是原装电池好还是换第三方大容量电池好?
转:https://www.xianjichina.com/news/details_60791.html 最近这段时间苹果降速门事件持续发酵,闹得满城风雨.尽管苹果公司两次致歉,很多果粉都去更换电池 ...
- 使用acme.sh快速生成SSL证书
起因 早上收到了一封来自MySSL EE <noreply@notify.myssl.com>的邮件提示证书即将过期, 少于7天,但是acme.sh应该是60天自动renew的.于是查看下 ...
随机推荐
- bootstrap3无间距栅格/grid no-gutter
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8&quo ...
- android cmd adb命令安装和删除apk应用
copy自http://blog.csdn.net/xpsharp/article/details/7289910 1. 安装Android应用程序 1) 启动Android模拟器 2) adb in ...
- PHP fSQL Tutorial
PHP fSQL Tutorial This tutorial is designed to give a brief overview of the PHP fSQL API since versi ...
- java web 学习笔记 - jsp用的文件上传组件 SmartUpload
---恢复内容开始--- 1. SmartUpload 此控件在jsp中被广泛的使用,而FileUpload控件主要是用在框架中 2. 如果想要使用,需要在tomcat的lib目录中,将SmartUp ...
- Unable to start ServletWebServerApplicationContext due to missing ServletWebServerFactory bean
WebsocketSourceConfiguration { @Bean ServletWebServerFactory servletWebServerFactory(){ return new T ...
- CAD多个点构造选择集(网页版)
主要用到函数说明: IMxDrawSelectionSet::SelectByPolygon 在多个点组合的闭合区域里,构造选择集.详细说明如下: 参数 说明 [in] IMxDrawPoints* ...
- docker 1-->docker swarm 转载
实践中会发现,生产环境中使用单个 Docker 节点是远远不够的,搭建 Docker 集群势在必行.然而,面对 Kubernetes, Mesos 以及 Swarm 等众多容器集群系统,我们该如何选择 ...
- Invalid ON UPDATE clause for 'create_date' column
高版本的mysql导数据到低版本出现的问题 日期类型报错 解决方式:将datetime DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP COMMENT 中的 ON ...
- Java中对象流使用的一个注意事项
再写jsp的实验作业的时候,需要用到java中对象流,但是碰到了之前没有遇到过的情况,改bug改到崩溃!!记录下来供大家分享 如果要用对象流去读取一个文件,一定要先判断这个文件的内容是否为空,如果为空 ...
- Linux 安装 Tomcat 详解
说明:安装的 tomcat 为解压版(即免安装版):apache-tomcat-8.5.15.tar.gz (1)使用 root 用户登录虚拟机,在根目录下的 opt 文件夹新建一个 software ...