WeChat-微信小程序登录api设计

10 篇文章 0 订阅

1.小程序请求getToken接口【参数:code】

	/**
     * 获取token接口
     */
	public function getToken(Request $request)
    {
        $code = $request->param('code');

        if (empty($code)) {
            throw new ParameException('code参数不能为空');
        }

        $userToken = new UserToken($code);
        $token = $userToken->get();

        $cacheToken = Cache::get($token);
        $cacheTokenJson = json_decode($cacheToken);

        if (empty($cacheTokenJson->user_id)) {
            throw new ParameException('系统缓存错误!请联系开发人员');
        }

        return $token;
    }

2.:路径:app\userapi\service\UserToken【服务】

	/**
     * 获取token接口
     */
class UserToken extends Token
{
    protected $code;
    protected $wxAppID;
    protected $wxAppSecret;
    protected $wxLoginUrl;

    /**
     * UserToken constructor.
     * @param $code
     */
    function __construct($code)
    {
        $this->code = $code;
        $this->wxAppID = Config('wx.app_id');
        $this->wxAppSecret = Config('wx.secret');
        //  拼接url拼接访问微信接口
        $this->wxLoginUrl = 'https://api.weixin.qq.com/sns/jscode2session' . 
        					$this->wxAppID . 
        					$this->wxAppSecret . 
        					$this->code;
    }

    //	模拟发送get方式发送http请求微信服务器

    public function get()
    {
        //  发送get请求(字符串)
        $result = curl_get($this->wxLoginUrl);
        $wxResult = json_decode($result, true);

        if (empty($wxResult)) {
            // 为什么以empty判断是否错误,这是根据微信返回
            // 规则摸索出来的
            // 这种情况通常是由于传入不合法的code
            throw new ParameException('获取session_key及openid异常,微信内部错误');
        }

        // 建议用明确的变量来表示是否成功
        // 微信服务器并不会将错误标记为400,无论成功还是失败都标记成200
        // 这样非常不好判断,只能使用errcode是否存在来判断
        $loginFail = array_key_exists('errcode',$wxResult);

        if ($loginFail) {
            throw new ParameException($wxResult['errmsg']);
        }

        return $this->grantToken($wxResult);
    }

	private function grantToken($wxResult)
    {
        //  拿到openid
        //  检查当前openid是否已经存在        1.如果存在,则不做处理,       2.如果不存在那么新增一条user记录
        //  生成令牌,准备缓存数据,写入缓存
        //  把令牌返回到客户端去
        //  key:令牌
        //  value wxResult,user_id,scope

        //  获取微信返回的openid
        $openid = $wxResult['openid'];

        //  1.如果存在,则不做处理,       2.如果不存在那么新增一条user记录
        $userFind = UserModel::getbyOpenID($openid);

        //  拼接-缓存数组
        $cacheValue = $this->prepareCacheValue($wxResult,$userFind->id);

        return $this->saveToken($cacheValue);
    }
	
	/**
     * 拼接缓存数据
     * @param $wxResult
     * @param $user_id
     * @return
     */
    private function prepareCacheValue($wxResult,$user_id)
    {
        $cacheValue['openid'] = $wxResult['openid'];
        $cacheValue['session_key'] = $wxResult['session_key'];
        $cacheValue['user_id'] = $user_id;
        $cacheValue['scope'] = 16;

        return $cacheValue;
    }


	/**
	 *	添加缓存数据
     * @param $cacheValue
     * @return string
     * @throws ParameException
     * @author:  deng    (2019/4/10 11:22)
     */
    private function saveToken($cacheValue)
    {
        //  生产令牌的方法
        $key = $this->createToken();

        //  数组格式转换json字符串
        $value = json_encode($cacheValue);

        $expire_in = Config::get('setting.token_expire_in');

        $result = cache($key, $value , $expire_in);

        if (!$result) {
            throw new ParameException('服务器缓存异常');
        }

        return $key;
    }

3.路径:app/config/wx.php

<?php

// +----------------------------------------------------------------------
// | 微信配置设置
// +----------------------------------------------------------------------
return [
    'app_id' => 'wx777777777777e',
    'secret' => '242ea8e550cad7a5ff8e3fdb5e1bed555',
    'login_url' => "https://api.weixin.qq.com/sns/jscode2session?".
        "appid=s%&secret=s%&js_code=s%&grant_type=authorization_code"
];

4.路径: app/commom.php
// ±---------------------------------------------------------------------
// | 发送get请求
// ±---------------------------------------------------------------------

function curl_get($url, &$httpCode = 0)
{
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);

    //  不做证书效验,部署在Linux环境下请改为true
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 10);
    $file_contents = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    return $file_contents;
}

5.:路径:app\common\model\UserModel.php 【模型】

	/**
     * 自动解码base64
     * @return bool|string
     */
	public function getNickNameAttr()
    {
        return htmlentities(base64_decode($this->getData('nick_name')));
    }
    
	public static function getbyOpenID($openid)
    {
        //  判断当前openid是否存在,
        $userFind = self::where('openid','=',$openid)
            ->find();
        if (empty($userFind)) {
            $userFind = self::create([
                'openid' => $openid,
                'add_time' => date('Y-m-d H:i:s')
            ]);
        }

        return $userFind;
    }
如何把code和手机号同时获取
1.用户进入【我的】,然后提示未登陆,
2.点击登陆,后,提示输入验证码,手机号,
3.验证通过时,传递
code,注册用户并添加手机号
性名性别,手机号,,验证码,code
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值