search
HomeBackend DevelopmentPHP TutorialPHP calls JD Alliance Kepler and Zeus API templates

This article introduces the content of PHP calling JD Alliance Kepler and Zeus API templates. Now I share it with everyone. Friends in need can refer to

JD Kepler’s Appkey and AppSecret here. You can see (you need to create an application first): http://kepler.jd.com/console/app/app_list.action
Authorization introduction is here: http://kepler.jd.com/console/docCenterCatalog/docContent ?channelId=17

/*开普勒类*/
class KeplerApi{
    private $appKey = 'YourKey';    //  你的Key
    private $appScret = 'YourSecret';   //  你的Secret
    private $app_token_json = '{}'; //  第一次需要手动授权获取京东Token然后粘贴到这里
     /**
     * 获取开普勒接口数据
     * @param string $apiUrl    要获取的api
     * @param string $param_json   该api需要的参数
     * @param string $version   版本可选为 2.0
     * @param bool $get 是否使用get,默认为post方式
     * @return mixed    京东返回的json格式的数据
     */
    public function GetKelperApiData($apiUrl='',$param_json = array(),$version='1.0',$get=false){

        $API['access_token'] = $this->refreshAccessToken(); //  生成的access_token,30天一换
        $API['app_key'] = $this->appKey;
        $API['method'] = $apiUrl;
        $API['param_json'] = json_encode($param_json);
        $API['sign_method'] = 'md5';
        $API['timestamp'] = date('Y-m-d H:i:s',time());
        $API['v'] = $version;
        ksort($API);    //  排序
        $str = '';      //  拼接的字符串
        foreach ($API as $k=>$v) $str.=$k.$v;
        $sign = strtoupper(md5($this->appScret.$str.$this->appScret));    //  生成签名    MD5加密转大写
        if ($get){
            //  用get方式拼接URL
            $url = "https://router.jd.com/api?";
            foreach ($API as $k=>$v)
                $url .= urlencode($k) . '=' . urlencode($v) . '&';  //  把参数和值url编码
            $url .= 'sign='.$sign;  //  接上签名
            $res = self::curl_get($url);
        }else{
            //  用post方式获取数据
            $url = "https://router.jd.com/api";
            $API['sign'] = $sign;
            $res = self::curl_post($url,$API);
        }
        return $res;
    }
    //  刷新accessToken
    private function refreshAccessToken(){
        $filePath = dirname(dirname(__FILE__)).'/Config/KelperToken.config';     //  Token文本保存路径
        if (file_exists($filePath)){
            $handle = fopen($filePath,'r');
            $tokenJson = fread($handle,8142);
        }else{
            //  插入默认的token
            fwrite(fopen($filePath,'w'),$this->app_token_json);
            $tokenJson = $this->app_token_json;
        }

        if (substr($tokenJson, 0,3) == pack('CCC',0xef,0xbb,0xbf)) {
            $tokenJson = substr($tokenJson, 3);
        }
        $res = json_decode(trim($tokenJson),true);   //  解析不了可能是文本出了问题,注意BOM头
        //  判断
        if ($res['code'] == 0){
            if ($res['expires_in']*1000 + $res['time']  appKey;
                $refreshUrl .= '&app_secret='.$this->appScret;
                $refreshUrl .= '&refresh_token='.$res['refresh_token'];
                //  获取新的token数据
                $newAccessTokenJson = self::curl_get($refreshUrl);
                //  写入文本
                fwrite(fopen($filePath,'w'),$newAccessTokenJson);
                //  解析成数组
                $newAccessTokenArr = json_decode($newAccessTokenJson,true);
                $accessToken = $newAccessTokenArr['access_token'];
            }else{
                $accessToken = $res['access_token'];
            }
            return $accessToken;
        }else{
            //  如果refresh_token过期,将会返回错误码code:2011;msg:refresh_token过期
            return $res['msg'];
        }
    }
    //  get请求
    private static function curl_get($url){
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_HEADER, FALSE);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_REFERER, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
        $result = curl_exec($ch);
        curl_close($ch);
        return $result;
    }
    //  post请求
    private static function curl_post($url,$curlPost){
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_HEADER, false);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_REFERER, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $curlPost);
        $result = curl_exec($ch);
        curl_close($ch);
        return $result;
    }
    //  获取13位时间戳
    private static function  getMillisecond(){
        list($t1, $t2) = explode(' ', microtime());
        return sprintf('%.0f',(floatval($t1)+floatval($t2))*1000);
    }
}

