大家好~~2016年了~转眼过去三年了...一年没有更新博客了.. ..在上一年里,遇到了几个好哥们,一起写程序一起装逼,以下给大家讲述一下工作上遇到的技术问题,由于这个我開始弄的时候也比較麻烦,不知道从何下手,网上资料除了京东的手冊,其余都没有资料,so~请看

一:首先登录授权获取access_token( 请填好自己的參数 )

  1. '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了)

  1. public function actionCallBack(){
  2.  
  3. $url = 'https://auth.360buy.com/oauth/token?grant_type=authorization_code&client_id='.Yii::$app->params['JD_client_id'];
  4. $url.='&redirect_uri='.Yii::$app->params['JD_callback'].'&code='.Yii::$app->request->get('code').'&client_secret='.Yii::$app->params['JD_app_secret'];
  5.  
  6. $result = Common::CURL_GET($url);#这个哪来的呢?事实上就是一个curl操作
  7. echo '<pre>';
  8. print_r($result);
  9. echo '</pre>';
  10. exit;
  11. }

Common::GET

  1. public static function CURL_GET($url)
  2. {
  3. $ch = curl_init($url);
  4. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  5. curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
  6. //https 请求
  7. if (strlen($url) > 5 && strtolower(substr($url, 0, 5)) == "https") {
  8. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
  9. curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
  10. }
  11.  
  12. $output = curl_exec($ch);
  13. return $output;
  14. }

请登录

接下你会接受到返回的access_token,(请保存起来)

然后使用access_token请求接口(  事实上就用到一个curl和一个签名 )

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

