<?php

namespace App\Http\Controllers\API\H5;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;
use JWT;

class LoginController extends Controller
{
    //微信登录授权获取code ,重新引导页面返回前端
    public function wxGetCode(Request $request) {
        $code = $request->query('code');

        $env= $request->query('state');
        if($env=='production'){
            return redirect(config('app.globals.WxReturnCodeUrl_server').$code);
        }else{
            return redirect(config('app.globals.WxReturnCodeUrl_local').$code);
        }


    }
    public function wxGetOpenid(){
        $result=array();
        $code =request('code');
        $url="https://api.weixin.qq.com/sns/oauth2/access_token?appid=".config('app.globals.WxAppid')."&secret=".config('app.globals.WxAppSecret')."&code=".$code."&grant_type=authorization_code";
        $response = Http::get($url);
        if ($response->successful()) {
            $data = $response->json(); // 获取响应的 JSON 数据
            //dd($data['openid']);
            $openid=$data['openid'];
            $accessTimeout = JWT::GetGetSecretTimeOut();
            $refreshTimeout = JWT::GetRefreshTokenTimeOut();
            $access_token = JWT::BuildJWT('yz','access',$openid,'mH5user',$accessTimeout);
            $refresh_token = JWT::BuildJWT('yz','refresh',$openid,'',$refreshTimeout);
            $result['token']=$access_token;
            $result['refresh_token']=$refresh_token;
            return \Yz::Return(true,'登录成功',$result);
        }else {
            return \Yz::echoError1('获取openid失败');
        }

    }
}
