laravel微信小程序授权

最近在对接微信小程序

其中有授权登录,可以获取微信用户的昵称及手机号

在laravel中如何实现

首先执行`composer require overtrue/wechat:~4.0 -vvv`

为分取用户openid

获取手机号

以下为代码

```
config('app.mini_program_appid'),
'secret' => config('app.mini_program_secret')
];

$this->app = Factory::miniProgram($wechat_config);
}

//授权登录获取openid
public function fetchOpenid(Code $request){
$code = $request->input('code');
$appid = config('app.mini_program_appid');
$secret = config('app.mini_program_secret');
$url = "https://api.weixin.qq.com/sns/jscode2session?appid=$appid&secret=$secret&js_code=$code&grant_type=authorization_code";
$content = Http::post($url);
$data = json_decode($content,true);
return $this->jsonData($data);
}

//获取手机号
public function fetchPhone(FetchPhone $request){
$session_key = $request->input('session_key');
$iv = $request->input('iv');
$encryptedData = $request->input('encrypted_data');
try{
$res = $this->app->encryptor->decryptData(
$session_key,
$iv,
$encryptedData
);
return $this->jsonData($res);
} catch (\Exception $e) {
return $this->jsonError('session_key无效');
}
}

//添加用户信息
public function updateUserInfo(UpdateUserInfo $request){
$res = UserMiniProgrameService::updateUserInfo($request);
if(!$res){
return $this->jsonError('添加失败');
}
return $this->jsonData('修改成功');
}

//获取用户信息
public function fetchUserInfo(Request $request){
if(!$request->openid) return $this->jsonError('openid不能为空');
$user = UserMiniProgrameService::getUserByOpenid($request['openid']);
if($user && $user->nickname && $user->mobile){
$time = time() + 3600*24;
$user['token'] = auth('miniprogram')->claims(['exp' => $time])->login($user);
return $this->jsonData($user);
}else{
return $this->jsonData($user);
}
}

public function removeOpenid(Request $request){
UserMiniProgrameService::removeOpenid($request->id);
return $this->jsonData('删除成功');
}

//通过token获取用户信息
public function fetchUserInfoByToken(){
$user = auth('miniprogram')->user();
if($user){
return $this->jsonData($user);
}else{
return $this->jsonError('token无效');
}
}
}
```

详细请看`https://www.hongfs.cn/2019/07/php/laravel/laravel-wechat-mini-program-authorization/`

    A+
发布日期:2022年12月29日  所属分类:未分类

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: