微信登录

1、在微信开放平台注册开发者帐号,并拥有一个已审核通过的移动应用,获得 AppID 和 AppSecret

2、下载微信的sdk   pod 'WechatOpenSDK'

3、在AppDelegate.h中声名微信sdk头文件和声名微信代理,如图:

#import <UIKit/UIKit.h>
#import <WXApi.h>

@interface AppDelegate : UIResponder <UIApplicationDelegate, WXApiDelegate>

@property (strong, nonatomic) UIWindow *window;

@end

4、在AppDelegate.m中的didFinishLaunchingWithOptions方法向微信终端程序注册AppID,如图

    // 向微信终端程序注册
    [WXApi registerApp:APPID];

5、在AppDelegate.m中实现下列方法

- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<UIApplicationOpenURLOptionsKey,id> *)options {
    return [WXApi handleOpenURL:url delegate:self];
}

#pragma mark - 微信的代理
//授权后回调 WXApiDelegate
-(void)onResp:(BaseReq *)resp
{
    /*
     ErrCode ERR_OK = 0(用户同意)
     ERR_AUTH_DENIED = -4(用户拒绝授权)
     ERR_USER_CANCEL = -2(用户取消)
     code    用户换取access_token的code,仅在ErrCode为0时有效
     state   第三方程序发送时用来标识其请求的唯一性的标志,由第三方程序调用sendReq时传入,由微信终端回传,state字符串长度不能超过1K
     lang    微信客户端当前语言
     country 微信用户当前国家信息
     */
    NSLog(@"微信的代理回调");
    if ([resp isKindOfClass:[SendAuthResp class]]) //判断是否为授权请求,否则与微信支付等功能发生冲突
    {
        SendAuthResp *aresp = (SendAuthResp *)resp;
        NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
        if (aresp.errCode== 0)
        {
            [center postNotificationName:WECHAT_NOTIFICATION object:nil userInfo:@{@"code":aresp.code}];
        }
        else {
            [center postNotificationName:WECHATCENTER_NOTIFICATION object:nil userInfo:nil];
        }
    }
}

6、在项目-TARGETS-info-URL Types中如下设置:

7、在info.plist中添加字段LSApplicationQueriesSchemes,如下:

8、现在配置就好了,可以点击按钮开始调起微信了,按钮方法如下:

if ([WXApi isWXAppInstalled]) {
        //构造SendAuthReq结构体
        SendAuthReq* req =[[SendAuthReq alloc]init];
        req.scope = @"snsapi_userinfo";     // 应用授权作用域,如获取用户个人信息则填写snsapi_userinfo
        req.state = @"123"; // 用于保持请求和回调的状态,授权请求后原样带回给第三方。该参数可用于防止csrf攻击(跨站请求伪造攻击),建议第三方带上该参数,可设置为简单的随机数加session进行校验
        //第三方向微信终端发送一个SendAuthReq消息结构
        [WXApi sendReq:req];
    }
    else {
        NSLog(@"不支持微信");
    }
}

9、调起微信后点击确认或取消都可以在AppDelegate.m中的微信代理回调-(void)onResp:(BaseReq *)resp中响应。

10、在微信代理的响应中可以获取到code,根据code、AppID和AppSecret请求微信的服务器可以获取到access_token和openid等信息。如下:

// 通过code获取access_token
- (void)AccessTokenWith:(NSString *)code Success:(void (^)(id responseObject))successTask Failure:(void (^)(NSError *error))failureTask {
    
    NSMutableString *m_str = [NSMutableString string];
    [m_str appendString:@"https://api.weixin.qq.com/sns/oauth2/access_token?appid="];
    [m_str appendString:APPID];// 你的AppID
    [m_str appendString:@"&secret="];
    [m_str appendString:SECRET];// 你的AppSecret
    [m_str appendString:@"&code="];
    [m_str appendString:code];
    [m_str appendString:@"&grant_type="];
    [m_str appendString:@"authorization_code"];
    
    [[self class] RequestWith:@"GET" url:m_str Success:^(id responseObject) {
        NSLog(@"通过code获取access_token = %@",responseObject);
        
    } Failure:^(NSError *error) {
        failureTask(error);
    }];
}

11、到这里微信登录就成功了,不过一般都会获取微信用户信息,需要access_Token和openid,在第10步已经获取到了

// 获取微信用户信息
- (void)WeChatUserInfoMessageWithAccessToken:(NSString *)accessToken openid:(NSString *)openid Success:(void (^)(id responseObject))successTask Failure:(void (^)(NSError *error))failureTask{
    
    NSMutableString *m_str = [NSMutableString string];
    [m_str appendString:@"https://api.weixin.qq.com/sns/userinfo?access_token="];
    [m_str appendString:accessToken];
    [m_str appendString:@"&openid="];
    [m_str appendString:openid];
    
    [[self class] RequestWith:@"GET" url:m_str Success:^(id responseObject) {
        NSLog(@"获取微信用户信息 = %@",responseObject);
        successTask(responseObject);
        
    } Failure:^(NSError *error) {
        NSLog(@"获取微信用户信息 error = %@",error);
        failureTask(error);
    }];
}

12、微信的用户信息如下

获取微信用户信息 = {
    city = Guangzhou;
    country = CN;
    headimgurl = "****"; // 微信头像url
    language = "zh_CN";
    nickname = "****"; // 微信名称
    openid = "***";
    privilege =     (
    );
    province = Guangdong;
    sex = 1;    // 性别
    unionid = "***";
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值