如何使用iOS SDK进行授权并使用微信登录?

时间:2016-06-28 06:52:15

标签: ios swift wechat

如何使用iOS SDK进行授权并使用微信登录?在堆栈溢出或谷歌上似乎没有太多关于此的信息,大多数文档都是中文的。

2 个答案:

答案 0 :(得分:9)

选择回答我自己的问题,因为在堆栈溢出和谷歌上似乎缺乏关于此的信息。我希望其他人也觉得它很有用。

1。)关于如何设置iOS SDK的{strong> Suragch 优秀答案:How to add the WeChat API to a Swift project?。确保按照AppDelegatefunc onReq(req: BaseReq!)方法的说明设置func onResp(resp: BaseResp!)

2。)要获得登录和授权,您必须下载并使用SDK的中文版。奇怪的是,登录所需的一些功能将从英文版中删除。中文SDK在这里:https://open.weixin.qq.com/cgi-bin/showdocument?action=dir_list&t=resource/res_list&verify=1&id=open1419319164&lang=zh_CN

3.。)首先,我们想要授权我们想要与微信一起使用的应用程序。这可以这样做:

let req = SendAuthReq()
req.scope = "snsapi_userinfo" //Important that this is the same
req.state = "co.company.yourapp_wx_login" //This can be any random value
WXApi.sendReq(req)

这应该将代码返回给func onResp(resp: BaseResp!)我实现了这样的方法 - 触发通知:

func onResp(resp: BaseResp!) {
        if let authResp = resp as? SendAuthResp {
            if authResp.code != nil {
                let dict = ["response": authResp.code]
                NSNotificationCenter.defaultCenter().postNotificationName("WeChatAuthCodeResp", object: nil, userInfo: dict)             
            } else {                    
                let dict = ["response": "Fail"]
                NSNotificationCenter.defaultCenter().postNotificationName("WeChatAuthCodeResp", object: nil, userInfo: dict)                    
            }                
        } else {                
            let dict = ["response": "Fail"]
            NSNotificationCenter.defaultCenter().postNotificationName("WeChatAuthCodeResp", object: nil, userInfo: dict)
        }
    }

4。)使用代码,我们现在可以尝试获取openID和accessToken。为此,我们需要使用appIDappSecret构建链接并执行HTTP GET请求。 appIDappSecret是您在使用微信注册应用时获得的详细信息。示例如下:

private let appID = "somecode2132113"
private let appSecret = "someappsecret213123"

private let accessTokenPrefix = "https://api.weixin.qq.com/sns/oauth2/access_token?"

private func buildAccessTokenLink(withCode code: String) -> String {
        return accessTokenPrefix + "appid=" + appID + "&secret=" + appSecret + "&code=" + code + "&grant_type=authorization_code"
    }

通过此链接,我们可以执行HTTP GET请求并获取JSON中的openIDaccessToken。 (在Postman中尝试)。我没有为此发布代码,但我使用的是Alamofire。

5.)最后,我们可以更进一步,尝试获取微信用户的昵称和个人资料照片。与我们之前使用openIDaccessToken创建新链接之前非常类似。像这样:

private let userInfoPrefix = "https://api.weixin.qq.com/sns/userinfo?"

private func buildUserInfoLink(withOpenID openID: String, accessToken: String) -> String {
        return userInfoPrefix + "access_token=" + accessToken + "&openid=" + openID
    }

再次,执行HTTP GET请求,JSON将返回昵称和个人资料照片链接!

plus:详细指南:http://www.kekearif.com/how-to-implement-ios-wechat-login/

答案 1 :(得分:0)

我已经按照可接受的答案进行了所有操作,但是直到我更改了Info.plist

后,它才起作用。
    <key>LSApplicationQueriesSchemes</key>
    <array>
        <string>weixin</string>
    </array>

    <key>LSApplicationQueriesSchemes</key>
    <array>
        <string>weixin</string>
        <string>weixinULAPI</string>
    </array>

从官方指南here那里得到它