laravel api验证

被访问页面路由

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);
    }



}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值