iOS微信第三方登录

1.先拿微信开路。。。。

设置微信的appKey和appSecret

(BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

    [[UMSocialManager defaultManager] setPlaform:UMSocialPlatformType_WechatSession appKey:KWechatKey appSecret:KWechatAppSecret redirectURL:@"http://mobile.umeng.com/social"];

}

2.applicationDelegate中

- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication

annotation:(id)annotation {

    if([[url absoluteString] hasPrefix:@"wx"]) {
        return [WXApi handleOpenURL:url delegate:self];
    }
    return YES;

}

3.回调

-(void)onResp:(BaseResp*)resp{

    if ([resp isKindOfClass:[SendAuthResp class]])

        {

        SendAuthResp *aresp = (SendAuthResp *)resp;

        [[NSNotificationCenter defaultCenter] postNotificationName:WXAUTH_NOTIFICATION object:self userInfo:[NSDictionary dictionaryWithObject:aresp forKey:@"wxAuthReturn"]];

        NSString *shareStr = [[NSUserDefaults standardUserDefaults]objectForKey:@"share"];

    if (![shareStr  isEqual: @"share"] && aresp.errCode == 0)

        {

        //微信登录成功,调用接口获取进一步的数据

        [LoginViewController WeChatLogin:aresp.code];

        }
    }
}

4.在登录页面中的.h文件添加

+(void)WeChatLogin:(NSString *)code;

5.登录页面中的.m文件

//微信登录

+(void)WeChatLogin:(NSString *)code

{

    [self.class getaccess_token:code];

}

+ (void)getaccess_token:(NSString*)code

{

//检查网络

    NSError *error = nil;

    if (![[Reachability reachabilityForInternetConnection] isReachable]) {

        UIAlertView *alertViews = [[UIAlertView alloc] initWithTitle:@"该功能需要连接网络才能使用,请检查您的网络连接状态" message:nil delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];

        [alertViews show];

        return;

    }

    NSString *weixinUrl = [NSString stringWithFormat:@"https://api.weixin.qq.com/sns/oauth2/access_token?appid=%@&secret=%@&code=%@&grant_type=authorization_code",KWechatKey,KWechatAppSecret,code];

    NSLog(@"weixinUrl=%@",weixinUrl);

    NSString *urlString = [weixinUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

    NSURLRequest *req = [NSURLRequest requestWithURL:[NSURL URLWithString:urlString]];

    NSData *response = [NSURLConnection sendSynchronousRequest:req returningResponse:nil error:&error];

    if (response != nil){

        NSDictionary  *dict = [NSJSONSerialization JSONObjectWithData:response options:NSJSONReadingMutableLeaves error:&error];

        if (dict) {

            NSNumber *retcode = [dict objectForKey:@"errcode"];

                if ([retcode integerValue] == 0) {

                    NSLog(@"登录成功 access_token=%@ openid=%@",[dict objectForKey:@"access_token"],[dict objectForKey:@"openid"]);

                    [self getUserInfo:[dict objectForKey:@"access_token"] openid:[dict objectForKey:@"openid"]];

                    [[NSUserDefaults standardUserDefaults] setObject:[dict objectForKey:@"access_token"] forKey:@"ACCESS_TOKEN"];

                    [[NSUserDefaults standardUserDefaults] setObject:[dict objectForKey:@"openid"] forKey:@"OPENID"];

                    //注意,这里用通知来处理你接下来要做什么,与服务器对接的事件

                    [[NSNotificationCenter defaultCenter]postNotificationName:@"wxLogData" object:nil];

                  }
              }
          }
}

#pragma mark

#pragma mark-- 微信返回数据

+(void)getUserInfo:(NSString*)access_code openid:(NSString*)openid

{

    NSError *error = nil;

    NSString *weixinUrl = [NSString stringWithFormat:@"https://api.weixin.qq.com/sns/userinfo?access_token=%@&openid=%@",access_code,openid];

    NSLog(@"weixinUrl=%@",weixinUrl);

    NSString *urlString = [weixinUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

    NSURLRequest *req = [NSURLRequest requestWithURL:[NSURL URLWithString:urlString]];

    NSData *response = [NSURLConnection sendSynchronousRequest:req returningResponse:nil error:&error];

    if (response != nil)

        {

            NSDictionary  *dict = [NSJSONSerialization JSONObjectWithData:response options:NSJSONReadingMutableLeaves error:&error];

            if (dict) {

            //NSLog(@"微信返回数据--%@",dict);

            NSNumber *retcode = [dict objectForKey:@"errcode"];

                if ([retcode integerValue] == 0){

                    NSLog(@"获取用户信息成功 nickName=%@ headImgUrl=%@",[dict objectForKey:@"nickname"],[dict objectForKey:@"headimgurl"]);

                    [[NSUserDefaults standardUserDefaults] setObject:[dict objectForKey:@"nickname"] forKey:@"wxNickName"];

                    [[NSUserDefaults standardUserDefaults] setObject:[dict objectForKey:@"headimgurl"] forKey:@"wxAvatar"];

                    [[NSUserDefaults standardUserDefaults] setObject:openid forKey:@"wxOpenid"];

                    }
              }
        }
}

6.最后在点击微信登录的按钮上添加调起微信的方法就完成了喔

if ([WXApi isWXAppInstalled]) {

    SendAuthReq *req = [[SendAuthReq alloc] init];

    req.scope = @"snsapi_userinfo";

    req.state = @"App";

    [WXApi sendReq:req];

}

到此,已经完成 了微信登录了,如果出现错误码,你可以对照微信返回的错误码,上次有人修改了微信的Secret 导致返回错误码结尾是100025什么的,具体不太记得了,拿到正确的secret就可以了

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 注意:代码自己动手写,不要复制! GitHub 一、接入微信第三方登录准备工作。 移动应用微信登录是基于OAuth...
    大冲哥阅读 15,177评论 0 7
  • 这是本人写的第一篇文章,写的不好还望见谅!~ 在做项目的时候,由于本人最先使用原生的微信集成第三方登录,测试是没有...
    哭与行阅读 2,100评论 0 0
  • 标签(空格分隔): iOS 我的计划1.使用微信SDK实现微信第三方登录2.使用友盟实现第三方登录3.使用open...
    iOS_愛OS阅读 5,848评论 1 9
  • multipliedBy(约束值为约束对象的百分比)用法: 动态布局,根据内容的大小,父视图大小根据子视图大小改变...
    Cooperluffy丨路飞阅读 659评论 0 0