ccc

Mostrando entradas con la etiqueta API Google. Mostrar todas las entradas
Mostrando entradas con la etiqueta API Google. Mostrar todas las entradas

Login con Google (Febrero 2022)

En https://console.developers.google.com/ dar de alta nuevas credenciales y obtener así la API KEY, ClientId y ClientSecret.
Hay que instalar la API de Google con composer:
composer require google/apiclient:"^2.0"

El código sería:
require_once 'vendor/autoload.php';
// init configuration
$clientID = 'xxxx';
$clientSecret = 'xxxxx';
$redirectUri = 'https://loquesea.com/form_login.php';
  
// create Client Request to access Google API
$client = new Google_Client();
$client->setClientId($clientID);
$client->setClientSecret($clientSecret);
$client->setRedirectUri($redirectUri);
$client->addScope("email");
$client->addScope("profile");
if (isset($_GET['code'])) { // identif por Google
    $token = $client->fetchAccessTokenWithAuthCode($_GET['code']);
    $client->setAccessToken($token['access_token']);
    // get profile info
    $google_oauth = new Google_Service_Oauth2($client);
    $google_account_info = $google_oauth->userinfo->get();
    // print_r($google_account_info);
    $email =  $google_account_info->email;
    $name =  $google_account_info->name;
}
?>
<a href='<?=$client->createAuthUrl();?>'><img src="img/btnGoogle.jpg"></a>

Más información en: https://code.tutsplus.com/es/tutorials/create-a-google-login-page-in-php--cms-33214

Google API: Subir ficheros a Google Drive desde PHP

a) Descargar https://github.com/numsu/google-drive-sdk-api-php-insert-file-parent-example

b) Ir a https://console.developers.google.com para habilitar la API de Google Drive

c) Ir a Biblioteca -> Buscar "Google Drive API" y habilitar esa API.

d) Ir a Credenciales -> Crear un nuevo IDs de cliente de OAuth 2.0

Con esto obtendrás:
ID de cliente
Secreto de cliente
url de Retorno: la ruta del fileUpload.php de lo previamente descargado, por ejemplo http://www.midominio.com/googleDrive/fileUpload.php

e) Editar el fichero functions.php con los datos proporcionados, por ej:
$CLIENT_ID = "261115921671-4l0XXXia7pi1bkluv54qhg785un4jqvd.apps.googleusercontent.com";
$CLIENT_SECRET = "UB-L_EW3D-xnXXXeR1cIaOUY";
$REDIRECT_URI = "http://www.midominio.com/googleDrive/fileUpload.php";

f) Editar el fichero index.php con dichos datos:
$authUrl = getAuthorizationUrl("261115921671-4l0XXXia7pi1bkluv54qhg785un4jqvd.apps.googleusercontent.com", "UB-L_EW3D-xnXXXeR1cIaOUY");

g) Ejecutar en el servidor ese index.

--------------------------------------------------------------------

Importante: Si lo ejecutas varias veces puede dar algún error, para que no de hay que desloguearse de tu cuenta de google y volver a ejecutarlo.

Si quisieramos listar todos los ficheros subidos al Drive (por motivos de seguridad solo permite listar aquellos ficheros que has subido con tu cuenta) sería por ejemplo en el fileUpload.php añadir:
<h3><a href="listarFicheros.php">Listar ficheros del Drive</a></h3>

Y luego listarFicheros.php:
require_once 'google-api-php-client/src/Google/Client.php';
require_once 'google-api-php-client/src/Google/Service/Oauth2.php';
require_once 'google-api-php-client/src/Google/Service/Drive.php';
session_start();

header('Content-Type: text/html; charset=utf-8');


$credentials = $_COOKIE["credentials"];

$json = json_decode(file_get_contents("./conf/GoogleClientId.json"), true);
$CLIENT_ID = $json['web']['client_id'];
$CLIENT_SECRET = $json['web']['client_secret'];
$REDIRECT_URI = $json['web']['redirect_uris'][0];


$client = new Google_Client();
$client->setClientId($CLIENT_ID);
$client->setClientSecret($CLIENT_SECRET);
$client->setRedirectUri($REDIRECT_URI);
$client->addScope(
"https://www.googleapis.com/auth/drive",
"https://www.googleapis.com/auth/drive.appfolder");


$client->setAccessToken($credentials);
$service = new Google_Service_Drive($client);
$files = $service->files->listFiles();


