使用 UniApp 实现小程序的微信登录功能(2)

<template> <view>我的页面</view> </template> <script> var loginRes; export default { data() { return {}; }, onLoad() { // 加载定义好的方法 loginRes = this.checkLogin('../my/my', 2); // 没有登录成功,返回空 if (!loginRes) { return; } }, methods: {} }; </script> <style></style>

5.PHP 接口 loginApplets

public function loginApplets(Request $request, UserInfo $userInfo) { // 获取数据 $data['u_openid'] = $request->param('openid', ''); // 验证数据 $rule = [ 'u_openid' => 'require|max:200|min:10' ]; $message = [ 'u_openid.require' => 'openid 不能为空', 'u_openid.max' => 'openid 格式错误', 'u_openid.min' => 'openid 格式错误' ]; $validate = Validate::rule($rule)->message($message); if (!$validate->check($data)) { return json(['code' => 1, 'msg' => $validate->getError(), 'res' => null]); } // 根据 openid 判断是否存在 $where['u_openid'] = $data['u_openid']; $user = $userInfo->selOne($where); if (!$user) { return json(['code' => 1, 'msg' => '还没授权登录、请先授权然后登录', 'res' => $user]); } return json(['code' => 0, 'msg' => '已授权获取到用户的数据', 'res' => $user]); }

6.PHP 接口 appletsUserInfo

public function appletsUserInfo(Request $request, UserInfo $userInfo) { // 获取数据 $data['u_openid'] = $request->param('openid', ''); $data['u_avatarUrl'] = $request->param('avatarUrl', ''); $data['u_city'] = $request->param('city', ''); $data['u_country'] = $request->param('country', ''); $data['u_gender'] = $request->param('gender', ''); $data['u_language'] = $request->param('language', ''); $data['u_nickName'] = $request->param('nickName', ''); // 验证数据 $rule = [ 'u_openid' => 'require|max:200|min:10', 'u_avatarUrl' => 'require', 'u_nickName' => 'require' ]; $message = [ 'u_openid.require' => 'openid 不能为空', 'u_openid.max' => 'openid 格式错误', 'u_openid.min' => 'openid 格式错误', 'u_avatarUrl.require' => '用户头像 不能为空', 'u_nickName.max' => '用户名 格式错误', ]; $validate = Validate::rule($rule)->message($message); if (!$validate->check($data)) { return json(['code' => 1, 'msg' => $validate->getError(), 'res' => null]); } // 根据 openid 判断是否存在 $where['u_openid'] = $data['u_openid']; $user = $userInfo->selOne($where); // 存在、执行修改 if ($user) { $user_res = $userInfo->updOne($where, $data); $res = []; $res['u_id'] = $user['u_id']; $res['u_regtime'] = $user['u_regtime']; } // 不存在、执行添加 if (empty($user)) { $res = []; $res = $data; $res['u_regtime'] = time(); $res['u_id'] = $userInfo->addOne($res); } // 判断是否添加成功 if (empty($res['u_id'])) { return json(['code' => 1, 'msg' => '注册失败,返回重试', 'res' => null]); } return json(['code' => 0, 'msg' => 'ok', 'res' => $res]); }

总结

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:http://www.heiqu.com/879fa26e37a61b53d8f63e6ed5e5de29.html