Bu yazımda projeleriniz için basit ve kullanışlı bir Facebook Login bileşeninden bahsedeceğim. Basit olduğu kadar da kod hakimiyeti üst düzeyde.
Web forms ve Mvc de kullanılabilir, aynı mantık. Ben Mvc örneği üzerinden gideceğim.
Öncelikle Nuget üzerinden aşağıdaki paketi yüklüyorsunuz.
Burası View tarafındaki kodunuz:
<form action="/Home/fbInit">
<input type="submit" value="Facebook İle Kaydol" class="fbLoginBtn" />
</form>
public ActionResult fbInit() {
FbClient fb = new FbClient();
var Link =
fb.CrateLoginUrl().ToString();
Response.Redirect(Link);
return null;
}
public ActionResult fbCallBack(string code) {
facebookErrorViewModel m = new facebookErrorViewModel();
try {
if
(code.Length > 10) {
FbClient fbc = new FbClient();
string token = fbc.GetAccessToken(code);
FbProfile fp = fbc.GetUserInfo(token);
if
(fp.Mail==null) {
m.ErrorMsg
= "E mail adresinizi
paylaşmanız gerekli..";
return View(m);
} if
(fp.Name==null) {
m.ErrorMsg
= "Ad Soyad bilgisini
paylaşmanız gerekli..";
return View(m);
}
return Redirect("/");
}
} catch (Exception ex) {
m.ErrorMsg = "Bir hata oluştu: " + ex.Message;
return View(m);
}
return View();
}
namespace TestFb.Client.Class {
public class FbProfile {
public string ID { get; set; }
public string Name { get; set; }
public string Mail { get; set; }
public string ProfilePhoto { get; set; }
}
public class FbClient {
string AppID = "App Id";
string AppSecret = "Secret";
string CallBackUrl = "https://localhost:44300/Home/fbCallBack";
string Scope = "email,public_profile";
//, user_birthday, user_hometown, user_website,
offline_access, read_stream, publish_stream, read_friendlists
FacebookClient FacebookIslem = new FacebookClient();
public Uri CrateLoginUrl() {
return FacebookIslem.GetLoginUrl(
new {
client_id = AppID,
client_secret = AppSecret,
redirect_uri = CallBackUrl,
response_type = "code",
scope = Scope,
});
}
public dynamic GetAccessToken(string code) {
dynamic result = FacebookIslem.Post("oauth/access_token",
new {
client_id = AppID,
client_secret = AppSecret,
redirect_uri =
CallBackUrl,
code = code
});
return result.access_token;
}
public FbProfile GetUserInfo(dynamic accessToken) {
var client =
new FacebookClient(accessToken);
var profile
= new FbProfile();
dynamic me = client.Get("me?fields=id,email,name");
profile.Name =
me.name;
profile.ID = me.id;
profile.Mail = me.email;
profile.ProfilePhoto =
string.Format("https://graph.facebook.com/{0}/picture?type=large", profile.ID);
return profile;
}
}
}
Herkese iyi kodlamalar!