首页 > 编程语言 >ThinpPHP5.0 微信小程序登录

ThinpPHP5.0 微信小程序登录

时间:2023-11-23 11:11:19浏览次数:29  
标签:return 登录 ThinpPHP5.0 微信 token session userInfo id user

创建WxUser Model类

<?php

namespace app\api\model;
use app\common\controller\Api;
use think\Model; // 引入tp框架的Model类
use think\Db; // 引入 tp 框架的Db类
use think\Cache; // 引入 tp 框架的缓存类
class Wxuser extends Api
{
    private $appId;
    private $appSecret;
    public $errorstr;
    public $token;
    protected $resultSetType = "collection"; // 设置返回类型
    protected $autoWriteTimestamp = true; // 自动记录时间戳
    protected $noNeedLogin = '*';
    protected $noNeedRight = '*';
    ///*** Wxuser constructor
    /// * @param $appId
    /// * @param $appSecret
    ///*/
    public function __construct()
    {
        $appKey = Db::name("appkey")->find(); // 查找管理后台入库的小程序信息
        if($appKey){
            $this->appId = $appKey["appId"];
            $this->appSecret = $appKey["appSecret"];
        }

    }

    /***
     * 获取用户信息
     * @param $token
     * @return null|static
     * @throws \think\exception\DbException
     */
    public static function getUser($token)
    {
        $open_id = Cache::get($token)['openid'];
        $userInfo = DB::name("customer")->where("open_id", $open_id)->find();
        if ($userInfo) {
            $userInfo["createtime"] = date('Y-m-d', $userInfo["createtime"]);
            $userInfo["updatetime"] = date('Y-m-d', $userInfo["updatetime"]);
        }
        return $userInfo;
    }

    /*** 用户登陆*/
    public function login($post)
    {
        // 微信登陆 获取session_key
        $session = $this->wxlogin($post["code"]);
        if(!$session){
            return $session;
        }
        // 自动注册用户
        $user_id = $this->register($session["openid"], $post["nickName"], $post["avatarUrl"], $post["gender"]);
        // 生成token
        $this->token = $this->tokens($session["openid"]);
        // 记录缓存 7天
        Cache::set($this->token, $session, 86400 * 7);
        return $user_id;
    }

    /*** 微信登陆
     * @param $code
     * @return array|mixed
     * @throws \think\exception\DbException
     */
    private function wxlogin($code)
    {
        // 获取当前小程序信息
        if (empty($this->appId) || empty($this->appSecret)) {
            return false;
            //$this->error('appid 和 appsecret 错误');
        }
        // 微信登录 (获取session_key)
        if (!$session = $this->sessionKey($code)) {
            return false;
        }
        return $session;
    }

    /*** 获取session_key
     * @param $code
     * @return array|mixed
     */
    public function sessionKey($code)
    {
        /*** code 换取 session_key
         * ​这是一个 HTTPS 接口,开发者服务器使用登录凭证 code 获取 session_key 和 openid。
         * 其中 session_key 是对用户数据进行加密签名的密钥。为了自身应用安全,session_key 不应该在网络上传输。
         */

        $url = 'https://api.weixin.qq.com/sns/jscode2session';
        $result = json_decode(curl_post($url, ['appid' => $this->appId, 'secret' => $this->appSecret, 'grant_type' => 'authorization_code', 'js_code' => $code]), true);

        if (isset($result['errcode'])) {
            //exit($result['errmsg']);
            $this->errorstr = $result['errmsg'];
            return false;
        }

        return $result;
    }

    /*** 生成用户认证的token
     * @param $openid
     * @return string
     */
    private function tokens($openid)
    {
        return md5($openid . 'token_salt');
    }

    /*** 获取token
     * @return mixed
     */
    public function getToken()
    {
        return $this->token;
    }

    /*** 自动注册用户
     * @param $open_id
     * @param $userInfo
     * @return mixed
     * @throws \think\exception\DbException
     *
     */
    private function register($open_id, $nickName, $avatarUrl, $gender)
    {
        exit;
        $userInfo['open_id'] = $open_id;
        $userInfo['nickname'] = preg_replace('/[\xf0-\xf7].{3}/', '', $nickName);
        $userInfo['avatar'] = $avatarUrl;
        $userInfo['gender'] = $gender + 1;
        $data = Db::name('customer')->where('open_id', $open_id)->find();
        if (!$data) {
            $userInfo['createtime'] = time();
            $userInfo['updatetime'] = time();
            $user_id = Db::name('customer')->insertGetId($userInfo);
            if (!$user_id) {
                return json_encode(['code' => 0, 'msg' => '用户注册失败']);
            }
            return $user_id;
        } else {
            $userInfo['updatetime'] = time();
            Db::name('customer')->where('id', $data['id'])->update($userInfo);
            return $data['id'];
        }
    }

}

控制其中添加登录函数

use app\api\model\Wxuser;

