1.首先去微信開放平臺下載和導入對應的SDK文件,得到的最終文件如下。
2.在開放平臺創建對應的App,綁定對應的公司信息和配置一些App的信息(Bundle ID)等,通過審核后最終得到對應的AppID和AppSecret。
3. 在項目中配置URL Type? 步驟:選中項目中的 Targets──Info──URL Types──加號──Identifier和Role分別寫死:值分別是:weixin和Editor──URL Schemes的值(微信的APP ID)
4.在AppDelegate.m中的 (application:? didFinishLaunchingWithOptions:)方法中通過微信 AppID注冊微信
5.在需要微信登錄的類中導入對應的頭文件,登錄之前判斷用戶是否有安裝對應的微信客戶端,點擊微信登錄配置和發送微信登錄請求。具體如下:
6.最后在AppDelegate.m中的(application: openURL: sourceApplication: annotation:)方法中回調得到微信返回的用戶信息,具體如下。其中對應的宏定義如下:
代碼如下:
#define WeChatStateValue? ? ? ? ? ? @"110"
#define loginWithWeChatAppID? ? ? ? @"wx************"? ? ? ? ? ? ? ? ? //微信AppID
#define loginWithWeChatAppSecret? ? @"************"? ? //微信AppSecret
#define TencentWeChatID ? ? ? ? ? ? ? ? ? ? @"com.tencent.xin"
#define TencentWeChatGetTokenUrl? ? @"https://api.weixin.qq.com/sns/oauth2/access_token?"? // 用來請求微信access_token的地址
if([sourceApplication isEqualToString:TencentWeChatID]){ //如果是微信
//#warning 如果點擊了微信的確認登錄,并且沒有走這個回調,那就是項目中的URL Types中的URL Schemes沒有配置好(URL Schemes對應的值就是微信的ID,Identifier對應的值就是固定的:weixin)
NSString *backUrlStr=url.absoluteString; //得到返回的URL(轉為字符串類型)
NSString *subStrCode=[self getURLValues:@"code" webaddress:backUrlStr];//截取URL中Code參數對應的值
NSLogLeng(@"得到的Code值:%@",subStrCode);
Http *http=[[Http alloc]init];
NSString *finaStrUrl=[NSString stringWithFormat:@"appid=%@&secret=%@&code=%@&grant_type=%@",loginWithWeChatAppID,loginWithWeChatAppSecret,subStrCode,@"authorization_code"];
[http asynPostWithString:TencentWeChatGetTokenUrl parameters:finaStrUrl success:^(NSDictionary *resultDic, NSString *resultStr) {
NSString *getToken=resultDic[@"access_token"]; //得到token之后(這里沒有判斷Token的有效期,但是每次請求的就是最新的Token)
NSString *openidStr=resultDic[@"openid"];
//判斷授權憑證(access_token)是否有效
NSString *checkToken=[NSString stringWithFormat:@"https://api.weixin.qq.com/sns/auth?access_token=%@&openid=%@",getToken,openidStr];
[http asynGet:checkToken success:^(NSDictionary *resultDic, NSString *resultStr) {
NSLogLeng(@"token是否有用,微信返回的值:%@",resultDic);
if ([resultDic[@"errmsg"]isEqualToString:@"ok"]) { //如果Token值有用
NSString *getUserMessUrl=[NSString stringWithFormat:@"https://api.weixin.qq.com/sns/userinfo?access_token=%@&openid=%@",getToken,openidStr];
[http asynGet:getUserMessUrl success:^(NSDictionary *resultDic, NSString *resultStr) {
if ([resultDic isKindOfClass:[NSDictionary class]]) {
#warning 這里將得到的微信用戶信息通過接口傳給后臺
NSLogLeng(@"微信返回的用戶信息:%@",resultDic);
}
} error:^(NSError *error) {
}];
}
} error:^(NSError *error) {
}];
} error:^(NSError *error) {
}];
7.最終的結果如下:
最后:Http是一個網絡請求類,可以用AFN代替,有問題也可以通過QQ:1205632644 聯系到我。