ThinpPHP5.0 微信小程序登录

创建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);
    }

微信小程序接口调用

posted @ 2023-11-23 11:04  鲨鱼大王  阅读(52)  评论(0编辑  收藏  举报