<?php
/* 
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
define(‘IN_ECS‘, true);
require(dirname(__FILE__) . ‘/includes/init.php‘);
require(dirname(__FILE__) . ‘/includes/lib_code.php‘);
#天猫配置
define(‘TMALL_APPKEY‘,‘你的key‘);
define(‘TMALL_SECRETKEY‘,‘你的appsecret‘);
define(‘TMALL_REDIRECT_URI‘,‘http://172.18.2.142/getsessionkey.php‘);
define(‘TMALL_RETURN_URI‘,‘Location:http://172.18.2.142/index.php‘);
$code = $_GET["code"];
  if (!empty($_GET[‘code‘])) {
      $url = ‘https://oauth.taobao.com/token‘;
      $postfields= array(
                  ‘grant_type‘=>‘authorization_code‘,
                  ‘client_id‘=>TMALL_APPKEY,
                  ‘client_secret‘=>TMALL_SECRETKEY,
                  ‘code‘=>$_GET[‘code‘],
                  ‘redirect_uri‘=>TMALL_REDIRECT_URI
                  );
      $post_data = ‘‘;
      foreach($postfields as $key=>$value){
          $post_data .="$key=".urlencode($value)."&";
      }
      $ch = curl_init();
      curl_setopt($ch, CURLOPT_URL, $url);
      curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
      curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, 0);  
      curl_setopt ($ch, CURLOPT_SSL_VERIFYHOST, 0);
      //指定post数据
      curl_setopt($ch, CURLOPT_POST, true);
      //添加变量
      curl_setopt($ch, CURLOPT_POSTFIELDS, substr($post_data,0,-1));
      $output = curl_exec($ch);
      $httpStatusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
      
      curl_close($ch);
      $a=json_decode($output,true);
      
     // $oOrder = &app::get(‘ome‘)->model(‘taobao_key‘);
      $access_token = $a[‘access_token‘];
      
     //将token插入数据库
//     $time = date(‘Y-m-d H:i:s‘,time());
//     $sql = ‘INSERT INTO  dsc_taobao_sessionkey  (`brand_id`,`time`, `access_token`) VALUES ("","‘.$time.‘","‘.$access_token.‘")‘;
//     $db->query($sql);
    $time = date(‘Y-m-d H:i:s‘,time());
    $table = "dsc_taobao_sessionkey";  
    $field_values = array("time" =>$time, "access_token" =>$access_token);  
    $db->autoExecute($table, $field_values, "INSERT"); 
     
     
     header(TMALL_RETURN_URI);
      }else{
         $url = "https://oauth.taobao.com/authorize";
         $parames = array(
            ‘client_id‘ =>TMALL_APPKEY,
            ‘response_type‘ => ‘code‘,
            ‘redirect_uri‘=>TMALL_REDIRECT_URI,
            ‘state‘=>‘1‘
         );
        $urlcode = ‘‘;
        foreach ($parames as $key=>$value){
            $urlcode .= "$key=".$value.‘&‘;
        }
        $urlcode = substr($urlcode,0,  strlen($urlcode)-1);
        $authUrl = $url.‘?‘.$urlcode;
        //echo $authUrl;die;
        //header("Location:".$authUrl);
        header("Location:".$authUrl);
        
      }
我们访问 172.18.2.142/getsessionkey 时就获取了sessionkey ,将其存入数据库
原文:https://www.cnblogs.com/wujf-myblog/p/9834763.html