IOS最新新浪微博开放平台Oauth2.0授权获取Access_Token

很久没写博客,最近在搞一个新浪微博的第三方应用,涉及到了Oauth2.0授权获取Access_Token,特此记录分享!

步骤一:添加应用

进入新浪微博开放平台(没有的话自行注册),进入“管理中心“,点击”创建应用”,选择“微链接应用”,再点击“创建应用”,,选“移动应用”,填写相应的信息,其中应用地址没有的话可随便,勾选平台后提交。注意保存你的App Key和App Secret以备后用。

步骤二:Oauth2.0授权设置

应用创建完后可以在“管理中心”-“我的应用”中查看信息,在“应用信息”--“高级信息”中可以设置网站的授权回调页和取消授权回调页。授权回调页会在用户授权成功后会被回调,同时传回一个“code”参数,开发者可以用code换取Access_Token值。当然如果是移动应用,比如本文是没有自己授权回调页的,建议这里填:https://api.weibo.com/oauth2/default.html 或者 http://www.baidu.com 之类的。如果授权后传回的形式如下:

https://api.weibo.com/oauth2/default.html?code=a6146547f981199c07348837b0629d5d

我们只要获取其中code的值a6146547f981199c07348837b0629d5d即可,注意code的值每次都是不一样的。

步骤三:引导用户授权

引导需要授权的用户到如下页面:
https://api.weibo.com/oauth2/authorize?client_id=YOUR_CLIENT_ID&response_type=code&redirect_uri=YOUR_REGISTERED_REDIRECT_URI
YOUR_CLIENT_ID:即应用的AppKey,可以在应用基本信息里查看到。
YOUR_REGISTERED_REDIRECT_URI:即之前填写的授权回调页,注意一定要和你在开发平台填写的完全相同,这里以https://api.weibo.com/oauth2/default.html 为例。
如果用户授权成功后,会跳转到回调页,开发者此时需要得到url参数中的code值,注意code只能使用一次。

步骤四:换取Access Token

开发者可以访问如下页面得到Access Token:
https://api.weibo.com/oauth2/access_token?client_id=YOUR_CLIENT_ID&client_secret=YOUR_CLIENT_SECRET&grant_type=authorization_code&redirect_uri=YOUR_REGISTERED_REDIRECT_URI&code=CODE
YOUR_CLIENT_ID:即应用的AppKey,可以在应用基本信息里查看到。
YOUR_CLIENT_SECRET:即应用的App Secret,可以在应用基本信息里查看到。
YOUR_REGISTERED_REDIRECT_URI:即之前填写的授权回调页
code:就是步骤三引导用户授权后回传的code。
如果都没有问题,就可以得到Access Token了,返回示例:
{
       "access_token": "ACCESS_TOKEN",
       "expires_in": 1234,
       "remind_in":"798114",
       "uid":"12341234"
 }


最后做了一个Xcode 5.0 storyboard的demo,用到一个UIViewController和一个UIWebView。

看代码如下:

#import <UIKit/UIKit.h>

@interface OAuthWebViewController : UIViewController<UIWebViewDelegate>

@property (weak, nonatomic) IBOutlet UIWebView *webView;

@end

#import "OAuthWebViewController.h"

@implementation OAuthWebViewController
@synthesize webView;

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    NSString *url = @"https://api.weibo.com/oauth2/authorize?client_id=3693781153&redirect_uri=https://api.weibo.com/oauth2/default.html&response_type=code&display=mobile";
    
    NSURLRequest *request = [[NSURLRequest alloc] initWithURL:[NSURL URLWithString:url]];
    [self.webView setDelegate:self];
    [self.webView loadRequest:request];

}

-(void)viewDidLoad
{
    [super viewDidLoad];
}

#pragma mark - UIWebView Delegate Methods