The Zeus interface is also similar, except that the domain name and authorization method are changed

/**
 * Class ZeusApi 宙斯接口调用类
 */
class ZeusApi
{
    private $appKey = 'YourKey';    //  你的Key
    private $appScret = 'YourSecret';   //  你的Secret
    private $app_token_json = '{}'; //  第一次需要手动授权获取京东Token然后粘贴到这里

    /**
     * 获取宙斯接口数据
     * @param string $apiUrl    要获取的api
     * @param string $param_json    该api需要的参数,使用json格式,默认为 {}
     * @param string $version   版本可选为 2.0
     * @param bool $get 是否使用get,默认为post方式
     * @return mixed    京东返回的json格式的数据
     */
    public function GetZeusApiData($apiUrl='',$param_json = array(),$version='1.0',$get=false){
        $API['access_token'] = $this->refreshAccessToken(); //  生成的access_token,30天一换
        $API['app_key'] = $this->appKey;
        $API['method'] = $apiUrl;
        $API['360buy_param_json'] = json_encode($param_json);
        $API['timestamp'] = date('Y-m-d H:i:s',time());
        $API['v'] = $version;
        ksort($API);    //  排序
        $str = '';      //  拼接的字符串
        foreach ($API as $k=>$v) $str.=$k.$v;
        $sign = strtoupper(md5($this->appScret.$str.$this->appScret));    //  生成签名    MD5加密转大写
        if ($get){
            //  用get方式拼接URL
            $url = "https://api.jd.com/routerjson?";
            foreach ($API as $k=>$v)
                $url .= urlencode($k) . '=' . $v . '&';  //  把参数和值url编码
            $url .= 'sign='.$sign;
            $res = self::curl_get($url);
        }else{
            //  用post方式获取数据
            $url = "https://api.jd.com/routerjson?";
            $API['sign'] = $sign;
            $res = self::curl_post($url,$API);
        }
        return $res;
    }
    //  刷新accessToken
    private function refreshAccessToken(){
        $filePath = dirname(dirname(__FILE__)).'/Config/ZeusToken.config';     //  Token文本保存路径
        if (file_exists($filePath)){
            $handle = fopen($filePath,'r');
            $tokenJson = fread($handle,8142);
        }else{
            //  插入默认的token
            fwrite(fopen($filePath,'w'),$this->app_token_json);
            $tokenJson = $this->app_token_json;
        }
        
        if (substr($tokenJson, 0,3) == pack('CCC',0xef,0xbb,0xbf)) {
            $tokenJson = substr($tokenJson, 3);
        }
        $res = json_decode(trim($tokenJson),true);   //  解析不了可能是文本出了问题
        //  判断
        if ($res['code'] == 0){
            if ($res['expires_in']*1000 + $res['time']  appKey;
                $refreshUrl .= '&client_secret='.$this->appScret;
                $refreshUrl .= '&grant_type=refresh_token';
                $refreshUrl .= '&refresh_token='.$res['refresh_token'];
                //  获取新的token数据
                $newAccessTokenJson = self::curl_get($refreshUrl);
                //  写入文本
                fwrite(fopen($filePath,'w'),$newAccessTokenJson);
                //  解析成数组
                $newAccessTokenArr = json_decode($newAccessTokenJson,true);
                $accessToken = $newAccessTokenArr['access_token'];
            }else{
                $accessToken = $res['access_token'];
            }
            return $accessToken;
        }else{
            //  如果refresh_token过期,将会返回错误码code:2011;msg:refresh_token过期
            return $res['msg'];
        }
    }
    //  get请求
    private static function curl_get($url){
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_HEADER, FALSE);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_REFERER, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
        $result = curl_exec($ch);
        curl_close($ch);
        return $result;
    }
    //  post请求
    private static function curl_post($url,$curlPost){
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_HEADER, false);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_REFERER, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $curlPost);
        $result = curl_exec($ch);
        curl_close($ch);
        return $result;
    }
    //  获取13位时间戳
    private static function  getMillisecond(){
        list($t1, $t2) = explode(' ', microtime());
        return sprintf('%.0f',(floatval($t1)+floatval($t2))*1000);
    }
}

                 

The above is the detailed content of PHP calls JD Alliance Kepler and Zeus API templates. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software