JdClient文件

  1. <?
  2.  
  3. php
  4. namespace common\models\common;
  5.  
  6. use Yii;
  7.  
  8. class JdClient
  9. {
  10. public $serverUrl = "http://gw.api.360buy.net/routerjson";
  11.  
  12. public $accessToken;
  13.  
  14. public $connectTimeout = 0;
  15.  
  16. public $readTimeout = 0;
  17.  
  18. public $appKey;
  19.  
  20. public $appSecret;
  21.  
  22. public $method;
  23.  
  24. public $version = "2.0";
  25.  
  26. public $format = "json";
  27.  
  28. private $charset_utf8 = "UTF-8";
  29.  
  30. private $json_param_key = "360buy_param_json";
  31.  
  32. protected function generateSign($params)
  33. {
  34. ksort($params);
  35. $stringToBeSigned = $this->appSecret;
  36. foreach ($params as $k => $v) {
  37. if ("@" != substr($v, 0, 1)) {
  38. $stringToBeSigned .= "$k$v";
  39. }
  40. }
  41. unset($k, $v);
  42. $stringToBeSigned .= $this->appSecret;
  43. return strtoupper(md5($stringToBeSigned));
  44. }
  45.  
  46. public function curl($url, $postFields = null)
  47. {
  48. $ch = curl_init();
  49. curl_setopt($ch, CURLOPT_URL, $url);
  50. curl_setopt($ch, CURLOPT_FAILONERROR, false);
  51. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  52. if ($this->readTimeout) {
  53. curl_setopt($ch, CURLOPT_TIMEOUT, $this->readTimeout);
  54. }
  55. if ($this->connectTimeout) {
  56. curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $this->connectTimeout);
  57. }
  58. //https 请求
  59. if (strlen($url) > 5 && strtolower(substr($url, 0, 5)) == "https") {
  60. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
  61. curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
  62. }
  63.  
  64. if (is_array($postFields) && 0 < count($postFields)) {
  65. $postBodyString = "";
  66. $postMultipart = false;
  67. foreach ($postFields as $k => $v) {
  68. if ("@" != substr($v, 0, 1))//推断是不是文件上传
  69. {
  70. $postBodyString .= "$k=" . urlencode($v) . "&";
  71. } else//文件上传用multipart/form-data。否则用www-form-urlencoded
  72. {
  73. $postMultipart = true;
  74. }
  75. }
  76. unset($k, $v);
  77. curl_setopt($ch, CURLOPT_POST, true);
  78. if ($postMultipart) {
  79. curl_setopt($ch, CURLOPT_POSTFIELDS, $postFields);
  80. } else {
  81. curl_setopt($ch, CURLOPT_POSTFIELDS, substr($postBodyString, 0, -1));
  82. }
  83. }
  84. $reponse = curl_exec($ch);
  85.  
  86. if (curl_errno($ch)) {
  87. throw new Exception(curl_error($ch), 0);
  88. } else {
  89. $httpStatusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
  90. if (200 !== $httpStatusCode) {
  91. throw new Exception($reponse, $httpStatusCode);
  92. }
  93. }
  94. curl_close($ch);
  95. return $reponse;
  96. }
  97.  
  98. public function execute($request, $access_token = null)
  99. {
  100. //组装系统參数
  101. $sysParams["app_key"] = $this->appKey;
  102. $sysParams["v"] = $this->version;
  103. $sysParams["method"] = $this->method;
  104. $sysParams["timestamp"] = date("Y-m-d H:i:s");
  105. if (null != $access_token) {
  106. $sysParams["access_token"] = $access_token;
  107. }
  108.  
  109. //获取业务參数
  110. //$apiParams = $request->getApiParas();
  111. if (isset($request['param'])) {
  112. $apiParams = json_encode($request['param']);
  113. } else {
  114. $apiParams = '';
  115. }
  116. $sysParams[$this->json_param_key] = $apiParams;
  117.  
  118. //签名
  119. $sysParams["sign"] = $this->generateSign($sysParams);
  120. //系统參数放入GET请求串
  121. $requestUrl = $this->serverUrl . "?";
  122. foreach ($sysParams as $sysParamKey => $sysParamValue) {
  123. $requestUrl .= "$sysParamKey=" . urlencode($sysParamValue) . "&";
  124. }
  125. //发起HTTP请求
  126. try {
  127. $resp = $this->curl($requestUrl, $apiParams);
  128. } catch (Exception $e) {
  129. exit('请求失败');
  130. }
  131.  
  132. //解析JD返回结果
  133. $respWellFormed = false;
  134. if ("json" == $this->format) {
  135. $respObject = json_decode($resp);
  136. if (null !== $respObject) {
  137. $respWellFormed = true;
  138. foreach ($respObject as $propKey => $propValue) {
  139. $respObject = $propValue;
  140. }
  141. }
  142. } else if ("xml" == $this->format) {
  143. $respObject = @simplexml_load_string($resp);
  144. if (false !== $respObject) {
  145. $respWellFormed = true;
  146. }
  147. }
  148.  
  149. //返回的HTTP文本不是标准JSON或者XML。记下错误日志
  150. /* if (false === $respWellFormed)
  151. {
  152. $this->logCommunicationError($sysParams["method"],$requestUrl,"HTTP_RESPONSE_NOT_WELL_FORMED",$resp);
  153. $result->code = 0;
  154. $result->msg = "HTTP_RESPONSE_NOT_WELL_FORMED";
  155. return $result;
  156. }
  157.  
  158. //假设JD返回了错误码。记录到业务错误日志中
  159. if (isset($respObject->code))
  160. {
  161. $logger = new LtLogger;
  162. $logger->conf["log_file"] = rtrim(JD_SDK_WORK_DIR, '\\/') . '/' . "logs/top_biz_err_" . $this->appKey . "_" . date("Y-m-d") . ".log";
  163. $logger->log(array(
  164. date("Y-m-d H:i:s"),
  165. $resp
  166. ));
  167. }*/
  168. return $respObject;
  169. }
  170.  
  171. public function exec($paramsArray)
  172. {
  173. if (!isset($paramsArray["method"])) {
  174. trigger_error("No api name passed");
  175. }
  176. $inflector = new LtInflector;
  177. $inflector->conf["separator"] = ".";
  178. $requestClassName = ucfirst($inflector->camelize(substr($paramsArray["method"], 7))) . "Request";
  179. if (!class_exists($requestClassName)) {
  180. trigger_error("No such api: " . $paramsArray["method"]);
  181. }
  182.  
  183. $session = isset($paramsArray["session"]) ? $paramsArray["session"] : null;
  184.  
  185. $req = new $requestClassName;
  186. foreach ($paramsArray as $paraKey => $paraValue) {
  187. $inflector->conf["separator"] = "_";
  188. $setterMethodName = $inflector->camelize($paraKey);
  189. $inflector->conf["separator"] = ".";
  190. $setterMethodName = "set" . $inflector->camelize($setterMethodName);
  191. if (method_exists($req, $setterMethodName)) {
  192. $req->$setterMethodName($paraValue);
  193. }
  194. }
  195. return $this->execute($req, $session);
  196. }
  197. }

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

