1. 程式人生 > >ecshop第三方登陸之微信登入

ecshop第三方登陸之微信登入


    $appid = 'XXXXX';
    $appsecret = 'XXXXXXX';

    if (empty($code))
    show_message('授權失敗', '返回首頁', '', 'wrong');
    
    $token_url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid='.$appid.'&secret='.$appsecret.'&code='.$code.'&grant_type=authorization_code';
    $token = json_decode(file_get_contents($token_url));
    if (isset($token->errcode))
    {
        show_message($token->errmsg, '返回首頁', '', 'wrong');
    }
    $access_token_url = 'https://api.weixin.qq.com/sns/oauth2/refresh_token?appid='.$appid.'&grant_type=refresh_token&refresh_token='.$token->refresh_token;

    $access_token = json_decode(file_get_contents($access_token_url));
    if (isset($access_token->errcode))
    {
        show_message($access_token->errmsg, '返回首頁', '', 'wrong');
    }
    $user_info_url = 'https://api.weixin.qq.com/sns/userinfo?access_token='.$access_token->access_token.'&openid='.$access_token->openid.'&lang=zh_CN';

    $user_info = json_decode(file_get_contents($user_info_url));
    if (isset($user_info->errcode)) {
        show_message($user_info->errmsg, '返回首頁', '', 'wrong');
    }
    
    setcookie('user_info',$user_info);
    $info = $user_info;
    $type='weixin';
    $info_user_id = $type .'_'.$info->openid; //  加個標識!!!防止 其他的標識 一樣  // 以後的ID 標識 將以這種形式 辨認
    $info->nickname= str_replace("'" , "" ,$info->nickname);
    
    
    $sql = 'SELECT user_name,password,aite_id FROM '.$ecs->table('users').' WHERE aite_id = \''.$info_user_id.'\' OR aite_id=\''.$info->openid.'\'';
    
    $count = $db->getRow($sql);
    $login_name = $info->nickname;
    if(!$count)   // 沒有當前資料
    {
        if($user->check_user($info->nickname))  // 重名處理
        {
            $info->nickname = $info->nickname.'_'.$type.(rand()*1000);
        }
        $login_name = $info->nickname;
        $user_pass = $user->compile_password(array('password'=>$info->openid));
        $sql = 'INSERT INTO '.$ecs->table('users').'(user_name , password, aite_id , sex , reg_time , user_rank , is_validated) VALUES '.
                "('$info->nickname' , '$user_pass' , '$info_user_id' , '$info->sex' , '".gmtime()."' , '0' , '1')" ;
        $db->query($sql);
    }
    else
    {
        $login_name = $count['user_name'];
        $sql = '';
        if($count['aite_id'] == $info->openid)
        {
            $sql = 'UPDATE '.$ecs->table('users')." SET aite_id = '$info_user_id' WHERE aite_id = '$count[aite_id]'";
            $db->query($sql);
        }
    }
    
   
    $user->set_session($login_name);
    $user->set_cookie($login_name);
    update_user_info();
    
    $redirect_url =  "http://".$_SERVER["HTTP_HOST"].str_replace("user.php", "index.php", $_SERVER["REQUEST_URI"]);
    header('Location: '.$redirect_url);
}