欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  后端开发

PHP调用京东联盟开普勒、宙斯API模板

程序员文章站 2022-03-11 13:27:27
...
本篇文章介绍的内容是PHP调用京东联盟开普勒、宙斯API模板 ,现在分享给大家,有需要的朋友可以参考一下

京东开普勒的 Appkey 和 AppSecret 在这里可以看到(需要先创建应用):http://kepler.jd.com/console/app/app_list.action
授权介绍在这里: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']  <  self::getMillisecond() - 86400000){    //  access_token失效前一天
                //  获取刷新token的url
                $refreshUrl = "https://kploauth.jd.com/oauth/token?grant_type=oauth_refresh_token";//&app_key=yourappkey&app_secret=yourappsecret&refresh_token=xxxxxxxx
                $refreshUrl .= '&app_key='.$this->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);
    }
}

宙斯接口也是大同小异,无非是换了个域名和授权方式

/**
 * 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']  <  self::getMillisecond() - 86400000){    //  access_token失效前一天
                //  获取刷新token的url
                $refreshUrl = "https://oauth.jd.com/oauth/token?";
                $refreshUrl .= '&client_id='.$this->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);
    }
}

以上就是PHP调用京东联盟开普勒、宙斯API模板 的详细内容,更多请关注其它相关文章!

相关标签: api php 开普勒