京东电商API的更多相关文章

  1. Laravel 教程 - 实战 iBrand 开源电商 API 系统

    iBrand 简介 IYOYO 公司于2011年在上海创立.经过8年行业积累,IYOYO 坚信技术驱动商业革新,通过提供产品和服务助力中小企业向智能商业转型升级. 基于社交店商的核心价值,在2016年 ...

  2. 北京望京SOHO-电商墨镜面试题

    我去面试,boos 给出了个.动态规划的题目: ‘’‘’‘’ A = "asdf" B = "axazxcv" S = "axasazdxfcv&qu ...

  3. TOP100summit:【分享实录】京东1小时送达的诞生之路

    本篇文章内容来自2016年TOP100summit 京东WMS产品负责人李亚曼的案例分享. 编辑:Cynthia 李亚曼:京东 WMS产品负责人.从事电商物流行业近10年,有丰富的物流行业经验,独立打 ...

  4. HTTP结构

    HTTP结构 转载请注明出处:HTTP结构简介 HTTP通信过程包括从客户端发往服务器的请求和服务器返回客户端的响应,这篇文章就简单的了解一下HTTP请求和响应的结构与协议本身的状态管理. 用户HTT ...

  5. Kubernetes 之上的架构应用

    规划并运转一个兼顾可扩展性.可移植性和健壮性的运用是一件很有应战的事情,尤其是当体系杂乱度在不断增长时.运用或体系 本身的架构极大的影响着其运转办法.对环境的依靠性,以及与相关组件的耦合强弱.当运用在 ...

  6. (转)Terraform,自动化配置与编排必备利器

    本文来自作者 QingCloud实践课堂 在 GitChat 上分享 「Terraform,自动化配置与编排必备利器」 Terraform - Infrastructure as Code 什么是 T ...

  7. SourceTree Win10 安装过程及配置

    SourceTree 是一款拥有可视化界面的项目版本控制软件,适用于git项目管理,同时它集成了 git flow 工作流程,对于不熟悉 git 命令的初学者来说,可以通过 SourceTree 快速 ...

  8. iPhone换电池是原装电池好还是换第三方大容量电池好?

    转:https://www.xianjichina.com/news/details_60791.html 最近这段时间苹果降速门事件持续发酵,闹得满城风雨.尽管苹果公司两次致歉,很多果粉都去更换电池 ...

  9. 使用acme.sh快速生成SSL证书

    起因 早上收到了一封来自MySSL EE <noreply@notify.myssl.com>的邮件提示证书即将过期, 少于7天,但是acme.sh应该是60天自动renew的.于是查看下 ...

随机推荐

  1. bootstrap3无间距栅格/grid no-gutter

    <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8&quo ...

  2. android cmd adb命令安装和删除apk应用

    copy自http://blog.csdn.net/xpsharp/article/details/7289910 1. 安装Android应用程序 1) 启动Android模拟器 2) adb in ...

  3. PHP fSQL Tutorial

    PHP fSQL Tutorial This tutorial is designed to give a brief overview of the PHP fSQL API since versi ...

  4. java web 学习笔记 - jsp用的文件上传组件 SmartUpload

    ---恢复内容开始--- 1. SmartUpload 此控件在jsp中被广泛的使用,而FileUpload控件主要是用在框架中 2. 如果想要使用,需要在tomcat的lib目录中,将SmartUp ...

  5. Unable to start ServletWebServerApplicationContext due to missing ServletWebServerFactory bean

    WebsocketSourceConfiguration { @Bean ServletWebServerFactory servletWebServerFactory(){ return new T ...

  6. CAD多个点构造选择集(网页版)

    主要用到函数说明: IMxDrawSelectionSet::SelectByPolygon 在多个点组合的闭合区域里,构造选择集.详细说明如下: 参数 说明 [in] IMxDrawPoints* ...

  7. docker 1-->docker swarm 转载

    实践中会发现,生产环境中使用单个 Docker 节点是远远不够的,搭建 Docker 集群势在必行.然而,面对 Kubernetes, Mesos 以及 Swarm 等众多容器集群系统,我们该如何选择 ...

  8. Invalid ON UPDATE clause for 'create_date' column

    高版本的mysql导数据到低版本出现的问题 日期类型报错 解决方式:将datetime DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP COMMENT  中的  ON ...

  9. Java中对象流使用的一个注意事项

    再写jsp的实验作业的时候,需要用到java中对象流,但是碰到了之前没有遇到过的情况,改bug改到崩溃!!记录下来供大家分享 如果要用对象流去读取一个文件,一定要先判断这个文件的内容是否为空,如果为空 ...

  10. Linux 安装 Tomcat 详解

    说明:安装的 tomcat 为解压版(即免安装版):apache-tomcat-8.5.15.tar.gz (1)使用 root 用户登录虚拟机,在根目录下的 opt 文件夹新建一个 software ...