Swift 微信授权登录

准备工作:(PS:Xcode = Version 11.3 (11C29))

1.创建项目
2.cd 项目路径
3.pod init(如果失败,可能是CocoaPods版本与xcode版本不一样,更新:gem install cocoapods --pre
4.vim Podfile
5.按 “i” 键,添加 pod 'WechatOpenSDK'; 然后“Esc”键,“:wq”保存。
6.pod install

CocoaPod添加微信SDK.png

7.新建桥接文件,引入 #import "WXApi.h"

图片.png

8.Build Setting -> 搜索 “bridging” 找到 Objective-C Bridging Header 设置引用路径:$(SRCROOT)/$(PROJECT_NAME)/WX_Bridging-Header.h
9.添加白名单

LSApplicationQueriesSchemes
    
        wechat
        weixin
        weixinULAPI
    

10.添加URL Schemes 回调

图片.png

正式接入微信授权登录

1.继承代理:WXApiDelegate(必须)、WXApiLogDelegate(可选)
2.新增block,用于回到微信授权登录成功获取的code,后续利用该code获取微信用户信息。
3.实现代理方法:onReqonResponLog(可选)
4.初始化微信SDK

//
//  SceneDelegate.swift
//  WeChatLoginDemo
//
//  Created by 郭明健 on 2019/12/31.
//  Copyright © 2019 郭明健. All rights reserved.
//

import UIKit

class SceneDelegate: UIResponder, UIWindowSceneDelegate, WXApiDelegate, WXApiLogDelegate {

    var window: UIWindow?
    //
    var wechatLoginCallback : ((_ code: String)->())?

    @available(iOS 13.0, *)
    func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {

        // 初始化微信SDK
        registerWeChat()

        guard let _ = (scene as? UIWindowScene) else { return }
    }

    @available(iOS 13.0, *)
    func sceneDidDisconnect(_ scene: UIScene) {
    }

    @available(iOS 13.0, *)
    func sceneDidBecomeActive(_ scene: UIScene) {
    }

    @available(iOS 13.0, *)
    func sceneWillResignActive(_ scene: UIScene) {
    }

    @available(iOS 13.0, *)
    func sceneWillEnterForeground(_ scene: UIScene) {
    }

    @available(iOS 13.0, *)
    func sceneDidEnterBackground(_ scene: UIScene) {
    }

    //MARK:-
    /// 初始化微信SDK
    func registerWeChat() {
        WXApi.startLog(by: .detail, logDelegate: self)
        WXApi.registerApp(WX_AppID, universalLink: WX_UNIVERSAL_LINK)
    }

    //MARK:- WXApiDelegate
    func onReq(_ req: BaseReq) {
        print("====>onReq")
    }

    func onResp(_ resp: BaseResp) {
        print("====>onResp")
        if resp.isKind(of: SendAuthResp.self) {
            let _resp = resp as! SendAuthResp
            if let code = _resp.code {
                //
                if wechatLoginCallback != nil {
                    wechatLoginCallback!(code)
                }
            }
        } else {
            print(resp.errStr)
        }
    }

    //MARK:- WXApiLogDelegate
    func onLog(_ log: String, logLevel level: WXLogLevel) {
        print(log)
    }
}

5.创建个工具类,用于调用微信用户信息。

//
//  WeChatFunc.swift
//  WeChatLoginDemo
//
//  Created by 郭明健 on 2020/1/2.
//  Copyright © 2020 郭明健. All rights reserved.
//

import UIKit

class WeChatFunc: NSObject {

    //MARK:- 微信授权登录
    /// 发送Auth请求到微信,支持用户没安装微信,等待微信返回onResp
    /// - Parameters:
    ///   - wxApiDelegate: WXApiDelegate对象,用来接收微信触发的消息。
    ///   - currentVC: viewController 当前界面对象。
    static func sendWeChatLogin(wxApiDelegate: WXApiDelegate, currentVC: UIViewController) {
        //构造SendAuthReq结构体
        let req = SendAuthReq()
        req.openID = WX_AppID
        req.scope = "snsapi_userinfo"
        req.state = "wx_oauth_authorization_state"// 用于保持请求和回调的状态,授权请求或原样带回。
        //第三方向微信终端发送一个SendAuthReq消息结构
        WXApi.sendAuthReq(req, viewController: currentVC, delegate: wxApiDelegate, completion: nil)
    }

    /// 微信:获取用户个人信息(UnionID 机制)
    static func getWeChatUserInfo(code: String, success: @escaping (_ userInfo: [String : Any]) -> ()) {
        self.getWeChatAccessToken(code: code) { (result, access_token, openid) in
            self.getWeChatUserInfo(access_token: access_token, openID: openid) { (userInfoJson) in
                success(userInfoJson)
            }
        }
    }

    /// 微信:通过 code 获取 access_token、openid
    static func getWeChatAccessToken(code: String, success: @escaping (_ result: [String : Any], _ access_token: String, _ openid: String) -> ()) {
        let urlString = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=\(WX_AppID)&secret=\(WX_AppSecret)&code=\(code)&grant_type=authorization_code"
        var request = URLRequest(url: URL(string: urlString)!)
        request.httpMethod = "GET"
        UIApplication.shared.isNetworkActivityIndicatorVisible = true
        URLSession.shared.dataTask(with: request) { data, response, error in
            DispatchQueue.main.async(execute: {
                UIApplication.shared.isNetworkActivityIndicatorVisible = false
                if error == nil && data != nil {
                    do {
                        let dic = try JSONSerialization.jsonObject(with: data!, options: []) as! [String: Any]
                        let access_token = dic["access_token"] as! String
                        let openID = dic["openid"] as! String
                        //
                        success(dic, access_token, openID)
                    } catch  {
                        print(#function)
                    }
                    return
                }
            })
        }.resume()
    }

    /// 微信:获取用户个人信息(UnionID 机制)
    static func getWeChatUserInfo(access_token: String, openID: String, success: @escaping (_ userInfo: [String : Any]) -> ()) {
        let urlString = "https://api.weixin.qq.com/sns/userinfo?access_token=\(access_token)&openid=\(openID)"
        var request = URLRequest(url: URL(string: urlString)!)
        request.httpMethod = "GET"
        UIApplication.shared.isNetworkActivityIndicatorVisible = true
        URLSession.shared.dataTask(with: request) { data, response, error in
            DispatchQueue.main.async(execute: {
                UIApplication.shared.isNetworkActivityIndicatorVisible = false
                if error == nil && data != nil {
                    do {
                        let dic = try JSONSerialization.jsonObject(with: data!, options: []) as! [String: Any]
                        //dic当中包含了微信登录的个人信息,用于用户创建、登录、绑定等使用
                        success(dic)
                    } catch  {
                        print(#function)
                    }
                    return
                }
            })
        }.resume()
    }

}

6.点击微信授权按钮,获取微信用户信息

    // 微信授权登录
    @IBAction func loginAction(_ sender: Any) {
        
        // 1.判断手机是否安装微信应用
        let isInstallWeChat = WXApi.isWXAppInstalled()
        if isInstallWeChat {
            if let appdelegate = UIApplication.shared.delegate as? AppDelegate {
                // 拉起微信授权登录
                WeChatFunc.sendWeChatLogin(wxApiDelegate: appdelegate, currentVC: self)
                // code回调
                appdelegate.wechatLoginCallback = { (code) in
                    // 获取微信用户信息
                    WeChatFunc.getWeChatUserInfo(code: code) { (userInfoJson) in
                        var info = ""
                        for key in userInfoJson.keys {
                            let value = userInfoJson[key]
                            info.append("\(key) : \(value ?? "")\n")
                        }
                        print("===========>微信返回个人信息:\n\(info)\n===========")
                    }
                }
            }
        } else {
            print("未安装微信APP!")
        }
        
    }
图片.png

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