关于微信授权登录并获取Openid以及用户信息

一.集成微信授权登录

二.集成代码

  1. AppDelegate 代码

#import "AppDelegate.h"
#import "WXApi.h"
#import "WXApiManager.h"
@interface AppDelegate ()

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    
    [WXApi registerApp:@"wx1a607bdfc220e2e0" withDescription:@"demo 2.0"];

    // Override point for customization after application launch.
    return YES;
}

- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url {
    return  [WXApi handleOpenURL:url delegate:[WXApiManager sharedManager]];
}

- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation {
    return [WXApi handleOpenURL:url delegate:[WXApiManager sharedManager]];
}
2.调起授权代码

//调起授权

  -(void)Auth{

   [WXApiRequestHandler sendAuthRequestScope: kAuthScope
                                        State:kAuthState
                                       OpenID:kAuthOpenID
                             InViewController:self];
    
    
}

//遵循代理方法通过授权得到code 再通过code 得到用户的Openid
- (void)managerDidRecvAuthResponse:(SendAuthResp *)response {
  NSString *URlStr =  [self code:response.code];
    AFHTTPRequestOperationManager *httpClient = [AFHTTPRequestOperationManager manager];
    
    httpClient.requestSerializer = [AFJSONRequestSerializer serializer];
    //如果报接受类型不一致请替换一致text/html或别的
    httpClient.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];
//    [httpClient.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
//    [httpClient.requestSerializer setValue:@"utf-8" forHTTPHeaderField:@"charset"];
    // FOR HTTP
    httpClient.responseSerializer = [AFHTTPResponseSerializer serializer];
    httpClient.operationQueue.maxConcurrentOperationCount = 3;
    
    AFSecurityPolicy *securityPolicy = [AFSecurityPolicy defaultPolicy];
    
    securityPolicy.allowInvalidCertificates = YES;
    securityPolicy.validatesDomainName = NO;
    
    httpClient.securityPolicy = securityPolicy;
    
    [httpClient POST:URlStr parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSLog(@"%@", [[NSString alloc] initWithData:responseObject  encoding:NSUTF8StringEncoding] );
        
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"%@",error);
    }];
    
    
}

//配置URL
-(NSString*)code:(NSString*)selfCode{
    NSString *str = [NSString stringWithFormat:@"https://api.weixin.qq.com/sns/oauth2/access_token?appid=wx1a607bdfc220e2e0&secret=e13ded42afd77947311038480d7d3b64&code=%@&grant_type=authorization_code",selfCode];
    NSLog(@"%@",str);
    return str;
}


posted @ 2016-05-11 11:02  杨大龙dalong  阅读(3783)  评论(0编辑  收藏  举报