<?php
namespace App\Http\Controllers\Api;

use App\Models\User;
use EasyWeChat\Factory;
use Auth;

class PassportController extends Controller
{
    public function login()
    {
       $req = request()->post();
        /* $this->validate(request(), [
            'code'      => 'required',
        ]);*/

        $app = Factory::miniProgram(config('wechat.mini_program.default'));

        $data = $app->auth->session($req['code']);
        $decryptedData = $app->encryptor->decryptData($data['session_key'], $req['iv'], $req['encryptedData']);

        $user = User::where('openid',$decryptedData['openId'])->first();
        if(!$user){
            $user = new User();
            $user->nickname = $decryptedData['nickName'];
            $user->openid = $decryptedData['openId'];
            $user->head_img = $decryptedData['avatarUrl'];
            $user->save();
            $user = User::where('openid',$decryptedData['openId'])->first();
        }

        $token = Auth::guard('api')->fromUser($user);

        return out([
            'token' => 'Bearer ' . $token,
            'user'  => $user
        ]);
    }
}


