iOS swift 微信App授权登录/网页版授权登录
一、向微信开放平台申请创建应用
二、接入后初始化并进行授权登录的操作
//微信SDK初始化
func initializeWeixinSDK(){
//在微信开放平台创建应用后申请到的appId
let wxappId = "你自己App的ID"
//在微信开放平台创建应用时填写的universal link
let universalLinks = "你自己App的universal link"
WXApi.registerApp(wxappId, universalLink: universalLinks)
//此处时开启微信SDK的调试log,不需要调试的可注释调
WXApi.startLog(by: .detail) { str in
FPPrint("=========微信登录============\(str)")
}
}
- 3、重写应用的三个方法(三个方法都重写,目的是兼容低版本系统)
func pplication( _ app:UIApplication, open url:URL, options: [UIApplication.OpenURLOptionsKey :Any] = [:]) -> Bool{
//url.host == "oauth":微信app授权跳转回到自身app时的判断
//url.host == "wapoauth":网页授权跳转回到自身app时的判断
//url.host == nil:微信app授权,点击取消时跳转回到自身app时的判断
if url.host == "oauth" || url.host == "wapoauth" || url.host == nil {
//设置授权成功/取消后接受回调的代理
return WXApi.handleOpen(url, delegate: self)
}
return true
}
func application(_ application: UIApplication, handleOpen url: URL) -> Bool {
WXApi.handleOpen(url, delegate: self)
}
func application(_ application: UIApplication, open url: URL, sourceApplication: String?, annotation: Any) -> Bool {
WXApi.handleOpen(url, delegate: self)
}
func sendWXAuthReq(){
//是否安装微信App
if WXApi.isWXAppInstalled() {
let sendAuth = SendAuthReq()
sendAuth.scope = "snsapi_userinfo"//授权作用域:获取用户个人信息
sendAuth.state = "wx_oauth_authorization_state"//用于保持请求和回调的状态,授权请求或原样带回
WXApi.send(sendAuth) { _ in
}
}else{
//未安装微信App,使用网页授权方式进行授权登录
//但是根据官方文档解析:最好是判断是否安装微信来显示微信授权登录按钮,这样可以更好的规避app被拒绝的风险
let sendAuth = SendAuthReq()
sendAuth.scope = "snsapi_userinfo"//授权作用域:获取用户个人信息
sendAuth.state = "pedometer_binding"//用于保持请求和回调的状态,授权请求或原样带回
DispatchQueue.main.async {
WXApi.sendAuthReq(sendAuth, viewController: self, delegate: appDelegate, completion: nil)
}
}
}
- 5、接受回调的方法(WXApiDelegate的方法)
//授权成功/取消授权回调的方法:网页和app授权都是走这个方法,后面会细说网页授权的原理
func onResp(_ resp: BaseResp) {
if resp.isKind(of: SendAuthResp.self){
let response = resp as! SendAuthResp
let errorCode = response.errCode
if errorCode != 0{
//授权失败,根据自身需要进行一些处理
return
}
if let code = response.code{
DispatchQueue.main.async {
//获取openId和access_token
self.getWXOpenId(code: code)
}
}else{
//=====微信登录========code为空======
}
}
}
//获取openID和access_token来获取微信用户的头像/昵称等
func getWXOpenId(code:String){
DispatchQueue.global().async {[weak self] in
let appId = "自身appId"//微信开放平台申请的appid
let secret = "secretkey"微信开放平台申请的secretkey
let codeStr = code
let grantType = "authorization_code"//类型,直接赋予该值即可
let urlStr = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=\(appId)&secret=\(secret)&code=\(codeStr)&grant_type=\(grantType)"
if let url = URL(string: urlStr){
if let zoneStr = try? String(contentsOf: url){
if let data = zoneStr.data(using: .utf8){
if let dataDict = try? JSONSerialization.jsonObject(with: data, options: .allowFragments) as? [String:Any]{
let openId = dataDict["openid"] as? String
let accessToken = dataDict["access_token"] as? String
if openId != nil && accessToken != nil{
//获取微信用户信息
self?.getWXUserInfo(accessToken: accessToken!, openId: openId!)
}
}else{
//获取失败
}
}else{
//获取失败
}
}else{
//获取失败
}
}else{
//获取失败
}
}
}
//获取用户信息:昵称/头像等
func getWXUserInfo(accessToken:String,openId:String){
DispatchQueue.global().async {[weak self] in
let urlStr = "https://api.weixin.qq.com/sns/userinfo?access_token=\(accessToken)&openid=\(openId)"
if let url = URL(string: urlStr){
if let zoneStr = try? String(contentsOf: url){
if let data = zoneStr.data(using: .utf8){
if let dataDict = try? JSONSerialization.jsonObject(with: data, options: .allowFragments) as? [String:Any]{
//获取成功,根据自身需要取值进行相应的操作
}else{
//获取失败
}
}else{
//获取失败
}
}else{
//获取失败
}
}else{
//获取失败
}
}
}
三、网页授权登录原理
1、未安装微信的情况,使用(二.4)的方式调用起网页授权页面,然后输入绑定微信号的手机号,点击发送,回收到授权登录的短信,如下图所示
- 2、点击短信授权链接,跳转到自身的App,会进入重写的方法(二.3),流程变成与安装微信的授权流程一样
四、最后的解释,或者遇到的坑
|