微信登录

1.下载SDK

提示:官方将,分享、登录、收藏、支付,集合在一个SDK中
下载地址:https://open.weixin.qq.com/cgi-bin/showdocument?action=dir_list&t=resource/res_list&verify=1&id=open1419319164&token=&lang=zh_CN

微信登录_第1张图片
屏幕快照 2016-09-06 下午8.23.55.png

2.导入SDK文件

微信登录_第2张图片
屏幕快照 2016-09-02 下午2.50.07.png

3.添加依赖库

这些类库都要导入


微信登录_第3张图片
微信所配备的库.png

4.URL — Types(加入 appid)

位置:target - Info - URL Types
提示:只需要将冲微信申请的appID填上即可


微信登录_第4张图片
20160620144003150.jpeg

5.设置白名单

注意:iOS9.0 之后要设置 白名单。在 info.plist->文件中加入LSApplicationQueriesSchemes, 如果不设置白名单无法打开微信

20160620144207541.jpeg

还有,iOS9.0之后要手动设置网络请求,上图App Transport Security 中的设置就是手动设置HTTP请求

以上基本是做微信都要配置的步骤



6.代码

1. AppDelegate.h中导入微信的头文件

// 微信支付的SDK
#import “WXApi.h”

2.AppDelegate.m中 添加方法

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

    //  向微信应用注册
    [WXApi registerApp:@“此处填写微信申请的appid" withDescription:@"Wechat"];
    return YES;
}

3.发起授权请求

此方法中并没有考虑reAccessToken是否过期。reAccessToken一般为两小时

//  微信登录
- (IBAction)weiXinLogin:(id)sender {
    NSString *accessToken = [[NSUserDefaults standardUserDefaults] objectForKey:@"access_token"];
    NSString *openID = [[NSUserDefaults standardUserDefaults] objectForKey:@"openid"];
    // 如果已经请求过微信授权登录,那么考虑用已经得到的access_token
    if (![accessToken isEqualToString:@"access_token"]|| ![openID isEqualToString:@"openid"]) {
        AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
        manager.responseSerializer = [AFHTTPResponseSerializer serializer];
        NSString *refreshToken = [[NSUserDefaults standardUserDefaults] objectForKey:@"refresh_token"];
        NSString *refreshUrlStr = [NSString stringWithFormat:@"%@/oauth2/refresh_token?appid=%@&grant_type=refresh_token&refresh_token=%@", @"https://api.weixin.qq.com/sns", @"自己的账号id", refreshToken];
        
        [manager GET:refreshUrlStr parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
            
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            NSLog(@"请求reAccess的response = %@", responseObject);
            
            //对数据进行转码
            // ASCII to NSString
            NSString * refreshDictStr = [[NSString alloc] initWithData: responseObject encoding: NSUTF8StringEncoding];
            NSLog(@"\n\n refreshDict = %@",refreshDictStr);
            //字符串再生成NSData
            NSData * data = [refreshDictStr dataUsingEncoding:NSUTF8StringEncoding];
            //再解析
            NSDictionary *refreshDict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
            NSString *reAccessToken = [refreshDict objectForKey:WX_ACCESS_TOKEN];
            // 如果reAccessToken为空,说明reAccessToken也过期了,反之则没有过期
            if (reAccessToken) {
                // 更新access_token、refresh_token、open_id
                [[NSUserDefaults standardUserDefaults] setObject:reAccessToken forKey:@"access_token"];
                [[NSUserDefaults standardUserDefaults] setObject:[refreshDict objectForKey:@"openid"] forKey:@"openid"];
                [[NSUserDefaults standardUserDefaults] setObject:[refreshDict objectForKey:@"refresh_token"] forKey:@"refresh_token"];
                [[NSUserDefaults standardUserDefaults] synchronize];
                // 当存在reAccessToken不为空时直接执行AppDelegate中的weixinLoginByRequestForUserInfo方法
                AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];

                //  此方法是写在appdelegate.m文件中的方法,
               [appDelegate weixinLoginByRequestForUserInfo];
                appDelegate.num = 1;
                
            }
            else {
                [self weixinLogin];
                AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
                appDelegate.num = 1;
            }
            
            
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            NSLog(@"用refresh_token来更新accessToken时出错 = %@", error);
        }];
        
        
    }else{
        [self weixinLogin];
        [self loginWithNetworkWithtype:@"1" openid:[self.appdelegate.userInfo objectForKey:@"openid"]];
    }
}


















-(IBAction)weixinLogin
{ 
//  判断是否安装微信
    if([WXApi isWXAppInstalled]){
        SendAuthReq *req = [[SendAuthReq alloc]init];
        req.scope = @"snsapi_userinfo";
        req.state = @"APP"; //可省,不影响功能
        [WXApi sendReq:req];
    }else{
      UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"请先安装微信客户端" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *actionConfirm = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil];
    [alert addAction:actionConfirm];
    [self presentViewController:alert animated:YES completion:nil];

scope:授权域,@"snsapi_userinfo" 获取用户信息

4.AppDelegate.m中添加两个方法

注意:这个两个方法必须实现。有另外方法不需要实现
首先遵循 协议

#pragma mark --- 此方法用于从微信返回第三方App
-(BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url{
    [WXApi handleOpenURL:url delegate:self];
    return YES;
}

-(BOOL)application:(UIApplication *)application openURL:(nonnull NSURL *)url options:(nonnull NSDictionary *)options{
   return [WXApi handleOpenURL:url delegate:self];
}

WXApiDelegate的代理方法

//微信代理方法
- (void)onResp:(BaseResp *)resp
{
    
     SendAuthResp *aresp = (SendAuthResp *)resp;
     if(aresp.errCode== 0 && [aresp.state isEqualToString:WXPacket_State])
        {
            NSString *code = aresp.code;
            [self getWeiXinOpenId:code];
        }
}
//通过code获取access_token,openid,unionid
- (void)getWeiXinOpenId:(NSString *)code{
    NSString *url =[NSString stringWithFormat:@"https://api.weixin.qq.com/sns/oauth2/access_token?appid=%@&secret=%@&code=%@&grant_type=authorization_code",AppId,AppSerect,code];
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSURL *zoneUrl = [NSURL URLWithString:url];
        NSString *zoneStr = [NSString stringWithContentsOfURL:zoneUrl encoding:NSUTF8StringEncoding error:nil];
        NSData *data = [zoneStr dataUsingEncoding:NSUTF8StringEncoding];
        dispatch_async(dispatch_get_main_queue(), ^{
            if (data){
                NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
                NSString *openID = dic[@"openid"];
                NSString *unionid = dic[@"unionid"];
            }
        });
    });
    
}

获取到openID,头像等。要看后台怎么使用

你可能感兴趣的:(微信登录)