foreach ($files['items'] as $item) { ?>
<a target="_blank" href="<?=$item['alternateLink'];?>"> <?=$item['title'];?> </a>
<br>
<?php
}

Más fácil, subir al Drive todo lo que haya en una carpeta local de tu ordenador:
https://github.com/leandrosiegar/google_drive_upload_from_folder

Ojo: En algunas versiones de PHP (como la 5.3) no funciona el mime_content_type

API Google: Obtener los datos del usuario mediante JS sin necesidad de mandarlo a otra página

En nuestra web:
<button class="button-linkedin" onclick="login_google();"><i class="fa fa-google-plus"></i>Registrarse con Google</button>

En api_google.js:
function login_google() {
  var myParams = {
    'clientid' : 'xxx.apps.googleusercontent.com',
    'cookiepolicy' : 'single_host_origin',
    'callback' : 'loginCallback',
    'approvalprompt':'force',
    'scope' : 'https://www.googleapis.com/auth/plus.login https://www.googleapis.com/auth/plus.profile.emails.read'
  };
  gapi.auth.signIn(myParams);
}


function generar_password_random(length) {
  var iteration = 0;
  var password = "";
  var randomNumber;
  var special = false;


  while(iteration < length){
    randomNumber = (Math.floor((Math.random() * 100)) % 94) + 33;
    console.log(randomNumber);
    if(!special){
      if ((randomNumber >=33) && (randomNumber <=47)) { continue; }
      if ((randomNumber >=58) && (randomNumber <=64)) { continue; }
      if ((randomNumber >=91) && (randomNumber <=96)) { continue; }
      if ((randomNumber >=123) && (randomNumber <=126)) { continue; }
    }
    iteration++;
    password += String.fromCharCode(randomNumber);
  }
  return password;
}

function loginCallback(result) { // Se llamará a la de google/get_google.php
   if(result['status']['signed_in'])
    {
        var request = gapi.client.plus.people.get(
        {
            'userId': 'me'
        });
        request.execute(function (resp)
        {
            console.log("RESP:");
            console.log(resp);
            var email = '';
            if(resp['emails'])
            {
                for(i = 0; i < resp['emails'].length; i++)
                {
                    if(resp['emails'][i]['type'] == 'account')
                    {
                        email = resp['emails'][i]['value'];
                    }
                }
            }
         

            var str = "Name:" + resp['displayName'] + "<br>";
            str += "Image:" + resp['image']['url'] + "<br>";
            str += "<img src='" + resp['image']['url'] + "' /><br>";

            str += "URL:" + resp['url'] + "<br>";
            str += "Email:" + email + "<br>";
         
            // document.getElementById("profile").innerHTML = str;
         
            // alert("givenName:"+resp["name"]["givenName"]);
         
         
            var azar = Math.floor((Math.random() * 999) + 1);
            var username = "GOO_"+resp["name"]["givenName"].substr(0,4)+"_"+resp["name"]["familyName"].substr(0,4)+"_"+azar;
            // alert(username);
   
              rutaReg = "http://midominio.com/public/es/post_registro";
         
            var pass = generar_password_random(10);
            // alert("Sale del pass:"+pass);
         
            var html = '';
            html += '<form id="form_reg_linkedin" name="form_reg_linkedin" action="'+rutaReg+'" method="POST">';
            html += '<input type="hidden" name="nombre_completo" value="'+resp['displayName']+'">';
            html += '<input type="hidden" name="email" value="'+email+'">';
            html += '<input type="hidden" name="esRegLinkedin" value="1">';
            html += '<input type="hidden" name="id_pais" value="73">';
            html += '<input type="hidden" name="otra_ciudad" value="'+resp['placesLived'][0]['value']+'">';
            html += '<input type="hidden" name="cp" value="28000">';
            html += '<input type="hidden" name="fecha_nacimiento" value="31/12/1977">';
            html += '<input type="hidden" name="nif" value="2222">';
            html += '<input type="hidden" name="username" value="'+username+'">';
            html += '<input type="hidden" name="pw1" value="'+pass+'">';
            html += '</form>';
            // alert(html);
            // $("#divHTML").html(html);
            document.write(html);
            // alert("Escrito el html");
         
            $(function() {
               //  alert("Enviar form a "+rutaReg);
                $("#form_reg_linkedin").submit();
             });
        });

    }

}
function onLoadCallback()
{
 
    gapi.client.setApiKey('AIzaxxx');
    gapi.client.load('plus', 'v1',function(){});
}


      (function() {
       var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true;
       po.src = 'https://apis.google.com/js/client.js?onload=onLoadCallback';
       var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s);
     
     
     })();
   
     $(function() {

     });

