实现Token身份权限体系(二)

  1. 我们知道code是要小程序向微信服务器请求的一个code码,使用的是wx.login接口。在小程序调用我们Token模型中的getToken接口时,并传入一个code码参数,之后我们的getToken接口接收该code参数后再携带code参数调用微信的接口来获取openid和session_key。我们将该微信接口地址写入配置文件中。
  2. 在config目录下,创建wechat.php配置文件,写入小程序相关配置信息
<?php

return [
    'app_id' => '填你自己的小程序ID',
    'app_secret' =>'填你自己的小程序secret',
    'login_url' =>'https://api.weixin.qq.com/sns/jscode2session?'.
    "appid=%s&secret=%s&js_code=%s&grant_type=authorization_code"
];
  1. 编写UserToken类
<?php

namespace app\api\service;



class UserToken extends Token
{
    protected $code;
    protected $wxAppID;
    protected $wxAppSecret;
    protected $wxLoginUrl;

    public function __construct($code)
    {
        $this->code = $code;
        $this->wxAppID = config('wechat.app_id');
        $this->wxAppSecret = config('wechat.app_secret');
        $this->wxLoginUrl = sprintf(config('wechat.login_url'), $this->wxAppID, $this->wxAppSecret, $this->code, $this->code);
    }
}
  1. 编写UserToken类的get方法,我们需要使用php去curl发起http请求,很多地方都会用到,所以我们编写一个公共函数(commen.php文件)。这里抛出的Exception我们用TP5内置的,因为该错误不需要返回给客户端,只供服务端使用。大部分都是经验性的编码,参考即可。
function curl_get($url)
{
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
    $res = curl_exec($ch);
    curl_close($ch);;
    return $res;
}
  1. UserToken类的get方法
public function get()
    {
        $result = curl_get($this->wxLoginUrl);
        $wxResult = json_decode($result, true);
        if (empty($wxResult)) {
            throw new Exception('获取session_key及openID时异常,微信内部错误');
        } else {
            $fail = array_key_exists('errcode', $wxResult);
            if ($fail) {
               
            }
        }
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值