/*** 用户自动登录
     * @return string
     * @throws \think\Exception
     * @throws \think\exception\DbException */
    public function autologin()
    {
        $model = new Wxuser;
        $user_id = $model->login($this->request->param());
        if(!$user_id){
            $this->error('登录失败');
        }
        $token = $model->getToken();
        $this->success('操作成功',['user_id' => $user_id, 'token' => $token]);
    }

    /*** 获取用户信息
     * @return string
     * @throws \think\Exception
     * @throws \think\exception\DbException */
    public function loginInfo()
    {
        if (!$token = $this->request->param("token")) {
            $this->error('缺少必要的参数:token');
        }
        if (!$user = Wxuser::getUser($token)) {
            $this->error('没有找到用户信息');
        }
        $user['token']= setJWT($user);
        $this->success('操作成功', $user);
    }

微信小程序接口调用

标签:return,登录,ThinpPHP5.0,微信,token,session,userInfo,id,user
From: https://www.cnblogs.com/catyxiao/p/17851123.html

相关文章

  • 小程序一键登录按钮与点击事件冲突
    在小程序登录时按照政策要求必须要提醒用户阅读服务协议以及隐私协议,例如这种情况下必须先勾选才能够点击一键登录,否则就会进行弹窗提示。 <buttontype="primary"open-type="getPhoneNumber"@getphonenumber="getPhoneNumber">一键登录</button>但是open-type为getPhoneN......
  • 微信小程序 图片处理前后对比 滑动效果
    此处是封装的组件,如果在页面中需要使用的话需要把lifetimes中的attached方法移动到页面onload事件中,同时调整methods方法列表js//component/sliderimg/sliderimg.jsComponent({/***组件的属性列表*/properties:{},data:{clipPath:'polygon(0%......
  • 陌陌头像留二维码隐藏技术,微信号,双头像生成工具,“codeA”方式开源
    正常情况下我们在陌陌头像留二维码会被系统检测到的,因为它识别到了这是二维码是,就算不封号对账号权重也有营销,但是一些人想在陌陌做一些产品,比如足浴、保健品之类的,想在陌陌引流,那么留二维码头像不封号的实现就非常重要了,我制作的这个工具可以生成干扰码,就是二维码生成干扰码导致......
  • 陌陌头像留微信号二维码不被检测的方法,工具一键生成干扰码,屏蔽系统检测
    正常情况下我们在陌陌头像留二维码会被系统检测到的,因为它识别到了这是二维码是,就算不封号对账号权重也有营销,但是一些人想在陌陌做一些产品,比如足浴、保健品之类的,想在陌陌引流,那么留二维码头像不封号的实现就非常重要了,我制作的这个工具可以生成干扰码,就是二维码生成干扰码导致......
  • 微信小程序隐私授权
    微信小程序开发时,需要用到微信接口则需要处理隐私授权微信小程序用户隐私保护:https://developers.weixin.qq.com/miniprogram/dev/framework/user-privacy/微信小程序用户隐私保护从基础库 2.32.3 开始支持,可查看基础库版本分布进行兼容处理,处理方式可查看:https://www.cnblog......
  • wxid批量转换微信号接口工具,自动转换二维码,开源API分享!
    这个是今天客户定制的,就是从微信群导出了很多WXID,然后实现通过WXID加好友,我就直接调用了微信的接口,说明一下这是微信公开的接口,不存在HOOK或者是逆向技术存在的,公开接口,任何人都可以调用,我就是把接口通过易语言实现了批量生成的功能效果。界面图:  WXID添加效果,不是微信号,是......
  • 微信小程序 在session失效时,自动重新登录
    调试程序的时候经常会碰到很长时间不去碰手机,这样小程序session失效了,但是数据还是存在。去检测一下是否失效,来决定是否需要重新登录:onCheckSessionValid(){setInterval(function(){wx.checkSession({success:function(){//session_key......
  • 微信小程序记住密码,让登录解放双手
    密码是用户最重要的数据,也是系统最需要保护的数据,我们在登录的时候需要用账号密码请求登录接口,如果用户勾选记住密码,那么下一次登录时,我们需要将账号密码回填到输入框,用户可以直接登录系统。我们分别对这种流程进行说明:记住密码在请求登录接口成功后,我们需要判断用户是否勾选记......
  • 如何优雅的使用微信小程序的wx.request请求(封装request.js工具类)
    首先官方的文档不是支持Promise风格的请求我们通过官方文档可以看到微信小程序发请求的一些具体参数,下面的代码展示了用wx.request()发送的一个标准请求:wx.request({     url:"https://xxx.com",     method:"POST",     data:{   ......
  • springboot移动端授权登录请求接口说明
    使用系统内部演示代码,在附件下载方便统一管理用户方便在线用户监控一处编写、处处可用统一鉴权方式1.新增角色、用户组【若已分配可跳过】角色管理-新增专门用于移动等模块-不分配任何后台菜单【DZDS已有】2.新增、修改用户在业务模块添加、修改用户信息,需要同步到sys_user中......