Skip to content

Instantly share code, notes, and snippets.

@leokovaski
Forked from maiconschmitz/exemplo.php
Created May 2, 2017 17:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save leokovaski/f8c49e03a6a492f9c290fca7a69d866e to your computer and use it in GitHub Desktop.
Save leokovaski/f8c49e03a6a492f9c290fca7a69d866e to your computer and use it in GitHub Desktop.
Classe para encurtar URL utilizando o Google url shortener
include "googl.php";
$googl = new Googl();
$googl->setChave("");
$retorno = $googl->encurtarUrl("http://www.maiconschmitz.com.br");
echo "URL encurtada: " . $retorno->id;
class Googl
{
/**
* URL da API do Google url shortener
* @var string
*/
private $urlApi = 'https://www.googleapis.com/urlshortener/v1';
/**
* Chave da API do Google url shortener
* @var string
*/
private $chave;
/**
* Define a chave
* @param string $chave
*/
public function setChave($chave) {
$this->chave = $chave;
}
/**
* Retorna a chave
* @return string
*/
public function getChave() {
return $this->chave;
}
/**
* Encurta a URL
* @param string $url URL a ser encurtada
* @return stdClass
*/
public function encurtarUrl($url) {
/* verifica se deve montar o URL com a chave */
if ($this->getChave()) {
$urlApi = sprintf('%s/url?key=%s', $this->urlApi, $this->getChave());
} else {
$urlApi = sprintf('%s/url', $this->urlApi);
}
/* inicializa a conexão cURL */
$cUrl = curl_init($urlApi);
/* indica ao cURL que deve efetuar retorno dos dados */
curl_setopt($cUrl, CURLOPT_RETURNTRANSFER, true);
/* define que a requisição deve ser do tipo POST */
curl_setopt($cUrl, CURLOPT_POST, true);
/* cria os dados a serem codificados posteriormente com JSON */
$cabecalhoRequisicao = array(
'Content-type: application/json'
);
/* define que o tipo de conteúdo é do tipo JSON */
curl_setopt($cUrl, CURLOPT_HTTPHEADER, $cabecalhoRequisicao);
/* cria os dados a serem codificados posteriormente com JSON */
$dadosRequisicao = array(
'longUrl' => $url
);
/* define os dados a serem postados, codificando-os com JSON */
curl_setopt($cUrl, CURLOPT_POSTFIELDS, json_encode($dadosRequisicao));
/* executa a requisição */
$retorno = curl_exec($cUrl);
/* fecha a conexão */
curl_close($cUrl);
return json_decode($retorno);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment