Swift集成微信登录

本文记录微信登录的全部流程

1.微信开发者平台获取必要密钥
(1)WXAPPID【微信开发者平台中的AppID】
(2)WXAPPSECRET【微信开发者平台中的AppSecret】
(3)UniversalLinks 【微信开发者平台中的Universal Links】

2.通过Pod加载微信SDK

pod 'WechatOpenSDK'

注意:

命令行下执行 pod search WechatOpenSDK,如显示的 WechatOpenSDK 版本不是最新的,则先执行 pod repo update 操作更新本地 repo 的内容

3.微信SDK接入

(1)打开Associated Domains开关,将Universal Links域名加到配置上


image.png

(2)在 Xcode 中,选择你的工程设置项,选中“TARGETS”一栏,在“info”标签栏的“URL type“添加“URL scheme”为你所注册的应用程序 id(如下图所示)


image.png

(3)在Xcode中,选择你的工程设置项,选中“TARGETS”一栏,在 “info”标签栏的“LSApplicationQueriesSchemes“添加weixin 和weixinULAPI(如下图所示)


image.png

4.微信SDK进行配置

(1)增加 WXApiDelegate 协议

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate,UITabBarControllerDelegate,WXApiDelegate {、、、}

(2)在代码中使用开发工具包

[1]要使你的程序启动后微信终端能响应你的程序,必须在代码中向微信终端注册你的 id。

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {

        WXApi.registerApp(WXAPPID, universalLink: UniversalLinks)
        WXApi.startLog(by: .detail) { (log) in
            print(#line,log)
        }
        return true
}

[2] 重写 AppDelegate 的 handleOpenURL 和 openURL 方法

func application(_ application: UIApplication, open url: URL, sourceApplication: String?, annotation: Any) -> Bool {
        
        return WXApi.handleOpen(url, delegate: self)
        
    }

func application(_ application: UIApplication, handleOpen url: URL) -> Bool {

        return WXApi.handleOpen(url, delegate: self)
    }

[3] 重写AppDelegate的continueUserActivity方法:

 func application(_ application: UIApplication, continue userActivity: NSUserActivity, restorationHandler: @escaping ([UIUserActivityRestoring]?) -> Void) -> Bool {
        
        return WXApi.handleOpenUniversalLink(userActivity, delegate: self)
        
    }

[4] 现在,你的程序要实现和微信终端交互的具体请求与回应,因此需要实现 WXApiDelegate 协议的两个方法:

 //MARK: ======================== WXApiDelegate
    func onReq(_ req: BaseReq) {
        print("aaaaaaaaaaaaaa")
    }
    
    func onResp(_ resp: BaseResp) {
        
        if resp.isKind(of: SendAuthResp.self) {
            
            if resp.errCode == 0 {
                
                let _resp = resp as! SendAuthResp
                if let code = _resp.code {
                      wxDelegate.loginSuccessByCode(code: code)
                }
              
            } else {
                
                print(resp.errStr)
            }
        }
    }

做到这一步,恭喜你,微信登录相关SDK已经准备完成,如果Universal Links有问题,可以参阅官方文档:
https://developers.weixin.qq.com/doc/oplatform/Mobile_App/Access_Guide/iOS.html

5.微信登录集成
(1)登录页面增加Delegate

class LoginViewController: UIViewController,WXDelegate {}

(2)请求 CODE(通过Button点击事件触发等)

    var appdelegate: AppDelegate!
 //MARK: ===================== 微信登录
    @objc func weixinLogin() {
        
       //构造SendAuthReq结构体
        let req = SendAuthReq()
        req.openID = WXAPPID
        req.scope = "snsapi_userinfo"
        req.state = "135790"//用于保持请求和回调的状态,授权请求后原样带回给第三方。该参数可用于防止 csrf 攻击(跨站请求伪造攻击),建议第三方带上该参数,可设置为简单的随机数加 session 进行校验
        appdelegate = UIApplication.shared.delegate as? AppDelegate
        appdelegate.wxDelegate = self
        //第三方向微信终端发送一个SendAuthReq消息结构
        WXApi.send(req)
     
    }

(3)通过 code 获取 access_token

//MARK: ==================== 微信授权回调
    func loginSuccessByCode(code: String) {
        
        let urlString = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=\(WXAPPID)&secret=\(WXAPPSECRET)&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
                        self.requestUserInfo(access_token, openID)
                    } catch  {
                        print(#function)
                    }
                    return
                }
            })
        }.resume()
    }

(4)获取微信个人信息

//MARK: ==================== 获取用户个人信息(UnionID机制)
    func requestUserInfo(_ token: String, _ openID: String) {
       
        let urlString = "https://api.weixin.qq.com/sns/userinfo?access_token=\(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当中包含了微信登录的个人信息,用于用户创建、登录、绑定等使用
                        print(#line, dic)
                        
                        
                    } catch  {
                        print(#function)
                    }
                    return
                }
            })
        }.resume()
    }

至此整个微信登录流程结束。

附录:
将要把apple-app-site-association文件放在根目录下
【链接】{"applinks":{"apps":[],"details...
https://xkjl.vnionpay.com/apple-app-site-association

你可能感兴趣的:(Swift集成微信登录)