微信登录条件
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!!!
func application(_ application: UIApplication,handleOpen url: URL) -> Bool {
return WXApi.handleOpen(url as URL!,delegate: self)
}
原文链接:https://www.f2er.com/swift/321989.html