Per creare un'applicazione PHP che esporti i contatti email da Yahoo Mail faccio riferimento a questa pagina della documentazione ufficiale
https://developer.yahoo.com/social/contacts/
La prima cosa da fare è creare un'applicazione in Developer Yahoo, l'indirizzo è questo:
https://developer.yahoo.com/apps/
se abbiamo già un account Yahoo, effettuiamo l'accesso, nella pagina che si aprirà successivamente c'è un bottone sulla destra "Create an App":
che ci permette di creare una APP, scegliamo un nome e selezioniamo in Application Type Web Application:
Description e Home Page URL non sono obbligatori, è invece obbligatorio Redirect URI(s) che sarebbe l'url della pagina a cui gli utenti vengono indirizzati dopo aver effettuato l'accesso su Yahoo, nel mio esempio visto che sto lavorando su un server locale è http://localhost/yh/contacts.php, contacts.php è il file che mi mostrerà la lista dei contatti Yahoo, lo scriveremo in seguito.
Infine nella sezione "API Permissions" selezioniamo "Contacts" e poi "Read/Write ":
clicchiamo sul bottone "Create App", e la nostra app è stata creata.
Nella pagina dell'applicazione appena creata, prendiamo nota di "Consumer Key" e "Consumer Secret", sono delle stringhe alfanumeriche.
A questo punto possiamo incominciare a scrivere la nostra applicazione PHP che ci farà esportare tutti i contatti Yahoo.
Codice HTML
<a href="https://api.login.yahoo.com/oauth2/request_auth?client_id=<ConsumerKey>&redirect_uri=http://localhost/yh/contacts.php&response_type=code&language=it-it">Vai →</a>
questo è il link per iniziare la procedura, il parametro get client_id è il Consumer Key che abbiamo visto prima, e redirect_uri è l'url del file a cui vengono reindirizzati gli utenti, questo lo abbiamo definito quando abbiamo creato l'applicazione.
yahoo_contact.class.php
<?php
class YahooContacts
{
protected static $oauthConsumerKey = "<Consumer Key>";
protected static $OauthConsumerSecret = "<Consumer Secret>";
protected static $oauthDomain = "http://localhost/yh/contacts.php";
public function __construct()
{
//Check Session is Start Or not
if (session_status() == PHP_SESSION_NONE) {
session_name('YahooContacts');
session_start();
}
}
/**
* Authentication user And Access Refresh and access token
*
* @author <Pawan Kumar>
* @return type boolean
**/
public function getAuthorization($code)
{
$url = "https://api.login.yahoo.com/oauth2/get_token";
$data = "grant_type=authorization_code&redirect_uri=" . self::$oauthDomain . "&code=" . $code;
$auth = base64_encode(self::$oauthConsumerKey . ":" . self::$OauthConsumerSecret);
$headers = array(
'Authorization: Basic ' . $auth,
'Content-Type: application/x-www-form-urlencoded'
);
try {
$resultSet = self::makeRequest($url, $data, $headers);
if ($resultSet->access_token) {
$this->setAccessToken($resultSet->access_token);
$this->setRefreshToken($resultSet->refresh_token);
$this->setGuidToken($resultSet->xoauth_yahoo_guid);
return true;
}
}
catch (Exception $ex) {
throw ($ex);
}
}
/**
* Get All Contacts list From Yahoo API using Auth Access Token And oAuth Guid Token
*
* @author <Pawan Kumar>
* @return type Object
**/
public function getUserContactsDetails()
{
/** Refresh Access Token is Expired **/
$this->generateAccessToken();
$guid = $this->getGuidToken();
$token = $this->getAccessToken();
$contactUrl = "https://social.yahooapis.com/v1/user/$guid/contacts?format=json";
$opts = array(
'http' => array(
'method' => "GET",
'header' => "Authorization: Bearer $token"
)
);
$context = stream_context_create($opts);
$file = file_get_contents($contactUrl, false, $context);
$output = json_decode($file);
return $output;
}
/**
* Get New Access Token using Refresh Token
*
* @author <Pawan Kumar>
* @return type boolean
**/
protected function generateAccessToken()
{
$url = "https://api.login.yahoo.com/oauth2/get_token";
$refreshToken = $this->getRefreshToken();
$data = "grant_type=refresh_token&redirect_uri=" . self::$oauthDomain . "&refresh_token=" . $refreshToken;
$auth = base64_encode(self::$oauthConsumerKey . ":" . self::$OauthConsumerSecret);
$headers = array(
'Authorization: Basic ' . $auth,
'Content-Type: application/x-www-form-urlencoded'
);
try {
$resultSet = self::makeRequest($url, $data, $headers);
if ($resultSet->access_token) {
$this->setAccessToken($resultSet->access_token);
return true;
} else {
return false;
}
}
catch (Exception $ex) {
throw ($ex);
}
}
/**
* Build a login url using oAuth Consumber Key And Redirect Domain
*
* @author Pawan Kumar
* @return type String
**/
public static function getLoginUrl()
{
$loginUrl = "https://api.login.yahoo.com/oauth2/request_auth";
$buildUrl = $loginUrl . "?client_id=" . self::$oauthConsumerKey . "&redirect_uri=" . self::$oauthDomain . "&response_type=code&language=en-us";
return $buildUrl;
}
/**
* Make a Remote Post Request using MakeRequest Function
*
* @param Url String
* @param $postData String Send Post Data With Request
* @param headers Array Contain Auth basic information
* @author Pawan Kumar
* @return type Object
**/
public static function makeRequest($url, $postData, $headers)
{
try {
if (empty($url))
throw new Exception("Url is Not Format.");
if (empty($postData))
throw new Exception("Post Parameters is Not Defined");
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
curl_setopt($ch, CURLOPT_URL, $url);
$result = curl_exec($ch);
$output = json_decode($result);
return $output;
}
catch (\Exception $ex) {
throw ($ex);
}
}
/**
* @param RefreshToken to set String Token Into Session
*/
public function setRefreshToken($token)
{
$_SESSION['refresh_token'] = $token;
}
/**
* @return String Refresh Token From Session
*/
public function getRefreshToken()
{
return $_SESSION['refresh_token'];
}
/**
* @param AccessToken to set String Token into Session
*/
public function setAccessToken($token)
{
$_SESSION['access_token'] = $token;
}
/**
* @return String Access Token From Session
*/
public function getAccessToken()
{
return $_SESSION['access_token'];
}
/**
* @param GuidToken to set String Token into Session
*/
public function setGuidToken($token)
{
$_SESSION['xoauth_yahoo_guid'] = $token;
}
/**
* @return String Guid Token from Session
*/
public function getGuidToken()
{
return $_SESSION['xoauth_yahoo_guid'];
}
}
?>
anche in questa classe bisogna settare le costanti
- $oauthConsumerKey;
- $OauthConsumerSecret;
- $oauthDomain.
rispettivamente con Consumer Key, Consumer Secret e l'url di reindirizzamento, la funzione getUserContactsDetails() restituisce l'oggetto con tutti i contatti presenti nella rubrica di Yahoo.
infine il file contacts.php
contacts.php
<?php
require_once 'yahoo_contact.class.php';
session_name('YahooContacts');
session_start();
if (isset($_GET['error']) && $_GET['error'] == 'access_denied') {
echo "access denied";
exit();
}
if (isset($_GET['code'])) {
$code = $_GET['code'];
if (!empty($code)) {
$obj = new YahooContacts();
$obj->getAuthorization($code);
}
header("Location: contacts.php");
} else {
if (isset($_SESSION['access_token'])) {
$obj = new YahooContacts();
$res = $obj->getUserContactsDetails();
$contact = $res->contacts->contact;
$numContact = count($contact);
if ($numContact == 0) {
echo "Nessun contatto!";
} else {
for ($i = 0; $i < $numContact; $i++) {
$fields = $contact[$i]->fields;
for($y=0;$y<count($fields);$y++)
{
if($fields[$y]->type == 'email')
{
echo $fields[$y]->value; // email address
}
}
}
}
}
}
?>