Swift 3.0 微信三方授权登录

微信三方登录授权步骤:

一,下载导入SDK

现在微信支持cocopods,直接pod 'WechatOpenSDK'就能一键下载,老司机都懂得,小司机要先集成cocopods,或者按照微信开发文档,手动下载SDK,手动添加框架即可

二,配置 scheme

调用微信后,在微信中返回你的APP就要使用URL scheme,选中“TARGETS”一栏,在“info”标签栏的“URL type“添加“URL scheme”,“URL scheme”为你所注册的应用程序id

Swift 3.0 微信三方授权登录_第1张图片
屏幕快照 2017-05-23 下午2.56.28.png

还要添加白名单


Swift 3.0 微信三方授权登录_第2张图片
qQRJruU.png!web.png

三,微信接入

//添加头文件
#import "WXApi.h"
//添加协议  WXApiDelegate
//注册: 在APPDelagate的didFinishLaunchingWithOptions方法中添加
WXApi.registerApp("申请得到的APPID")

//微信登录成功和支付成功回调方法,添加一个通知 

    /*
     WXSuccess           = 0,    成功
     WXErrCodeCommon     = -1,  普通错误类型
     WXErrCodeUserCancel = -2,    用户点击取消并返回
     WXErrCodeSentFail   = -3,   发送失败
     WXErrCodeAuthDeny   = -4,    授权失败
     WXErrCodeUnsupport  = -5,   微信不支持
     */
  func onResp(_ resp: BaseResp!) {
        //微信分享
        if resp.errCode == 0 {
            let myResp:SendAuthResp = resp as! SendAuthResp
            print(myResp.code)
        }
    }


//MARK:微信登录
    func wechatClick() {
        if WXApi.isWXAppInstalled() {
            let req = SendAuthReq.init()
            req.scope = "snsapi_userinfo"
            req.state = "com.iuzuan.zsdfw"
            WXApi.send(req)
        }else{
        
           
        }
    }

//重写AppDelegate的handleOpenURL和openURL方法

    func application(_ application: UIApplication, handleOpen url: URL) -> Bool {
        
        WXApi.handleOpen(url, delegate: self)
        return true
        
    }
    
    func application(_ application: UIApplication, open url: URL, sourceApplication: String?, annotation: Any) -> Bool {
        WXApi.handleOpen(url, delegate: self)
        return true
    }
//成功回调
    func onResp(_ resp: BaseResp!) {
        if resp.errCode == 0 {
            let myResp:SendAuthResp = resp as! SendAuthResp
            print(myResp.code)
            //使用通知方法把回调返回到需要的控制器
            NotificationCenter.default.addObserver(self, selector: #selector(addNotic(notice:)), name: NSNotification.Name(rawValue: "MyNotice"), object: nil)
            ///发送通知
            NotificationCenter.default.post(name: NSNotification.Name.init(rawValue: "TaskNotice"), object: nil, userInfo: ["str":myResp.code])
        }
    }

四,授权

   //MARK:微信登录点击
    func wechatClick() {
        if WXApi.isWXAppInstalled() {
            let req = SendAuthReq.init()
            req.scope = "snsapi_userinfo"
            req.state = "com12312312"
            WXApi.send(req)
        }else{
          
        }
    }
    //MARK:成功后其它控制器的通知方法
    func addNotic(notice:Notification) {
        print(notice.userInfo!["str"] as Any)
        print("接受到通知")
        
        /*返回实例:下面的参数都有删减,使用自己的参数
         
         {
         "access_token": "8OVqz3f8JVEDEwTlFJozDeIR3WHvZWPVeZZkuJ1xoqJsGjmrPrgL7e3AEkRGg2FQ8bSmIgf85",
         "expires_in": 700,
         "refresh_token": "RBEMo5D0yirHuxODrcUslcFZG5DZWJlArz_wZEnxllTlZssfTTTw_qexxqZfCHr0qBLTagOkFvU9C2Lg2R708oyHw8Bw32FENdPjwA",
         "openid": "I",
         "scope": "snserinfo",
         "unionid": "CBhHOXTVqSM34bvLB4wk"
         }
         access_token有效期为2个小时
         refresh_token拥有较长的有效期(30天)当refresh_token失效的后,需要用户重新授权。
         
         */

        Alamofire.request("https://api.weixin.qq.com/sns/oauth2/access_token?", method: HTTPMethod.get, parameters: ["appid":"wxab59e8498" as Any,"secret":"55ca0720e63e6ca14b86c80a18" as Any,"code":notice.userInfo?["str"] as Any,"grant_type":"authorization_code"], encoding: URLEncoding.default, headers: nil).responseJSON { (response) in
            println(message: response)
            switch response.result {
            case .success(_):
                //把得到的JSON数据转为字典
                if let j = response.result.value as? Dictionary{
                    self.accessToken = j["access_token"] as! String?
                    self.wxOpenID = j["openid"] as! String?
                    self.setUserInfo()
                }
            case .failure(_): break
                
            }
        }
    }

    //MARK:微信登录获取用户信息
    func setUserInfo() {
        
        /*返回实例
         
         
         {
         "openid": "ovH_u0aLE02ZBPEGtJBI",
         "nickname": "111",
         "sex": 0,
         "language": "zh_CN",
         "city": "",
         "province": "",
         "country": "CN",
         "headimgurl": "http://wx.qlogo.cn/mpen/icF4iau8Sj7b2dwmVjtU1x153dqWOrDdMksichtT9ttGsxUkicRVNRKMl2tIFZ80EHFnBNeaPjGlrczBYHHr1fQgPp18nMv11111111aHd1/0",
         "privilege": [],
         "unionid": "oicxf1C0JOXTVqSM34bk123444"
         }
         
         */
        //拿到用户信息,登录授权成功
        Alamofire.request("https://api.weixin.qq.com/sns/userinfo?", method: HTTPMethod.get, parameters: ["access_token":self.accessToken as Any,"openid":self.wxOpenID as Any], encoding: URLEncoding.default, headers: nil).responseJSON { (response) in
            println(message: response)
            switch response.result {
            case .success(_):
               
                }
            case .failure(_): break
                
            }
        }
    }

警告⚠️:参数有删减,请对照开发文档填写自己申请的APP参数

你可能感兴趣的:(Swift 3.0 微信三方授权登录)