被访问页面路由
Route::middleware('auth:api')->get('account_folder','Api\KeyController@account_folder')->name('account_folder');
小程序登录调用,返回token
<?php
namespace App\Http\Controllers\Api;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\Http\Model\Users;
use App\Http\Model\UsersThreeLogin;
use Illuminate\Support\Str;
class LoginController extends BaseController
{
public function __construct()
{
header("Access-Control-Allow-Origin: *");
$this->user = new Users;
$this->login = new UsersThreeLogin;
$this->auth = new Auth;
}
/**
* 微信小程序登陆
* 参数:code
* 返回:token
* **/
public function wxlogin(Request $request){
//获取微信此次登陆的code
$code = $request->input('code','');
if(!$code){return false;}
//获取微信服务器的session key 和 openid
//{session_key: "owHKU3lYInmxs0FnxLBBQw==", openid: "oKU7W5c452ETBhEvbTbYCfYpEWUY"}
$url = "https://api.weixin.qq.com/sns/jscode2session?appid=".Config('hcode.xcx_appId')."&secret=".Config('hcode.xcx_appSecret')."&js_code=".$code."&grant_type=authorization_code";
$login_info = file_get_contents($url);
$login_info = json_decode($login_info,true);
//$login_info = ['session_key' => '8u9QuJrqUbP1uBmixzzCKg==','openid' => 'oKU7W5c452ETBhEvbTbYCfYpEWUY '];
//查询比对openid,查找用户
$user_info = $this->login::where('openid',$login_info['openid'])->first('user_id');
$token = Str::random(60);
if($user_info){
//登录
$flight = $this->user::find($user_info['user_id']);
$flight->api_token = $token;
$flight->prevtime = time();
$flight->save();
}else{
//存储用户
$param = [
'name'=>'用户'.rand(10000,99999),
'group_id'=>1,
'api_token'=>$token,
'prevtime'=>time(),
'created_at'=>date('Y-m-d H:i:s'),
'updated_at'=>date('Y-m-d H:i:s'),
'loginip'=>$request->getClientIp(),
];
$user_id = $this->user->insertGetId($param);
//插入微信登陆的关联表数据
$this->login->user_id = $user_id;
$this->login->openid = $login_info['openid'];
$this->login->session_key = $login_info['session_key'];
$this->login->type = 1;
$this->login->save();
}
echo json_encode($token);
}
}