您的位置:首页 > 移动开发 > 微信开发

iOS 微信三方登陆

2016-02-28 11:38 716 查看

第一种方法:直接集成微信SDK(不使用友盟)

一:官方文档说明

官方文档连接:https://open.weixin.qq.com/cgi-bin/showdocument?action=dir_list&t=resource/res_list&verify=1&id=open1419317851&token=f001bdf731047893b5d79ab4e8c904af956d997c&lang=zh_CN

文件下载地址:https://open.weixin.qq.com/cgi-bin/showdocument?action=dir_list&t=resource/res_list&verify=1&id=open1419319164&token=f001bdf731047893b5d79ab4e8c904af956d997c&lang=zh_CN

二:配置环境

将文件拖入工程



配置URL scheme



三:DEFINE
1 #ifndef LoginDemo_Define_h
2 #define LoginDemo_Define_h
3
4 #define kAppDescription   @“*******"
5
6 #define kWeiXinAppId               @“wx**************"
7 #define kWeiXinAppSecret           @“4f85d************011afa8a23d5a"
8
9 #define kWeiXinAccessToken   @"WeiXinAccessToken"
10 #define kWeiXinOpenId             @"WeiXinOpenId"
11 #define kWeiXinRefreshToken  @"WeiXinRefreshToken"
12
13
14 #endif


四: AppDelegate.h
1 #import <UIKit/UIKit.h>
2
3 #import "WeChatSDK_64/WXApi.h"
4
5 @interface AppDelegate : UIResponder <UIApplicationDelegate,WXApiDelegate>
6
7 @property (strong, nonatomic) UIWindow *window;
8
9 @end


五:AppDelegate.m
1 #import "AppDelegate.h"
2 #import "RootViewController.h"
3 #import "Define.h"
4
5 @interface AppDelegate ()
6 {
7     RootViewController *root;
8 }
9 @end
10
11 @implementation AppDelegate
12
13
14 - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
15 {
16     //….
17
18     root = [[RootViewController alloc]init];
19     self.window.rootViewController = root;
20
21     [WXApi registerApp:kWeiXinAppId withDescription:kAppDescription];
22
23     return YES;
24 }
25
26 - (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url
27 {
28     return [WXApi handleOpenURL:url delegate:self];
29 }
30
31 - (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
32 {
33     return [WXApi handleOpenURL:url delegate:self];
34 }
35
36 - (void)onReq:(BaseReq*)req
37 {
38     /*
39      onReq是微信终端向第三方程序发起请求,要求第三方程序响应。第三方程序响应完后必须调用sendRsp返回。在调用sendRsp返回时,会切回到微信终端程序界面。
40      */
41 }
42
43 - (void)onResp:(BaseResp*)resp
44 {
45     /*
46      如果第三方程序向微信发送了sendReq的请求,那么onResp会被回调。sendReq请求调用后,会切到微信终端程序界面。
47      */
48     [root.weixinViewController getWeiXinCodeFinishedWithResp:resp];
49 }


六:发起授权请求
1 - (void)loginButtonClicked
2 {
3     SendAuthReq* req =[[SendAuthReq alloc ] init];
4     req.scope = @"snsapi_userinfo";
5     req.state = kAppDescription;
6     [WXApi sendReq:req];
7 }


调用方法后会弹出授权页面,完成授权后调用AppDelegate中的- (void)onResp:(BaseResp*)resp

七:处理返回数据,获取code
1 - (void)getWeiXinCodeFinishedWithResp:(BaseResp *)resp
2 {
3     if (resp.errCode == 0)
4     {
5         statusCodeLabel.text = @"用户同意";
6         SendAuthResp *aresp = (SendAuthResp *)resp;
7         [self getAccessTokenWithCode:aresp.code];
8
9     }else if (resp.errCode == -4){
10         statusCodeLabel.text = @"用户拒绝";
11     }else if (resp.errCode == -2){
12         statusCodeLabel.text = @"用户取消";
13     }
14 }


八:使用code获取access token
1 - (void)getAccessTokenWithCode:(NSString *)code
2 {
3     NSString *urlString =[NSString stringWithFormat:@"https://api.weixin.qq.com/sns/oauth2/access_token?appid=%@&secret=%@&code=%@&grant_type=authorization_code",kWeiXinAppId,kWeiXinAppSecret,code];
4     NSURL *url = [NSURL URLWithString:urlString];
5
6     dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
7
8         NSString *dataStr = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:nil];
9         NSData *data = [dataStr dataUsingEncoding:NSUTF8StringEncoding];
10
11         dispatch_async(dispatch_get_main_queue(), ^{
12
13             if (data)
14             {
15                 NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
16
17                 if ([dict objectForKey:@"errcode"])
18                 {
19 //获取token错误
20                 }else{
21 //存储AccessToken OpenId RefreshToken以便下次直接登陆
22 //AccessToken有效期两小时,RefreshToken有效期三十天
23                     [self getUserInfoWithAccessToken:[dict objectForKey:@"access_token"] andOpenId:[dict objectForKey:@"openid"]];
24                 }
25             }
26         });
27     });
28
29     /*
30      正确返回
31      "access_token" = “Oez*****8Q";
32      "expires_in" = 7200;
33      openid = ooVLKjppt7****p5cI;
34      "refresh_token" = “Oez*****smAM-g";
35      scope = "snsapi_userinfo";
36      */
37
38     /*
39      错误返回
40      errcode = 40029;
41      errmsg = "invalid code";
42      */
43 }


