Created
February 17, 2018 04:44
-
-
Save sivasankars/0896cfeb179e505946cf887c7f73d6dc to your computer and use it in GitHub Desktop.
Google URL Shortener
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use strict'; | |
var express = require('express'); | |
var { google } = require('googleapis'); | |
// API keys, Client ID and Client Secret @ https://code.google.com/apis/console | |
var GAPI = "AIzaSyBheQiEQ_NYpsFugde-jb8hmC7FBAFEVHI"; | |
var CLIENT_ID = "507857393893-tmnp49jq8of3en7m81dqdidedupris8d.apps.googleusercontent.com"; | |
var CLIENT_SECRET = "aLHvXDEV_I_YpAA4Y9tl1tdg"; | |
var REDIRECT_URL = "http://localhost:3000/oauth2callback"; | |
var urlshortener = google.urlshortener('v1'); | |
var OAuth2Client = google.auth.OAuth2; | |
var oauth2Client = new OAuth2Client(CLIENT_ID, CLIENT_SECRET, REDIRECT_URL); | |
var app = express(); | |
app.get('/', (req, res) => res.send('Google URL Shortener - API Demo')); | |
// Get Information About Short URL | |
app.get('/get', (req, res) => { | |
var params = { | |
"auth": GAPI, | |
"shortUrl": 'https://goo.gl/MTEs4' | |
}; | |
urlshortener.url.get(params, function (err, response) { | |
if (err || !response) { | |
res.send("Error On Get"); | |
} else { | |
res.json(response.data); | |
} | |
}); | |
}); | |
// Generate Short URL | |
app.get('/insert', (req, res) => { | |
var params = { | |
"auth": GAPI, | |
"resource": { | |
"longUrl": "http://niralar.com/" | |
} | |
}; | |
urlshortener.url.insert(params, function (err, response) { | |
if (err || !response) { | |
res.send("Error On Insert"); | |
} else { | |
res.json(response.data); | |
} | |
}); | |
}); | |
// Retrieves a list of URLs shortened by the authenticated user. | |
app.get('/list', (req, res) => { | |
const url = oauth2Client.generateAuthUrl({ | |
access_type: 'offline', // OAuth2 (Generate AuthUrl) | |
scope: 'https://www.googleapis.com/auth/urlshortener' | |
}); | |
res.redirect(url); | |
}); | |
app.get('/oauth2callback', (req, res) => { | |
var code = req.query.code + '#'; | |
oauth2Client.getToken(code, (err, tokens) => { | |
if (err || !tokens) { | |
res.send("Error On OAuth"); | |
} else { | |
oauth2Client.setCredentials(tokens); | |
urlshortener.url.list({ auth: oauth2Client }, function (err, response) { | |
if (err || !response) { | |
res.send("Error On Listing"); | |
} else { | |
res.json(response.data); | |
} | |
}); | |
} | |
}); | |
}); | |
app.listen(3000, () => console.log('Example app listening on port 3000!')); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment