<?php
/**
 * 公众号授权登录
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/9/6
 * Time: 14:16
 */
define('IA_ROOT', '');
error_reporting(E_ERROR);
date_default_timezone_set("Asia/Shanghai");
defined('BASE_ROOT') or define('BASE_ROOT', str_replace('/public/php', '', str_replace('\\', '/', realpath(dirname(__FILE__) . '/')) . "/"));
defined('SITE_PATH') or define('SITE_PATH', BASE_ROOT);
defined('PUBLIC_PATH') or define('PUBLIC_PATH', SITE_PATH . 'public/');
define('EXTEND_PATH', BASE_ROOT . 'extend/');
// 定义应用目录
define('APP_PATH', SITE_PATH . 'app/');

// 加载 Composer 自动加载
require_once SITE_PATH . 'vendor/autoload.php';

// 加载自定义配置
if (file_exists(PUBLIC_PATH . 'php/yb.version.php')) {
    require_once PUBLIC_PATH . 'php/yb.version.php';
}

use think\facade\Db;
use think\facade\Log;
use think\App;
use think\facade\Request;
use addons\channel_wxgzh\service\WechatAuth;
use addons\channel_wxgzh\service\UserService;

// 初始化应用
$http = (new App(SITE_PATH))->http;
$response = $http->run();

$mch_id = Request::instance()->param("mch_id", '');
$page = Request::instance()->param("page", '');
$id = Request::instance()->param("id", '');
$scope_type = Request::instance()->param("scope_type", 'snsapi_base'); // 授权方式

if (strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger') !== false) {
    $page = urlencode($page);
    //获取code
    $code = Request::instance()->param("code");
    if (empty($code)) {
        $url = get_localhost_domain(false, true, true) . "/public/php/wechat.php?mch_id=" . $mch_id . '&id=' . $id . '&scope_type=' . $scope_type . '&page=' . $page;
        $we_chat = new WechatAuth($mch_id); //实例化类
        $we_chat->accredit($url, $scope_type); //调用方法
    } else {
        $userService = new UserService();
        $userService->CheckUser($code, $mch_id, $page, $id, $scope_type);
    }
} else {
    if (!empty($id)) {
        $page = "$page&id=$id";
    }
    //商城配置
    $wap_path = 'h5';
    $url = get_localhost_domain(false, true, true) . "/$wap_path/$mch_id/#/$page";
    header("Location:$url");
    exit();
}