API Google: Obtener los datos del usuario con el login de Google

Ejemplo general:
http://hayageek.com/login-with-google-plus-javascript-api/

Entrar en:
https://console.developers.google.com

1. Crear un nuevo proyecto llamado por ejemplo "Registrarse en www.midominio.com"
2. Ir a "Credenciales" -> Crear Credenciales -> Clave de API (con esto obtenemos la API Key)
3. Una vez creado ir a: Visión general -> APIs de Google
4. Habilitar las APIS de "Gmail API" y la de "Google+ API"
5. Ir a "Credenciales" -> Crear Credenciales -> "Id de Cliente OAuth" -> Web
6. Rellenar aquí los datos de "Orígenes de JavaScript autorizados" y de "URIs de redireccionamiento autorizados" con las urls de tu web, por ejemplo:
http://www.midominio.com
http://www.midominio.com/google/get_google.php
7. Con esto obtenemos el Id de Cliente y el App Secret.
8. Para que te deje hacerlo tendrás que verificar que tú eres el dueño del dominio www.midominio.com para ello te enlazará con tu servidor (por ejemplo www.ovh.com) para que añadas un texto para confirmar que es tuyo el dominio.

Una vez guardados todos los cambios el código sería:

<!DOCTYPE html>
<html>
<head>
</head>
<body>
<input type="button"  value="Login" onclick="login()" />
<input type="button"  value="Logout" onclick="logout()" />

<div id="profile"></div>
<script type="text/javascript">

function logout()
{
    gapi.auth.signOut();
    location.reload();
}
function login()
{
  var myParams = {
    'clientid' : 'XXX',
    'cookiepolicy' : 'single_host_origin',
    'callback' : 'loginCallback',
    'approvalprompt':'force',
    'scope' : 'https://www.googleapis.com/auth/plus.login https://www.googleapis.com/auth/plus.profile.emails.read'
  };
  gapi.auth.signIn(myParams);
}

function loginCallback(result)
{
    if(result['status']['signed_in'])
    {
        var request = gapi.client.plus.people.get(
        {
            'userId': 'me'
        });
        request.execute(function (resp)
        {
            console.log("RESP:");
            console.log(resp);
            var email = '';
            if(resp['emails'])
            {
                for(i = 0; i < resp['emails'].length; i++)
                {
                    if(resp['emails'][i]['type'] == 'account')
                    {
                        email = resp['emails'][i]['value'];
                    }
                }
            }

            var str = "Name:" + resp['displayName'] + "<br>";
            str += "Image:" + resp['image']['url'] + "<br>";
            str += "<img src='" + resp['image']['url'] + "' /><br>";

            str += "URL:" + resp['url'] + "<br>";
            str += "Email:" + email + "<br>";
            document.getElementById("profile").innerHTML = str;
        });

    }

}
function onLoadCallback()
{
    gapi.client.setApiKey('XXXX');
    gapi.client.load('plus', 'v1',function(){});
}

    </script>

<script type="text/javascript">
      (function() {
       var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true;
       po.src = 'https://apis.google.com/js/client.js?onload=onLoadCallback';
       var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s);
     })();
</script>

</body>
</html>

API Google+

--------------------------------------------------
BOTÓN +1
a) Entrar en https://developers.google.com/+/web/+1button/?hl=es
b) Especificas las característicaS del botón y te genera todo el código a poner en tu web.

----------------------------------------

ACCEDER A LA WEB CREADA EN GOOGLE+
https://plus.google.com/112644250846313088999/posts

-------------------------------------

HACER QUE TODO LO QUE SE PUBLIQUE EN BLOGGER SE PUBLIQUE EN GOOGLE+

a) Entras en blogger
b) Seleccionas Google+ (menú a la izquierda)
c) Marcamos el checkbox de "Compartir automáticamente después de Publicar"
d) Te pedirá que te identifiques en google+ y la web donde quieres publicarlo (por si tienes varias)

-------------------------------------------

APLICACIONES EN GOOGLE+

Habilitar las APIs que se necesiten: https://console.developers.google.com

Iniciar sesión con Google+: https://developers.google.com/+/web/signin/?hl=es

Obtener información de los usuarios identificados: https://developers.google.com/+/web/people/?hl=es

----------------------------------------------