-(void)webViewDidFinishLoad:(UIWebView *)_webView
{
    NSString *url = _webView.request.URL.absoluteString;
    NSLog(@"absoluteString:%@",url);
    
    if ([url hasPrefix:@"https://api.weibo.com/oauth2/default.html?"]) {
        
        //找到”code=“的range
        NSRange rangeOne;
        rangeOne=[url rangeOfString:@"code="];
        
        //根据他“code=”的range确定code参数的值的range
        NSRange range = NSMakeRange(rangeOne.length+rangeOne.location, url.length-(rangeOne.length+rangeOne.location));
        //获取code值
        NSString *codeString = [url substringWithRange:range];
        NSLog(@"code = :%@",codeString);
        
        //access token调用URL的string
        NSMutableString *muString = [[NSMutableString alloc] initWithString:@"https://api.weibo.com/oauth2/access_token?client_id=3693781153&client_secret=7954135ee119b1fd068b8f41d2de5672&grant_type=authorization_code&redirect_uri=https://api.weibo.com/oauth2/default.html&code="];
        [muString appendString:codeString];
        NSLog(@"access token url :%@",muString);
        
        //第一步,创建URL
        NSURL *urlstring = [NSURL URLWithString:muString];
        //第二步,创建请求
        NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL:urlstring cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10];
        [request setHTTPMethod:@"POST"];//设置请求方式为POST,默认为GET
        NSString *str = @"type=focus-c";//设置参数
        NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding];
        [request setHTTPBody:data];
        //第三步,连接服务器
        NSData *received = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
        
        NSString *str1 = [[NSString alloc]initWithData:received encoding:NSUTF8StringEncoding];
        NSLog(@"Back String :%@",str1);
        
        NSError *error;
        //如何从str1中获取到access_token
        NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:received options:NSJSONReadingMutableContainers error:&error];
        
        NSString *_access_token = [dictionary objectForKey:@"access_token"];
        NSLog(@"access token is:%@",_access_token);
        
    }
}

@end

来几张图:




demo下载地址:http://download.csdn.net/detail/wangqiuyun/6851621

注意替换为你的AppKey和App Secret。

  • 5
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
weibo node sdk 是新浪微博 Node.js SDK。 特点 api可配置化 接口采用promise 最少依赖,专注新浪微博OAuth2.0认证 使用方法 安装 npm install iweibo 配置 引入iweibo var iweibo = require('iweibo'); var Weibo = iweibo.Weibo; 配置app信息 iweibo.set(name, options); //设置单条 iweibo.set(optionsObject);  //设置多条 iweibo.set({  appkey: 'xxx',  appsecret: 'xxxxxxxxxx'  }) 支持的配置: var CONFIG = {  appkey: '',  appsecret: '',  oauth_host: 'https://api.weibo.com/oauth2/authorize',  access_url: 'https://api.weibo.com/oauth2/access_token',  api_url: 'https://api.weibo.com/2/'  } 配置api接口 iweibo.setAPI(apiname, options); //设置单条api iweibo.setAPI(optionsObject);  //设置多条api iweibo.setAPI('statuses/update', {  method: 'post',  params: {  status: 'hello, world',  visible: 0  } }); 配置下微博接口(由于太多,并且不时更新,所以我就没全配置),配置下自己使用的接口,方法参考下件,基本如下: '接口名称': {  method: 'get', //请求方法,post或者get(get可省略),参考api文档  params: { //默认参数,不用填写appkey和access_token,程序会自动补上  } } 可以讲接口统一写到一个json或者js文件中,然后使用 require 引入,直接给 setAPI 传入 使用 参考 examples/app.js 文件(需要先在本目录执行 npm install 安装依赖模块) 修改host,添加下面内容: 127.0.0.1 testapp.cn 进入 open.weibo.com 设置应用回调地址到 http://testapp.cn/callbak 获取登录链接 weibo.getAuthorizeURL(backURL); 获取access_token weibo.getAccessToken('code', {  code: code,  redirect_uri: backURL }).done(function(err, data) {  var realpath = templateDir   'callback.html';  html = fs.readFileSync(realpath);  data = JSON.parse(data);  data.refresh_token = data.refresh_token || '';  req.session.refresh_token = data.refresh_token;  req.session.access_token = data.access_token;  req.session.uid = data.uid;  html = bdTemplate(html, data);  res.end(html); }).fail(function(err, data) {  var html;  if (err) {  html = fs.readFileSync(templateDir   'error.html');  }      res.end(html); }); 使用api接口 //所有API都支持promise接口  weibo.api('users/show', urlObj).done(function(err, result) {  console.log(result);  res.end(JSON.stringify(result));  }); 测试方法 进入examples 修改config.json,回调地址需要在open.weibo.com配置好,然后修改自己的host,将回调地址指到127.0.0.1 执行 npm install 访问自己在config.json配置的网站 标签:weibo

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值