準(zhǔn)備工作:(PS:Xcode = Version 11.3 (11C29))
1.創(chuàng)建項(xiàng)目
2.cd 項(xiàng)目路徑
3.pod init(如果失敗,可能是CocoaPods版本與xcode版本不一樣匹涮,更新:gem install cocoapods --pre
)
4.vim Podfile
5.按 “i” 鍵运授,添加 pod 'WechatOpenSDK'旺垒; 然后“Esc”鍵油讯,“:wq”保存劲赠。
6.pod install
7.新建橋接文件摄悯,引入 #import "WXApi.h"
8.Build Setting -> 搜索 “bridging” 找到 Objective-C Bridging Header 設(shè)置引用路徑:$(SRCROOT)/$(PROJECT_NAME)/WX_Bridging-Header.h
9.添加白名單
<key>LSApplicationQueriesSchemes</key>
<array>
<string>wechat</string>
<string>weixin</string>
<string>weixinULAPI</string>
</array>
10.添加URL Schemes 回調(diào)
正式接入微信授權(quán)登錄
1.繼承代理:WXApiDelegate
(必須)矩肩、WXApiLogDelegate
(可選)
2.新增block现恼,用于回到微信授權(quán)登錄成功獲取的code,后續(xù)利用該code獲取微信用戶(hù)信息黍檩。
3.實(shí)現(xiàn)代理方法:onReq
叉袍、onResp
、onLog
(可選)
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.創(chuàng)建個(gè)工具類(lèi)刽酱,用于調(diào)用微信用戶(hù)信息喳逛。
//
// WeChatFunc.swift
// WeChatLoginDemo
//
// Created by 郭明健 on 2020/1/2.
// Copyright ? 2020 郭明健. All rights reserved.
//
import UIKit
class WeChatFunc: NSObject {
//MARK:- 微信授權(quán)登錄
/// 發(fā)送Auth請(qǐng)求到微信,支持用戶(hù)沒(méi)安裝微信棵里,等待微信返回onResp
/// - Parameters:
/// - wxApiDelegate: WXApiDelegate對(duì)象润文,用來(lái)接收微信觸發(fā)的消息姐呐。
/// - currentVC: viewController 當(dāng)前界面對(duì)象。
static func sendWeChatLogin(wxApiDelegate: WXApiDelegate, currentVC: UIViewController) {
//構(gòu)造SendAuthReq結(jié)構(gòu)體
let req = SendAuthReq()
req.openID = WX_AppID
req.scope = "snsapi_userinfo"
req.state = "wx_oauth_authorization_state"http:// 用于保持請(qǐng)求和回調(diào)的狀態(tài)转唉,授權(quán)請(qǐng)求或原樣帶回皮钠。
//第三方向微信終端發(fā)送一個(gè)SendAuthReq消息結(jié)構(gòu)
WXApi.sendAuthReq(req, viewController: currentVC, delegate: wxApiDelegate, completion: nil)
}
/// 微信:獲取用戶(hù)個(gè)人信息(UnionID 機(jī)制)
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)
}
}
}
/// 微信:通過(guò) 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()
}
/// 微信:獲取用戶(hù)個(gè)人信息(UnionID 機(jī)制)
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當(dāng)中包含了微信登錄的個(gè)人信息赠法,用于用戶(hù)創(chuàng)建麦轰、登錄、綁定等使用
success(dic)
} catch {
print(#function)
}
return
}
})
}.resume()
}
}
6.點(diǎn)擊微信授權(quán)按鈕砖织,獲取微信用戶(hù)信息
// 微信授權(quán)登錄
@IBAction func loginAction(_ sender: Any) {
// 1.判斷手機(jī)是否安裝微信應(yīng)用
let isInstallWeChat = WXApi.isWXAppInstalled()
if isInstallWeChat {
if let appdelegate = UIApplication.shared.delegate as? AppDelegate {
// 拉起微信授權(quán)登錄
WeChatFunc.sendWeChatLogin(wxApiDelegate: appdelegate, currentVC: self)
// code回調(diào)
appdelegate.wechatLoginCallback = { (code) in
// 獲取微信用戶(hù)信息
WeChatFunc.getWeChatUserInfo(code: code) { (userInfoJson) in
var info = ""
for key in userInfoJson.keys {
let value = userInfoJson[key]
info.append("\(key) : \(value ?? "")\n")
}
print("===========>微信返回個(gè)人信息:\n\(info)\n===========")
}
}
}
} else {
print("未安裝微信APP款侵!")
}
}