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

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

1.user 模型

use laravel\passport\hasapitokens; 新增

use hasapitokens, notifiable;

protected $fillable = [

'id',

'name',

'email',

'email_verified_at',

'username',

'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('/user/login', 'usercontroller@weapplogin');

});

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

use app\user;

use carbon\carbon;

use illuminate\http\request;

use illuminate\support\facades\storage;

写两个 function weapplogin (),avatarupyun ()

public function weapplogin(request $request)

{

$code = $request->code;

// 根据 code 获取微信 openid 和 session_key

$miniprogram = \easywechat::miniprogram();

$data = $miniprogram->auth->session($code);

if (isset($data['errcode'])) {

return $this->response->errorunauthorized('code已过期或不正确');

}

$weappopenid = $data['openid'];

$weixinsessionkey = $data['session_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 对应的用户

$user = user::where('weapp_openid', $weappopenid)->first();

//没有,就注册一个用户

if (!$user) {

$user = user::create([

'weapp_openid' => $weappopenid,

'weapp_session_key' => $weixinsessionkey,

'password' => $weixinsessionkey,

'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_session_key'] = $weixinsessionkey;

$attributes['weapp_avatar'] = $avatar;

if ($nickname) {

$attributes['nickname'] = $nickname;

}

if ($request->gender) {

$attributes['gender'] = $gender;

}

// 更新用户数据

$user->update($attributes);

// 直接创建token并设置有效期

$createtoken = $user->createtoken($user->weapp_openid);

$createtoken->token->expires_at = carbon::now()->adddays(30);

$createtoken->token->save();

$token = $createtoken->accesstoken;

return response()->json([

'access_token' => $token,

'token_type' => "bearer",

'expires_in' => carbon::now()->adddays(30),

'data' => $user,

], 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

aaa4da2ed174e4ffd6b618a3a9d36eec.png

小头像默认 / 132

f443b518adfd1e13f31d849f8ab32db2.png

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.userlocation": {

"desc": "你的位置信息将用于小程序位置接口的效果展示"

}

}

}

5. 打开 auth.js

const app = getapp();

page({

/**

* 页面的初始数据

*/

data: {

userdata: [],

isclick: false,

},

/**

* 生命周期函数--监听页面加载

*/

onload: function(options) {

},

login: function(e) {

let that=this

that.setdata({

isclick: true

})

wx.getuserinfo({

lang: "zh_cn",

success: response => {

wx.login({

success: res => {

let data = {

code:res.code,

nickname: response.userinfo.nickname,

avatar: response.userinfo.avatarurl,

country: response.userinfo.country ? response.userinfo.country : '',

province: response.userinfo.province ? response.userinfo.province : '',

city: response.userinfo.city ? response.userinfo.city : '',

gender: response.userinfo.gender ? response.userinfo.gender : '',

language: response.userinfo.language ? response.userinfo.language : '',

}

console.log(data)

app.globaldata.userinfo = data;

wx.request({

url: '你的后端地址',//我用的valet,http://ak.name/api/v1/user/login

method: 'post',

data: data,

header: {

'content-type': 'application/x-www-form-urlencoded'

},

success: function (res) {

console.log(res)

if (res.statuscode != '200') {

return false;

}

wx.setstoragesync('access_token', res.data.access_token)

wx.setstoragesync('userdata', res.data.data ? res.data.data : '')

wx.redirectto({

url: '/pages/index/index',

})

},

fail: function (e) {

wx.showtoast({

title: '服务器错误',

duration: 2000

});

that.setdata({

isclick: false

})

},

});

}

})

},

fail: function (e) {

that.setdata({

isclick: false

})

},

})

}

})

6. 打开 auth.wxml

微信登录

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

如您对本文有疑问或者有任何想说的,请点击进行留言回复,万千网友为您解惑!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值