微信三方登录相关(Swift)

前端之家收集整理的这篇文章主要介绍了微信三方登录相关(Swift)前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

微信登录条件

1.微信开放平台注册并认证成功(每年300RMB)

2.相关应用的微信的APPID和secret

3. 遵循微信代理WXApiDelegate

使用处编写相关登录代码

WXApi.registerApp("wxe7d57dc35de9c3c8")

let req = SendAuthReq.init()

req.scope = "snsapi_userinfo"

req.state = "wulianwang"

WXApi.send(req)

在回调方法中处理相关业务

func onResp(_ resp: BaseResp!) {

print(resp.errCode)

//errCode == 0时,请求access_token

if resp.errCode == 0 {

let pathStr = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=\(wxAPPID)&secret=\(secret)&code=\(resp.errCode)&grant_type=authorization_code"

let url = URL.init(string: pathStr)

let str = try! String.init(contentsOf: url!,encoding: String.Encoding(rawValue: String.Encoding.utf8.rawValue))

let data = str.data(using: String.Encoding(rawValue: String.Encoding.utf8.rawValue))

DispatchQueue.main.async {

if (data != nil){

let dic = try! JSONSerialization.jsonObject(with: data!,options: .mutableContainers)

/** 正确时返回的JSON格式入一下!!!

{

"access_token":"ACCESS_TOKEN",

"expires_in":7200,

"refresh_token":"REFRESH_TOKEN",

"openid":"OPENID",

"scope":"SCOPE",

"unionid": "o6_bmasdasdsad6_2sgVt7hMZOPfL"

}

*/

print(dic)

if (dic as! NSDictionary)["access_token"] == nil{

let alert = UIAlertController.init(title: "提示",message: str,preferredStyle: .alert)

let ok = UIAlertAction.init(title: "确定",style: .cancel,handler: nil)

alert.addAction(ok)

self.present(alert,animated: true,completion: nil)

}

}

}

}

}

//注意:secret可能会报错,注意重置secret!!!

appDelegate中增加相关方法

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

return WXApi.handleOpen(url as URL!,delegate: self)

}

原文链接:https://www.f2er.com/swift/321989.html

猜你在找的Swift相关文章