【PHP】阿里巴巴开放平台Oauth2.0协议获取access_token

 如果对Oauth2不太熟,有时间的话可以去学习一下之前写的一篇

Oauth2.0 oauth2-server-php的使用Demo,怎么连接redis/可实现thinkphp5/yii/Laravel中使用

阿里巴巴composer 包:

阿里巴巴开放平台SDK

一、获取Code

//获取的code有效时间2分钟

    public function getCode(){    

        #拼接获取Code的URL

        $url='http://gw.api.alibaba.com/openapi';

        $appKey='';

        $appSecret ='';    

        #回调URL

        $redirectUrl = 'http://127.0.0.1/auth.php';

        #生成签名

        $code_arr = array(

            'client_id' => $appKey,

            'redirect_uri' => $redirectUrl,

            'site' => '1688'

        );

        ksort($code_arr);

        $sign_str = '';

        foreach ($code_arr as $key=>$val){

            $sign_str .= $key . $val;

        }

        $code_sign = strtoupper(bin2hex(hash_hmac("sha1", $sign_str, $appSecret, true)));

        $get_code_url = 'http://gw.api.alibaba.com/auth/authorize.htm?client_id='.$appKey.'&site=aliexpress&redirect_uri='.$redirectUrl.'&_aop_signature='.$code_sign;

        $get_code_url;    

    }

 二、拿Code 换access_token

public function gettoken(){

        #根据code获取refresh_token、access_token 

        $url = 'http://gw.api.alibaba.com/openapi';

        $appKey = '';

        $appSecret ='';

        $redirectUrl =  'http://http://127.0.0.1/auth.php';

        #此处code即为上面的方法getCode取得的code值

        $code='';



        #拼接获取token的Url

        $getTokenUrl='https://gw.api.alibaba.com/openapi/http/1/system.oauth2/getToken/'.$appKey;

        $data='grant_type=authorization_code&need_refresh_token=true&client_id='.$appKey.'&client_secret='.$appSecret.'&redirect_uri='.$redirectUrl.'&code='.$code;

        $ch = curl_init();

        curl_setopt($ch, CURLOPT_URL, $getTokenUrl);

        curl_setopt($ch, CURLOPT_POST, true);

        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

        curl_setopt($ch, CURLOPT_POSTFIELDS,$data);

        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

        $result = curl_exec($ch);

        curl_close($ch);

        #打印出返回结果

        print_r(json_decode($result));

        exit;

    }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值