iosswiftwechat

How do I do authorization and login with WeChat using the iOS SDK?


How do I do authorization and login with WeChat using the iOS SDK? There doesn't seem to be much information about this on stack overflow or google and most of the documents are in Chinese.


Solution

  • Choosing to answer my own question here as there seems to be lack of information about this on stack overflow and google. I hope others also find it useful.

    1.) Follow Suragch's excellent answer on how to setup the iOS SDK: How to add the WeChat API to a Swift project?. Make sure AppDelegate is setup as described with the func onReq(req: BaseReq!) and func onResp(resp: BaseResp!) methods implemented.

    2.) To get login and authorization working you MUST download and use the Chinese version of the SDK. Curiously some of the functions needed to login are removed from the English version. Chinese SDK here: https://open.weixin.qq.com/cgi-bin/showdocument?action=dir_list&t=resource/res_list&verify=1&id=open1419319164&lang=zh_CN

    3.) Firstly we want to authorize the app we want to use with WeChat. This can be done like so:

    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)
    

    This should return a code to func onResp(resp: BaseResp!) I implemented the method like so - triggering a notification:

    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.) With the code we can now try and get the openID and the accessToken. To do this we need to build a link using the appID, appSecret and do a HTTP GET request. The appID and appSecret are details you get when you register the app with WeChat. Example like so:

    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"
        }
    

    With this link we can perform a HTTP GET request and obtain the openID and accessToken in the JSON. (Try it in Postman). I won't post the code for this, but I'm using Alamofire.

    5.) Finally we can go one step further and try to get the WeChat user's nickname and profile photo. Very similar to before we create a new link using the openID and accessToken we obtained in the step before. Like so:

    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
        }
    

    Again, perform a HTTP GET request and the JSON will return the nickname and profile photo link!

    plus: detailed guide here: http://www.kekearif.com/how-to-implement-ios-wechat-login/