微信小程序实现微信登陆(TP5后端)

思路:

  1. 小程序登录获取code,将code传到后台;
  2. 后台用code得到微信用户id,即openid,将openid存储在用户表中,完成绑定
  3. 登录时,再次获取code并传给后台,得到openid,若用户表中存在,便可直接登录

以下仅是代码片段,更多代码在Github

back_end/application/api/controller
mini_program/pages/student_mine
mini_program/pages/login

微信与小程序账号绑定

小程序前端获取code,将code与id传回后台

wx_binding: function () {
    var that = this
    wx.login({
        success: function (res) {
            console.log("code: ", res.code)
            wx.request({
                url: '******/user/wxbinding',
                data: {
                    code: res.code,
                    id: getApp().globalData.user.id,
                },
                method: "POST",
                header: {
                    "Content-Type": "application/x-www-form-urlencoded"
                },
            })
        }
    })
}

ThinkPHP5后端接受到code,用code得到openid,并将openid与账号id绑定

public function wxBinding() {
    $url = "https://api.weixin.qq.com/sns/jscode2session";
    // 参数
    $params = array();
    $params['appid'] = '******';
    $params['secret'] = '******';
    $params['js_code'] = $_POST['code'];
    $params['grant_type'] = 'authorization_code';

    // 微信API返回的session_key 和 openid
    $arr = $this -> httpCurl($url, $params, 'POST');
    $arr = json_decode($arr, true);

    // 判断是否成功
    if (isset($arr['errcode']) && !empty($arr['errcode'])) {
        return json(['error_code' => '2', 'msg' => $arr['errmsg'], "result" => null]);
    }
    $openid = $arr['openid'];

    // 插入openid
    $bind = db('user') -> where('id', $_POST['id']) -> update(['openid' => $openid]);
    if ($bind) {
        return json(['error_code' => '0', 'msg' => '绑定成功']);
    } else {
        // 找不到账号
        return json(['error_code' => '1', 'msg' => '绑定失败']);
    }
}

解密获取openid

use \think\Exception;

function httpCurl($url, $params, $method = 'GET', $header = array(), $multi = false) {
    date_default_timezone_set('PRC');
    $opts = array(
        CURLOPT_TIMEOUT => 30,
        CURLOPT_RETURNTRANSFER => 1,
        CURLOPT_SSL_VERIFYPEER => false,
        CURLOPT_SSL_VERIFYHOST => false,
        CURLOPT_HTTPHEADER => $header,
        CURLOPT_COOKIESESSION => true,
        CURLOPT_FOLLOWLOCATION => 1,
        CURLOPT_COOKIE
            => session_name(). '='.session_id(),
    );

    /* 根据请求类型设置特定参数 */
    switch (strtoupper($method)) {
        case 'GET':
            // $opts[CURLOPT_URL] = $url . '?' . http_build_query($params);
            // 链接后拼接参数  &  非?
            $opts[CURLOPT_URL] = $url. '?'.http_build_query($params);
            break;
        case 'POST':                //判断是否传输文件
            $params = $multi ? $params : http_build_query($params);
            $opts[CURLOPT_URL] = $url;
            $opts[CURLOPT_POST] = 1;
            $opts[CURLOPT_POSTFIELDS] = $params;
            break;
        default:
            throw new Exception('不支持的请求方式!');
    }

    /* 初始化并执行curl请求 */
    $ch = curl_init();
    curl_setopt_array($ch, $opts);
    $data = curl_exec($ch);
    $error = curl_error($ch);
    curl_close($ch);
    if ($error) throw new Exception('请求发生错误:'.$error);
    return $data;
}

微信登录小程序

小程序前端返回code

wx.login({
    success: function (res) {
        console.log("code: ", res.code)
        wx.request({
            url: '******/user/wxlogin',
            data: {
                code: res.code,
            },
            method: "POST",
            header: {
                "Content-Type": "application/x-www-form-urlencoded"
            },
            success: function (res) {
            },
        })
    }
})

后端获取openid,若有用户,返回用户信息给小程序

public function wxLogin() {
    if (empty($_POST['code'])) {
        return json(['error_code' => '1', 'msg' => '请输入code!']);
    }
    $url = "https://api.weixin.qq.com/sns/jscode2session";
    // 参数
    $params = array();
    $params['appid'] = '******';
    $params['secret'] = '******';
    $params['js_code'] = $_POST['code'];
    $params['grant_type'] = 'authorization_code';

    // 微信API返回的session_key 和 openid
    $arr = $this -> httpCurl($url, $params, 'POST');
    $arr = json_decode($arr, true);

    // 判断是否成功
    if (isset($arr['errcode']) && !empty($arr['errcode'])) {
        return json(['error_code' => '2', 'msg' => $arr['errmsg'], "result" => null]);
    }

    $openid = $arr['openid'];
    // $session_key = $arr['session_key'];

    // 从数据库中查找是否有该openid
    $user = db('user') -> where('openid', $openid) -> find();

    if ($user) {
        unset($user['openid']);  // 删除openid
        unset($user['password']);  // 删除密码
        return json(['error_code' => '0', 'msg' => '登录成功', 'data' => $user]);

    } else {
        // 该微信用户没有绑定账号
        return json(['error_code' => '1', 'msg' => '您没有绑定账号,请登录后在“我的”页面绑定~']);
    }
}

学习博客:
小程序和ThinkPHP5结合实现登录状态(附代码)
微信小程序授权登录+Tp5后端
从零开始开发微信小程序(三):微信小程序绑定系统账号并授权登录之微信端

posted @ 2020-07-24 23:27  oeong  阅读(1605)  评论(0编辑  收藏  举报