使用Javascript API检索访问令牌 [英] Retrieve Access Token Using Javascript API

查看:150
本文介绍了使用Javascript API检索访问令牌的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个后续的主题:将signed_request与AJAX调用一起传递到使用CanvasAuthorize装饰的ActionMethod



由于我无法将signed_request取为任何内容除了null之外,我以为我会在客户端验证用户,然后将访问令牌与AJAX调用一起发送到服务器端(ASP.NET MVC)。不幸的是,我也无法做到这一点。这是我的Javascript代码(我从文档中得到):

  function postOnFacebook(msg,itemLink,pic,itemTitle, signedReq){
var siteUrl ='http://www.localhost:2732';

var appID = 193005690721590;
if(window.location.hash.length == 0){
var path ='https://www.facebook.com/dialog/oauth?';
var queryParams = ['client_id ='+ appID,
'redirect_uri ='+ window.location,
'response_type = token',
'scope = offline_access'];
var query = queryParams.join('&');
var url = path + query;
window.open(url);
} else {
var accessToken = window.location.hash.substring(1);
var path =https://graph.facebook.com/me?;
var queryParams = [accessToken];
var query = queryParams.join('&');
var url = path + query;

//使用jsonp调用图
var script = document.createElement('script');
script.src = url;
document.body.appendChild(script);
}

$ .ajax({
url:'/ Facebook / Share',
data:{
'message':msg,
'link':siteUrl + itemLink,
'picture':siteUrl + pic,
'name':itemTitle,
'accessToken':accessToken
},
类型:'get',
success:function(data){
if(data.result ==success){
alert(item was posted on Facebook);
}
}
});
}

这是我的服务器端代码:

  public ActionResult Share(string message,string link,string picture,string name,string accessToken)
{
if(FacebookWebContext.Current .Session == null)
return RedirectToAction(Login);

var fb = new FacebookWebClient(accessToken);
var postArgs = new Dictionary< string,string>();
postArgs [message] = message;
postArgs [link] = link;
postArgs [picture] =图片;
postArgs [name] = name;

fb.Post(/ me / feed,postArgs);
return Json(new {result =success},JsonRequestBehavior.AllowGet);
}
}

更新: p>

我尝试过这个,但对我来说并不奏效。当我第一次点击按钮时,它将重定向到FB登录页面,然后将我返回到我的网站的主页。之后,它所做的只是重定向,然后马上回到主页。任何建议?

解决方案

Facebook Javascript SDK文档在这里: https://developers.facebook.com/docs/reference/javascript/



有几种使用Javascript SDK获取访问令牌的方法。有些是同步的,有些是异步的,有些可以让你订阅诸如登录状态的变化等事件,有些可以响应提示权限的事情来获取会话对象(包含访问令牌)。



这是一个简单的例子:

 < input id =AccessTokentype =textvalue =/> 
< div id =fb-root>< / div>
< script src =https://connect.facebook.net/en_US/all.jstype =text / javascript>< / script>
< script src =https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.jstype =text / javascript>< / script>
< script type =text / javascript>
$(document).ready(function(){

FB.init({
appId:'insert your appID value here',
cookie:true,
xfbml:true,
status:true});

FB.getLoginStatus(function(response){
if(response.authResponse){
$('#AccessToken')。val(response.authResponse.accessToken);
} else {
//做某事...可能显示登录提示
}
} );

});
< / script>

一旦你有访问令牌被捕获的客户端,你可以发布一个窗体或一个jax调用服务器。



另外要检查的是你的环境。 Facebook会查看是否使用这些api通话的域名与您的应用设置匹配。尝试在端口80和一个真正的域名与DNS指向您的服务器(而不是本地主机)。使用DynDns或其他此类服务来设置指向您的开发框的域名和DNS条目。在您的开发框上运行IIS,您的应用程序在端口80和防火墙/路由器端口转发设置上,以便您可以在与您的Facebook应用程序设置匹配的真实域上的端口80上提供您的页面。


