<?php
/**
 * Created by PhpStorm.
 * User: gevnc
 * Date: 2018/5/15
 * Time: 19:07
 */

$backurl = "http://activity.test.care001.cn/brainstorming/wxlogin.php?redirect=".urlencode($_GET["redirect"]);
$appSecret ='07ce7633ed54bc4bbd7b0b338b9583d8';
$appid = "wxfd4edda1018cd4ab";
$appSecret ='07ce7633ed54bc4bbd7b0b338b9583d8';
$returnUrl = "http://m.test.care001.cn/wxmp/code/";
$code = isset($_GET["code"])? $_GET["code"]:"";
$action = isset($_GET["action"])? $_GET["action"]:"";
if($action=="login"){
    $url  = 'https://open.weixin.qq.com/connect/oauth2/authorize';
    $url .= '?appid='.$appid;
    $url .= '&redirect_uri='.$returnUrl;
    $url .= '&response_type=code';
    $url .= '&scope=snsapi_userinfo';
    $url .= '&state=snsapi_userinfo';
    $url .= '#wechat_redirect';
    setcookie('oauth_url',base64_encode($backurl),0,"/","care001.cn");

    logger($_GET["redirect"]);
    header('location:'.$url);
}else{
    if(!empty($code)) {
        $url = 'https://api.weixin.qq.com/sns/oauth2/access_token';
        $url .= '?appid=' . $appid;
        $url .= '&secret=' . $appSecret;
        $url .= '&code=' . $code;
        $url .= '&grant_type=authorization_code';

        $result = json_decode(_httpGet($url), true);
        $url = 'https://api.weixin.qq.com/sns/userinfo?access_token=' . $result["access_token"];
        $url .= '&openid=' . $result["openid"];
        $url .= '&lang=zh_CN';

        $ret = json_decode(_httpGet($url), true);
        if (!empty($ret["openid"])) {
            setcookie("oauth_open_id", $ret["openid"], 0, "/","care001.cn");
            setcookie("oauth_avatar", $ret["headimgurl"], 0,"/", "care001.cn");
            setcookie("oauth_nickname", $ret["nickname"], 0,"/", "care001.cn");
            setcookie("oauth_platform", "微信", 0, "/","care001.cn");
            logger($_GET["redirect"]);
            header("location:" . $_GET["redirect"]);
        } else {
            exit("login fail1");
        }
    }else{
        die("login fail2");
    }
}

function _httpGet($url) {
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_TIMEOUT, 500);
    curl_setopt($curl, CURLOPT_URL, $url);
    $res = curl_exec($curl);
    curl_close($curl);
    return $res;
}

function logger($data){
    $log_file = 'log'.date('Ymd',time()).'_all.log';
    $content =var_export($data,TRUE);
    $content .= "\r\n\n";
    file_put_contents($log_file,$content, FILE_APPEND);
}