九:使用AccessToken获取用户信息
1 - (void)getUserInfoWithAccessToken:(NSString *)accessToken andOpenId:(NSString *)openId
2 {
3     NSString *urlString =[NSString stringWithFormat:@"https://api.weixin.qq.com/sns/userinfo?access_token=%@&openid=%@",accessToken,openId];
4     NSURL *url = [NSURL URLWithString:urlString];
5
6     dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
7
8         NSString *dataStr = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:nil];
9         NSData *data = [dataStr dataUsingEncoding:NSUTF8StringEncoding];
10
11         dispatch_async(dispatch_get_main_queue(), ^{
12
13             if (data)
14             {
15                 NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
16
17                 if ([dict objectForKey:@"errcode"])
18                 {
19 //AccessToken失效
20                     [self getAccessTokenWithRefreshToken:[[NSUserDefaults standardUserDefaults]objectForKey:kWeiXinRefreshToken]];
21                 }else{
22 //获取需要的数据
23                 }
24             }
25         });
26     });
27
28   /*
29      city = ****;
30      country = CN;
31      headimgurl = "http://wx.qlogo.cn/mmopen/q9UTH59ty0K1PRvIQkyydYMia4xN3gib2m2FGh0tiaMZrPS9t4yPJFKedOt5gDFUvM6GusdNGWOJVEqGcSsZjdQGKYm9gr60hibd/0";
32      language = "zh_CN";
33      nickname = “****";
34      openid = oo*********;
35      privilege =     (
36      );
37      province = *****;
38      sex = 1;
39      unionid = “o7VbZjg***JrExs";
40      */
41
42     /*
43      错误代码
44      errcode = 42001;
45      errmsg = "access_token expired";
46      */
47 }


十:使用RefreshToken刷新AccessToken

该接口调用后,如果AccessToken未过期,则刷新有效期,如果已过期,更换AccessToken。
1 - (void)getAccessTokenWithRefreshToken:(NSString *)refreshToken
2 {
3     NSString *urlString =[NSString stringWithFormat:@"https://api.weixin.qq.com/sns/oauth2/refresh_token?appid=%@&grant_type=refresh_token&refresh_token=%@",kWeiXinAppId,refreshToken];
4     NSURL *url = [NSURL URLWithString:urlString];
5
6     dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
7
8
9         NSString *dataStr = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:nil];
10         NSData *data = [dataStr dataUsingEncoding:NSUTF8StringEncoding];
11
12         dispatch_async(dispatch_get_main_queue(), ^{
13
14             if (data)
15             {
16                 NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
17
18                 if ([dict objectForKey:@"errcode"])
19                 {
20 //授权过期
21                 }else{
22 //重新使用AccessToken获取信息
23                 }
24             }
25         });
26     });
27
28
29     /*
30      "access_token" = “Oez****5tXA";
31      "expires_in" = 7200;
32      openid = ooV****p5cI;
33      "refresh_token" = “Oez****QNFLcA";
34      scope = "snsapi_userinfo,";
35      */
36
37     /*
38      错误代码
39      "errcode":40030,
40      "errmsg":"invalid refresh_token"
41      */
42 }

第二种方法:使用友盟集成

友盟官方论坛有集成文档:http://bbs.umeng.com/thread-5639-1-1.html

一、首先在微信开放平台获取微信登陆权限

二、在程序AppDelegate入口添加下面的方法

#import "UMSocialWechatHandler.h"
//设置微信AppId、appSecret,分享url
[UMSocialWechatHandler setWXAppId:@"wxd930ea5d5a258f4f" appSecret:@"db426a9829e4b49a0dcac7b4162da6b6" url:@"http://www.umeng.com/social"];

三、在AppDelegateD中添加回调

- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url
{
return  [UMSocialSnsService handleOpenURL:url];
}
- (BOOL)application:(UIApplication *)application
openURL:(NSURL *)url
sourceApplication:(NSString *)sourceApplication
annotation:(id)annotation
{
return  [UMSocialSnsService handleOpenURL:url];
}


四、微信登陆按钮实现下面的方法,获取到相应的用户信息

-(void)thirdLogin{

UMSocialSnsPlatform *snsPlatform = [UMSocialSnsPlatformManager getSocialPlatformWithName:UMShareToWechatSession];

snsPlatform.loginClickHandler(self,[UMSocialControllerService defaultControllerService],YES,^(UMSocialResponseEntity *response){

NSLog(@"-------%@",response);

if (response.responseCode == UMSResponseCodeSuccess) {

UMSocialAccountEntity *snsAccount = [[UMSocialAccountManager socialAccountDictionary]valueForKey:UMShareToWechatSession];

NSLog(@"\nusername is %@,\n uid is %@,\n token is %@\n url is %@,\n platform is %@\n",snsAccount.userName,snsAccount.usid,snsAccount.accessToken,snsAccount.iconURL,snsAccount.platformName);

}

});
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: