一、首先进入微信授权登陆之前的一个验证,在微信开放平台注册开发者账号,并拥有一个已经审核通过的移动应用,获得相应的AppID和AppSecrect,申请微信通过审核后(如下如)可开始植入工程的相关流程。
二、下载最新的SDK,链接如下:iOS SDK下载
下载下来的SDK如下图:
1、libWeChatSDK.a : 静态库,直接拖入工程中使用的;
2、README.txt : 重要内容,一些最新SDK版本的说明和安装配置
3、WechatAuthSDK.h :授权SDK
4、WXApi.h : 登陆方法所在类
5、WXApiObject.h : 所有接口和对象数据的定义类
iOS微信登陆注意事项:
1、目前移动应用上微信登录只提供原生的登录方式,需要用户安装微信客户端才能配合使用。
2、对于iOS应用,考虑到iOS应用商店审核指南中的相关规定,建议开发者接入微信登录时,先检测用户手机是否已安装微信客户端(使用sdk中isWXAppInstalled函数 ),对未安装的用户隐藏微信登录按钮,只提供其他登录方式(比如手机号注册登录、游客登录等)。【iOS9以上的系统需注意,要想使判断有效,需要进行白名单的适配】
iOS微信登陆大致流程:
1.第三方发起微信授权登录请求,微信用户允许授权第三方应用后,微信会拉起应用或重定向到第三方网站,并且带上授权临时票据code参数;
2.通过code参数加上AppID和AppSecret等,通过API换取access_token;
3.通过access_token进行接口调用,获取用户基本数据资源或帮助用户实现基本操作。
接下来我们结合工程来集成一下:
第一步:新建工程,并添加依赖库
第二步:设置URL Schemes(iOS9以上适配),URL Types,HTTPS设置 (如下图)
URL Schemes和HTTPS网络协议的适配,仅需要在Info.plist中添加如下相关源码:
网络适配:
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
</dict>
白名单适配:
<key>LSApplicationQueriesSchemes</key>
<array>
<string>weixin</string>
<string>wechat</string>
</array>
第三步:工程代码
-
-
-
-
-
-
-
-
- #import <UIKit/UIKit.h>
-
- #import "WXApi.h"
-
- @protocol WXDelegate <NSObject>
-
- - (void)loginSuccessByCode:(NSString *)code;
-
- @end
-
-
- @interface AppDelegate : UIResponder <UIApplicationDelegate,WXApiDelegate>
-
- @property (strong, nonatomic) UIWindow *window;
-
-
- @property (nonatomic,assign)id<WXDelegate>wxDelegate;
-
-
- @end
-
-
-
-
-
-
-
-
- #import "AppDelegate.h"
-
- #define weixinLoginAppId @""
- #define weixinLoginAppSecret @""
-
- @interface AppDelegate ()
-
-
- @end
-
- @implementation AppDelegate
-
-
- - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
-
-
-
- [WXApi registerApp:weixinLoginAppId withDescription:@"wechat"];
-
- return YES;
- }
-
- #pragma mark - 微信登陆
-
-
-
-
-
-
-
- - (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation {
- return [WXApi handleOpenURL:url delegate:self];
- }
-
-
-
-
-
-
-
- -(void) onResp:(BaseResp*)resp
- {
-
-
- NSLog(@"resp %d",resp.errCode);
-
-
-
-
-
-
-
-
-
-
-
- if ([resp isKindOfClass:[SendAuthResp class]]) {
- if (resp.errCode == 0) {
-
- if ([_wxDelegate respondsToSelector:@selector(loginSuccessByCode:)]) {
- SendAuthResp *resp2 = (SendAuthResp *)resp;
- [_wxDelegate loginSuccessByCode:resp2.code];
- }
- }else{
- NSLog(@"error %@",resp.errStr);
- UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"登录失败" message:[NSString stringWithFormat:@"reason : %@",resp.errStr] delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil nil];
- [alert show];
- }
- }
-
-
- }
- @end
-
-
-
-
-
-
-
-
- #import "ViewController.h"
- #import "WXApi.h"
-
- #import "AppDelegate.h"
-
- #define weixinLoginAppId @""
- #define weixinLoginAppSecret @""
-
- @interface ViewController ()<WXDelegate>
-
- @property (nonatomic,strong)AppDelegate *appDelegate;
-
- @end
-
- @implementation ViewController
-
- - (void)viewDidLoad {
- [super viewDidLoad];
-
-
-
-
-
- UIButton *weiXinLoginBtn = [UIButton buttonWithType:UIButtonTypeCustom];
- [weiXinLoginBtn setTitle:@"微信登陆" forState:UIControlStateNormal];
- weiXinLoginBtn.backgroundColor = [UIColor cyanColor];
- [weiXinLoginBtn addTarget:self action:@selector(weiXinLoginButtonAction) forControlEvents:UIControlEventTouchUpInside];
- weiXinLoginBtn.frame = CGRectMake(100, 100, 100, 100);
- [self.view addSubview:weiXinLoginBtn];
-
-
- }
-
-
- #pragma mark - 登陆按钮的响应方法
- - (void)weiXinLoginButtonAction{
-
-
- if ([WXApi isWXAppInstalled])
- {
-
- SendAuthReq* req =[[SendAuthReq alloc ] init] ;
-
- req.scope = @"snsapi_userinfo";
- req.openID = weixinLoginAppId;
- req.state = @"1245";
- _appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
- _appDelegate.wxDelegate = self;
-
- [WXApi sendReq:req];
-
-
- }else{
-
- UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"您没有安装微信,是否去下载" preferredStyle:UIAlertControllerStyleAlert];
- UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
- }];
-
- UIAlertAction *otherAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
- }];
-
-
- [alertController addAction:cancelAction];
- [alertController addAction:otherAction];
-
- [self presentViewController:alertController animated:YES completion:nil];
-
- }
- }
-
- #pragma mark - 此方法是,当用户点击允许授权之后,注册的通知的方法
-
-
- -(void)loginSuccessByCode:(NSString *)code{
-
-
- NSLog(@"code %@",code);
-
-
-
- NSString * grantStr = @"grant_type=authorization_code";
-
- NSString * tokenUrl = @"https://api.weixin.qq.com/sns/oauth2/access_token?";
- NSString * tokenUrl1 = [tokenUrl stringByAppendingString:[NSString stringWithFormat:@"appid=%@&",weixinLoginAppId]];
- NSString * tokenUrl2 = [tokenUrl1 stringByAppendingString:[NSString stringWithFormat:@"secret=%@&",weixinLoginAppSecret]];
- NSString * tokenUrl3 = [tokenUrl2 stringByAppendingString:[NSString stringWithFormat:@"code=%@&",code]];
- NSString * tokenUrlend = [tokenUrl3 stringByAppendingString:grantStr];
- NSLog(@"%@",tokenUrlend);
-
-
-
- NSURL *url = [NSURL URLWithString:tokenUrlend];
-
-
- NSURLRequest * request = [[NSURLRequest alloc]initWithURL:url];
-
- __weak typeof(self)weakSelf = self;
-
- [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
-
-
-
- NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
- NSString * access_token = [dic objectForKey:@"access_token"];
-
-
- NSString * openid = [dic objectForKey:@"openid"];
-
-
- [weakSelf requestUserInfoByToken:access_token andOpenid:openid];
-
-
- }];
-
-
- }
-
- #pragma mark - 根据accessToken和openID获取用户信息
-
- -(void)requestUserInfoByToken:(NSString *)token andOpenid:(NSString *)openID{
-
-
- NSString * userfulStr = [NSString stringWithFormat:@"https://api.weixin.qq.com/sns/userinfo?access_token=%@&openid=%@",token,openID];
- NSURL * userfulUrl = [NSURL URLWithString:userfulStr];
-
-
- NSURLRequest * userfulRequest = [[NSURLRequest alloc]initWithURL:userfulUrl];
-
- [NSURLConnection sendAsynchronousRequest:userfulRequest queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
-
-
- NSDictionary *userfulResultDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
-
- NSString * weixinOpenid = [userfulResultDic objectForKey:@"openid"];
-
- NSString * unionidStr = [userfulResultDic objectForKey:@"unionid"];
- NSString * langue = [userfulResultDic objectForKey:@"language"];
-
- NSString * nickStr = [userfulResultDic objectForKey:@"nickname"];
-
- NSString * filePath = [userfulResultDic objectForKey:@"headimgurl"];
-
- NSString * gender = [userfulResultDic objectForKey:@"sex"];
- NSString *sex;
- if ([gender intValue] == 1) {
- sex = @"1";
- }else if ([gender intValue] == 2){
- sex = @"0";
- }
-
- NSString * province = [userfulResultDic objectForKey:@"province"];
-
- NSString * city = [userfulResultDic objectForKey:@"city"];
-
- }];
-
-
-
-
- }
-
-
- - (void)didReceiveMemoryWarning {
- [super didReceiveMemoryWarning];
-
- }
-
- @end