This is a follow up to the topic: Passing the signed_request along with the AJAX call to an ActionMethod decorated with CanvasAuthorize

Since I couldn't get the signed_request to be anything other than null, I thought I'd authenticate the user on the client side, then send the access token to the server side (ASP.NET MVC) along with the AJAX call. Unfortunately, I cannot get that to work either! Here's my Javascript code (which I've got from the documentation):

function postOnFacebook(msg, itemLink, pic, itemTitle, signedReq) {
    var siteUrl = 'http://www.localhost:2732';

    var appID = 193005690721590;
     if (window.location.hash.length == 0) {
       var path = 'https://www.facebook.com/dialog/oauth?';
       var queryParams = ['client_id=' + appID,
         'redirect_uri=' + window.location,
         'response_type=token',
         'scope=offline_access'];
       var query = queryParams.join('&');
       var url = path + query;
       window.open(url);
     } else {
       var accessToken = window.location.hash.substring(1);   
       var path = "https://graph.facebook.com/me?";
       var queryParams = [accessToken];
       var query = queryParams.join('&');
       var url = path + query;

   // use jsonp to call the graph
       var script = document.createElement('script');
       script.src = url;
       document.body.appendChild(script);   
     }

    $.ajax({
        url: '/Facebook/Share',
        data: {
            'message': msg,
            'link': siteUrl + itemLink,
            'picture': siteUrl + pic,
            'name' : itemTitle,
            'accessToken': accessToken
        },
        type: 'get',
        success: function(data) {
            if(data.result == "success") {
                alert("item was posted on facebook");
            }
        }
    });
}

And this is my server-side code:

    public ActionResult Share(string message, string link, string picture, string name, string accessToken)
    {
        if (FacebookWebContext.Current.Session == null)
            return RedirectToAction("Login");

        var fb = new FacebookWebClient(accessToken);
        var postArgs = new Dictionary<string, string>();
        postArgs["message"] = message;
        postArgs["link"] = link;
        postArgs["picture"] = picture;
        postArgs["name"] = name;

        fb.Post("/me/feed", postArgs);
        return Json(new {result = "success"}, JsonRequestBehavior.AllowGet);
    }
}

UPDATE:

I tried this but it did not work for me. When I click on the button for the first time, it redirects me to the FB login page and then returns me back to my website's home page. After that, all it does is redirect and then back to the home page right away. Nothing gets posted.

Any suggestions?

解决方案

The Facebook Javascript SDK documentation is here: https://developers.facebook.com/docs/reference/javascript/

There are several methods of getting the access token using the Javascript SDK. Some are synchronous, some asynchronous, some let you subscribe to events such as changes in login state, some get the session object (which contains the access token) in response to things like prompting for permissions.

Here is one simple example:

<input id="AccessToken" type="text" value="" />
<div id="fb-root"></div>
<script src="https://connect.facebook.net/en_US/all.js" type="text/javascript"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
    $(document).ready(function () {

        FB.init({ 
            appId: 'insert your appID value here', 
            cookie: true, 
            xfbml: true, 
            status: true });

        FB.getLoginStatus(function (response) {
            if (response.authResponse) {
                $('#AccessToken').val(response.authResponse.accessToken);
            } else {
                // do something...maybe show a login prompt
            }
        });

    });
</script>

Once you have the access token captured client side you can post it in a form or ajax call to the server.

Another thing to check is your environment. Facebook will look to see if the domain making these api calls matches up with your app settings. Try it on port 80, and with a real domain with DNS that points at your server (not localhost). Use DynDns or some other such service to setup a domain name and DNS entry that points at your dev box. Run IIS on your dev box with your app on port 80 and the firewalls/router port forwarding setup so you can serve your pages on port 80 on a real domain that matches your Facebook app settings.

这篇关于使用Javascript API检索访问令牌的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