微信授权登录

http://www.mincoder.com/article/2115.shtml


1、可以到微信开发平台注册相关的APP,等待审核成功后可获得对应的key和secret,获取成功后需要单独申请开通登录和支付接口,如图所示:

2、和QQ比较类似,需要填写Url Schemes,如demo中的wxd930ea5d5a258f4f ,然后引入相应framework。

3、在AppDelegate中注册和实现授权后的回调函数,代码如下:

 
 //向微信注册  
    [WXApi registerApp:kWXAPP_ID withDescription:@"weixin"];  
      
  //授权后回调 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 微信用户当前国家信息 
      */      
      SendAuthResp *aresp = (SendAuthResp *)resp;  
      if (aresp.errCode== 0) {  
          NSString *code = aresp.code;  
          NSDictionary *dic = @{@"code":code};  
      }  
  }  
    
  //和QQ,新浪并列回调句柄
  - (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation  
  {  
      return [TencentOAuth HandleOpenURL:url] ||  
      [WeiboSDK handleOpenURL:url delegate:self] ||  
      [WXApi handleOpenURL:url delegate:self];;  
  }  
      
  - (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url  
  {  
      return [TencentOAuth HandleOpenURL:url] ||  
      [WeiboSDK handleOpenURL:url delegate:self] ||  
      [WXApi handleOpenURL:url delegate:self];;  
  }

4、第一步:获取code,这个用来获取token 
  - (IBAction)weixinLogin:(id)sender  
  {  
      [self sendAuthRequest];  
  }  
      
  -(void)sendAuthRequest  
  {  
      SendAuthReq* req =[[SendAuthReq alloc ] init];  
      req.scope = @"snsapi_userinfo,snsapi_base";  
      req.state = @"0744" ;  
      [WXApi sendReq:req];  
  }

这里获取后会调用之前在AppDelegate里面对应的oauthResp回调,获得得到的code。 
第二步:带上code获取token 
 
 -(void)getAccess_token  
  {  
      //https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code  
          
      NSString *url =[NSString stringWithFormat:@"https://api.weixin.qq.com/sns/oauth2/access_token?appid=%@&secret=%@&code=%@&grant_type=authorization_code",kWXAPP_ID,kWXAPP_SECRET,self.wxCode.text];  
          
      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];  
                /* 
                 { 
                 "access_token" = "OezXcEiiBSKSxW0eoylIeJDUKD6z6dmr42JANLPjNN7Kaf3e4GZ2OncrCfiKnGWiusJMZwzQU8kXcnT1hNs_ykAFDfDEuNp6waj-bDdepEzooL_k1vb7EQzhP8plTbD0AgR8zCRi1It3eNS7yRyd5A"; 
                 "expires_in" = 7200; 
                 openid = oyAaTjsDx7pl4Q42O3sDzDtA7gZs; 
                 "refresh_token" = "OezXcEiiBSKSxW0eoylIeJDUKD6z6dmr42JANLPjNN7Kaf3e4GZ2OncrCfiKnGWi2ZzH_XfVVxZbmha9oSFnKAhFsS0iyARkXCa7zPu4MqVRdwyb8J16V8cWw7oNIff0l-5F-4-GJwD8MopmjHXKiA"; 
                 scope = "snsapi_userinfo,snsapi_base"; 
                 } 
                 */  
                      
                  self.access_token.text = [dic objectForKey:@"access_token"];  
                  self.openid.text = [dic objectForKey:@"openid"];  
                    
              }  
          });  
      });  
  }

利用GCD来获取对应的token和openID。 
第三步:根据第二步获取的token和openid获取用户的相关信息。 
 
 -(void)getUserInfo  
  {  
     // https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID  
          
      NSString *url =[NSString stringWithFormat:@"https://api.weixin.qq.com/sns/userinfo?access_token=%@&openid=%@",self.access_token.text,self.openid.text];  
          
      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];  
                  /* 
                   { 
                   city = Haidian; 
                   country = CN; 
                   headimgurl = "http://wx.qlogo.cn/mmopen/FrdAUicrPIibcpGzxuD0kjfnvc2klwzQ62a1brlWq1sjNfWREia6W8Cf8kNCbErowsSUcGSIltXTqrhQgPEibYakpl5EokGMibMPU/0"; 
                   language = "zh_CN"; 
                   nickname = "xxx"; 
                   openid = oyAaTjsDx7pl4xxxxxxx; 
                   privilege =     ( 
                   ); 
                   province = Beijing; 
                   sex = 1; 
                   unionid = oyAaTjsxxxxxxQ42O3xxxxxxs; 
                   } 
                   */  
                      
                  self.nickname.text = [dic objectForKey:@"nickname"];  
                  self.wxHeadImg.image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[dic objectForKey:@"headimgurl"]]]];  
      
              }  
          });  
      
      });  
  }


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