移动应用微信授权登录iOS

简单介绍

微信OAuth2.0授权登录,简单来说:就是,让微信用户使用微信身份安全登录第三方应用或网站。

1、UnionID机制

使用微信微信OAuth2.0授权登录,我们必须先了解UnionID机制。

定义: 一个可能拥有多个移动应用、网站应用和公众帐号,我们可以通过获取用户基本信息中的unionid来区分用户的唯一性,因为只要是同一个微信开放平台帐号下的移动应用、网站应用和公众帐号,用户的unionid是唯一的。

举个例子,有一个应用A,该项目具有iOS端,android端,和微信公众号端。如果需要他们的账号是统一的,这样就有一个简便的方法,使用微信的UnionID机制。

步骤

  1. 第三方(我们的app)发起微信授权登录请求,微信用户允许授权第三方应用后,微信会拉起应用或重定向到第三方网站,并且带上授权临时票据code参数;(此时你可以获取到code,并可拉起微信打开授权登录页
  2. 通过code参数加上AppID和AppSecret等,通过API换取access_token;
  3. 通过access_token进行接口调用,获取用户基本数据资源或帮助用户实现基本操作。

这几个步骤我们完全可以按照微信开发平台上的资料一步步完成。肯定没问题的!!!
微信开发平台资料在这。
https://open.weixin.qq.com/cgi-bin/showdocument?action=dir_list&t=resource/res_list&verify=1&id=open1419317851&token=&lang=zh_CN

O(∩_∩)O哈哈~,我还是说一下使用步骤吧,记录一下!
(1)首先,必须要有AppId 和 AppSerect 。这个在注册应用时,会给你的。
(2)其次,微信的基本接入的设置是必须要有的,这个按照微信的接入指南来写就可以。https://open.weixin.qq.com/cgi-bin/showdocument?action=dir_list&t=resource/res_list&verify=1&id=1417694084&token=&lang=zh_CN
下面主要罗列代码中的部分:

  在AppDelegate中,导入#import "WXApi.h"
  // 向微信注册

if (![[NSUserDefaults standardUserDefaults] boolForKey:@"firstLaunch"]) {
BOOL isWXAppInstalled = [WXApi isWXAppInstalled];
if (isWXAppInstalled == NO) {

// testViewController * testVC = [[testViewController alloc] init];
// self.window.rootViewController = testVC;
AuthViewController * authVC = [[AuthViewController alloc] init];
self.window.rootViewController = authVC;
[self.window makeKeyAndVisible];
return YES;
}

    [self sendAuthRequest];


} else {
    
    [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"firstLaunch"];
    if ([[NSUserDefaults standardUserDefaults] objectForKey:@"openid"] && [[NSUserDefaults standardUserDefaults] objectForKey:@"unionid"]) {
        ViewController * vc = [[ViewController alloc] init];
        self.window.rootViewController = vc;
        [self.window makeKeyAndVisible];
        
    } else {
        
        BOOL isWXAppInstalled = [WXApi isWXAppInstalled];
        if (isWXAppInstalled == NO) {

            AuthViewController * authVC = [[AuthViewController alloc] init];
            self.window.rootViewController = authVC;
            [self.window makeKeyAndVisible];
            return YES;
        }

        [self sendAuthRequest];
        
    }
}

注意事项

请注意,在用户修改微信头像后,旧的微信头像URL将会失效,因此开发者应该自己在获取用户信息后,将头像图片保存下来,避免微信头像URL失效后的异常情况。

你可能感兴趣的:(移动应用微信授权登录iOS)