首页 > 作文

Laravel 微信小程序后端实现用户登录的示例代码

更新时间:2023-04-08 05:14:25 阅读: 评论:0

接上篇微信小程序后端搭建:分享:laravel 微信小程序后端搭建

后端搭建好后第一件事就是用户登录认证,简单实现微信小程序登录认证

1.ur 模型

u laravel\passport\hasapitokens; 新增

u hasapitokens, notifiable;protected $fillable = [ 'id', 'name', 'email', 'email_verified_at', 'urname', 'phone', 'avatar',//我用来把微信头像的/0清晰图片,存到又拍云上 'weapp_openid', 'nickname', 'weapp_avatar', 'country', 'province', 'city', 'language', 'location', 'gender', 'level',//用户等级 'is_admin',//is管理员];

2. 新增一条路由

//前端小程序拿到的地址:https://域名/api/v1/自己写的接口route::group(['prefix' => '/v1'], function () {  route::post('/ur/login', 'urcontroller@weapplogin');});

3. 在 urcontroller 控制器里新建 function weapplogin (),别忘了 u 这些

u app\ur;u carbon\carbon;u illumimake过去分词nate\http\request;u illuminate\support\facades\storage;

写两个 function weapplogin (),avatarupyun ()

public function weapplogin(request $request)  {    $code = $request->code;    // 根据 code 获取微信 openid 和 ssion_key    $minip梦见小白鼠rogram = \easywechat::miniprogram();    $data = $miniprogram->auth->ssion($code);    if (ist($data['errcode'])) {      return $this->respon->errorunauthorized('code已过期或不正确');    }    $weappopenid = $data['openid'];    $weixinssionkey = $data['ssion_key'];    $nickname = $request->nickname;    $avatar = str_replace('/132', '/0', $request->avatar);//拿到分辨率高点的头像    $country = $request->country?$request->country:'';    $province = $request->province?$request->province:'';    $city = $request->city?$request->city:'';    $gender = $request->gender == '1' ? '1' : '2';//没传过性别的就默认女的吧,体验好些    $language = $request->language?$request->language:'';    //找到 openid 对应的用户    $ur = ur::where('weapp_openid', $weappopenid)->first();    //没有,就注册一个用户    if (!$ur) {      $ur = ur::create([        'weapp_openid' => $weappopenid,        'weapp_ssion_key' => $weixinssionkey,        'password' => $weixinssionkey,        'avatar' => $request->avatar?$this->avatarupyun($avatar):'',        'weapp_avatar' => $avatar,        'nickname' => $nickname,        'country' => $country,        'province' => $province,        'city' => $city,        'gender' => $gender,        'language' => $language,      ]);    }    //如果注册过的,就更新下下面的信息    $attributes['updated_at'] = now();    $attributes['weixin_ssion_key'] = $weixinssionkey;    $attributes['weapp_avatar'] = $avatar;    if ($nickname) {      $attributes['nickname'] = $nickname;    }    if ($request->gender) {      $attributes['gender'] = $gender;    }    // 更新用户数据    $ur->update($attributes);    // 直接创建token并设置有效期    $createtoken = $ur->createtoken($ur->weapp_openid);    $createtoken->token->expires_at = carbon::now()->adddays(30);    $createtoken->token->save();    $token = $createtoken->accesstoken;    return respon()->json([      'access_token' => $token,      'token_type' => "bearer",      'expires_in' => carbon::now()->adddays(30),      'data' => $ur,    ], 200);  }  //我保存到又拍云了,版权归腾讯所有。。。头条闹的  private function avatarupyun($avatar)  {    $avatarfile = file_get_contents($avatar);    $filename = 'avatars/' . uniqid() . '.png';//微信的头像链接我也不知道怎么获取后缀,直接保存成png的了    storage师德师风先进事迹::disk('upyun')->write($filename, $avatarfile);    $wexinavatar = config('filesystems.disks.upyun.protocol') . '://' . config('filesystems.disks.upyun.domain') . '/' . $filename;    return $wexinavatar;//返回链接地址  }

微信的头像 / 0

小头像默认 / 132

4. 后端上面就写好了,再看下小程序端怎么做的哈,打开小程序的 app.json,添加 “pages/auth/auth”,

{ "pages": [  "pages/index/index",  "pages/auth/auth",//做一个登录页面  "pages/logs/logs" ], "window": {  "backgroundtextstyle": "light",  "navigationbarbackgroundcolor": "#fff",  "navigationbartitletext": "wechat",  "navigationbartextstyle": "black" }, "sitemaplocation": "sitemap.json", "permission": {  "scope.urlocation": {   "desc": "你的位置信息将用于小程序位置接口的效果展示"  } }}

5. 打开 auth.js

const app = getapp();page({ /**  * 页面的初始数据  */ data: {  urdata: [],  isclick: fal, }, /**  * 生命周期函数--监听页面加载  */ onload: function(options) { }, login: function(e) {  let that=this  that.tdata({   isclick: true  })  wx.geturinfo({   lang: "zh_cn",   success: respon => {    wx.login({     success: res => {      let data = {       code:res.code,       nickname: respon.urinfo.nickname,       avatar: respon.urinfo.avatarurl,       country: respon.urinfo.country ? respon.urinfo.country : '',       province: respon.urinfo.province ? respon.urinfo.province : '',       city: respon.urinfo.city ? respon.urinfo.city : '',       gender: respon.urinfo.gender ? respon.urinfo.gender : '',       language: respon.urinfo.language ? respon.urinfo.language : '',      }      console.log(data)      app.globaldata.urinfo = data;      wx.request({       url: '你的后端地址',//我用的valet,http://ak.name/api/v1/自来水管防冻ur/login       method: 'post',       data: data,       header: {        'content-type': 'application/x-www-form-urlencoded'       },       success: function (res) {        console.log(res)        if (res.statuscode != '200') {         return fal;        }        wx.tstoragesync('access_token', res.data.access_token)        wx.s大灰狼餐厅etstoragesync('urdata', res.data.data ? res.data.data : '')        wx.redirectto({         url: '/pages/index/index',        })       },       fail: function (e) {        wx.showtoast({         title: '服务器错误',         duration: 2000        });        that.tdata({         isclick: fal        })       },      });     }    })   },   fail: function (e) {    that.tdata({     isclick: fal    })   },  }) }})

6. 打开 auth.wxml

<view class='padding-xl'> <button class='cu-btn margin-top bg-green shadow lg block' open-type="geturinfo" bindgeturinfo="login" disabled="{{isclick}}" type='success'>  <text wx:if="{{isclick}}" class='cuicon-loading2 iconfont-spin'></text> 微信登录</button></view>

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持www.887551.com。

本文发布于:2023-04-08 05:14:17,感谢您对本站的认可!

本文链接:https://www.wtabcd.cn/fanwen/zuowen/8dbc603fe097ddb0ba216c365d76adf3.html

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。

本文word下载地址:Laravel 微信小程序后端实现用户登录的示例代码.doc

本文 PDF 下载地址:Laravel 微信小程序后端实现用户登录的示例代码.pdf

标签:程序   头像   后端   用户
相关文章
留言与评论(共有 0 条评论)
   
验证码:
Copyright ©2019-2022 Comsenz Inc.Powered by © 专利检索| 网站地图