【iOS】微信第三方登入,ios第三方登入

來源:互聯網
上載者:User

【iOS】第三方登入,ios第三方登入

一:下載SDK

https://open.weixin.qq.com/cgi-bin/frame?t=resource/res_main_tmpl&verify=1&lang=zh_CN&target=res/app_download_ios

二:配置環境

將檔案拖入工程

配置URL scheme

三:DEFINE

 1 #ifndef LoginDemo_Define_h 2 #define LoginDemo_Define_h 3  4 #define kAppDescription   @“*******" 5  6 #define kWeiXinAppId               @“wx**************" 7 #define kWeiXinAppSecret           @“4f85d************011afa8a23d5a" 8  9 #define kWeiXinAccessToken   @"WeiXinAccessToken"10 #define kWeiXinOpenId             @"WeiXinOpenId"11 #define kWeiXinRefreshToken  @"WeiXinRefreshToken"12 13 14 #endif

四:AppDelegate.h

1 #import <UIKit/UIKit.h>2 3 #import "WeChatSDK_64/WXApi.h"4 5 @interface AppDelegate : UIResponder <UIApplicationDelegate,WXApiDelegate>6 7 @property (strong, nonatomic) UIWindow *window;8 9 @end

五:AppDelegate.m

 1 #import "AppDelegate.h" 2 #import "RootViewController.h" 3 #import "Define.h" 4  5 @interface AppDelegate () 6 { 7     RootViewController *root; 8 } 9 @end10 11 @implementation AppDelegate12 13 14 - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions15 {16     //….17 18     root = [[RootViewController alloc]init];19     self.window.rootViewController = root;20     21     [WXApi registerApp:kWeiXinAppId withDescription:kAppDescription];22     23     return YES;24 }25 26 - (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url27 {28     return [WXApi handleOpenURL:url delegate:self];29 }30 31 - (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation32 {33     return [WXApi handleOpenURL:url delegate:self];34 }35 36 - (void)onReq:(BaseReq*)req37 {38     /*39      onReq是終端向第三方程式發起請求,要求第三方程式響應。第三方程式響應完後必須調用sendRsp返回。在調用sendRsp返回時,會切回到終端程式介面。40      */41 }42 43 - (void)onResp:(BaseResp*)resp44 {45     /*46      如果第三方程式向發送了sendReq的請求,那麼onResp會被回調。sendReq請求調用後,會切到終端程式介面。47      */48     [root.weixinViewController getWeiXinCodeFinishedWithResp:resp];49 }

六:發起授權請求

1 - (void)loginButtonClicked2 {3     SendAuthReq* req =[[SendAuthReq alloc ] init];4     req.scope = @"snsapi_userinfo";5     req.state = kAppDescription;6     [WXApi sendReq:req];7 }

調用方法後會彈出授權頁面,完成授權後調用AppDelegate中的- (void)onResp:(BaseResp*)resp

七:處理返回資料,擷取code

 1 - (void)getWeiXinCodeFinishedWithResp:(BaseResp *)resp 2 { 3     if (resp.errCode == 0) 4     { 5         statusCodeLabel.text = @"使用者同意"; 6         SendAuthResp *aresp = (SendAuthResp *)resp; 7         [self getAccessTokenWithCode:aresp.code]; 8          9     }else if (resp.errCode == -4){10         statusCodeLabel.text = @"使用者拒絕";11     }else if (resp.errCode == -2){12         statusCodeLabel.text = @"使用者取消";13     }14 }

八:使用code擷取access token

 1 - (void)getAccessTokenWithCode:(NSString *)code 2 { 3     NSString *urlString =[NSString stringWithFormat:@"https://api.weixin.qq.com/sns/oauth2/access_token?appid=%@&secret=%@&code=%@&grant_type=authorization_code",kWeiXinAppId,kWeiXinAppSecret,code]; 4     NSURL *url = [NSURL URLWithString:urlString]; 5      6     dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ 7          8         NSString *dataStr = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:nil]; 9         NSData *data = [dataStr dataUsingEncoding:NSUTF8StringEncoding];10         11         dispatch_async(dispatch_get_main_queue(), ^{12             13             if (data)14             {15                 NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];16                 17                 if ([dict objectForKey:@"errcode"])18                 {19 //擷取token錯誤       20                 }else{                 21 //儲存AccessToken OpenId RefreshToken以便下次直接登陸22 //AccessToken有效期間兩小時,RefreshToken有效期間三十天         23                     [self getUserInfoWithAccessToken:[dict objectForKey:@"access_token"] andOpenId:[dict objectForKey:@"openid"]];24                 }25             }26         });27     });28     29     /*30      正確返回31      "access_token" = “Oez*****8Q";32      "expires_in" = 7200;33      openid = ooVLKjppt7****p5cI;34      "refresh_token" = “Oez*****smAM-g";35      scope = "snsapi_userinfo";36      */37     38     /*39      錯誤返回40      errcode = 40029;41      errmsg = "invalid code";42      */43 }

九:使用AccessToken擷取使用者資訊

 1 - (void)getUserInfoWithAccessToken:(NSString *)accessToken andOpenId:(NSString *)openId 2 { 3     NSString *urlString =[NSString stringWithFormat:@"https://api.weixin.qq.com/sns/userinfo?access_token=%@&openid=%@",accessToken,openId]; 4     NSURL *url = [NSURL URLWithString:urlString]; 5      6     dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ 7          8         NSString *dataStr = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:nil]; 9         NSData *data = [dataStr dataUsingEncoding:NSUTF8StringEncoding];10         11         dispatch_async(dispatch_get_main_queue(), ^{12             13             if (data)14             {15                 NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];16                 17                 if ([dict objectForKey:@"errcode"])18                 {19 //AccessToken失效20                     [self getAccessTokenWithRefreshToken:[[NSUserDefaults standardUserDefaults]objectForKey:kWeiXinRefreshToken]];21                 }else{22 //擷取需要的資料                    23                 }24             }25         });26     });27 28   /*29      city = ****;30      country = CN;31      headimgurl = "http://wx.qlogo.cn/mmopen/q9UTH59ty0K1PRvIQkyydYMia4xN3gib2m2FGh0tiaMZrPS9t4yPJFKedOt5gDFUvM6GusdNGWOJVEqGcSsZjdQGKYm9gr60hibd/0";32      language = "zh_CN";33      nickname = “****";34      openid = oo*********;35      privilege =     (36      );37      province = *****;38      sex = 1;39      unionid = “o7VbZjg***JrExs";40      */41     42     /*43      錯誤碼44      errcode = 42001;45      errmsg = "access_token expired";46      */47 }

十:使用RefreshToken重新整理AccessToken

該介面調用後,如果AccessToken未到期,則重新整理有效期間,如果已到期,更換AccessToken。

 1 - (void)getAccessTokenWithRefreshToken:(NSString *)refreshToken 2 { 3     NSString *urlString =[NSString stringWithFormat:@"https://api.weixin.qq.com/sns/oauth2/refresh_token?appid=%@&grant_type=refresh_token&refresh_token=%@",kWeiXinAppId,refreshToken]; 4     NSURL *url = [NSURL URLWithString:urlString]; 5      6     dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ 7          8          9         NSString *dataStr = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:nil];10         NSData *data = [dataStr dataUsingEncoding:NSUTF8StringEncoding];11         12         dispatch_async(dispatch_get_main_queue(), ^{13             14             if (data)15             {16                 NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];17                 18                 if ([dict objectForKey:@"errcode"])19                 {20 //授權到期                    21                 }else{22 //重新使用AccessToken擷取資訊23                 }24             }25         });26     });27     28     29     /*30      "access_token" = “Oez****5tXA";31      "expires_in" = 7200;32      openid = ooV****p5cI;33      "refresh_token" = “Oez****QNFLcA";34      scope = "snsapi_userinfo,";35      */36     37     /*38      錯誤碼39      "errcode":40030,40      "errmsg":"invalid refresh_token"41      */42 }

 


ios突然不可以登陸,要檢查網路設定

這可能是網路訊號不夠強,我之前都是這樣訊號好點再上就可以了
 
ios 分享後怎連結appstore

最新版本的對此作了限制

官方用意是打擊第三方靠來宣傳自己產品

從程式的角度去分析。他並不是屏蔽了App Store,也不是不相容IOS7。是因為5.0之後的版本對WebView(就是開啟網頁的那個頁面,包括朋友圈分享的網頁,郵箱內容的網頁)的串連地址處理做了改變。之前工程師可以通過自訂scheme跳轉到自己的應用。現在只有http(或許還有其他我們未知的scheme,開放給他們自己的應用或者夥伴)能夠直接跳轉。所以。現在大多數應用選擇的方式都是先通過http跳轉到自己的網站,然後再通過網站的JS(或者其他Action)跳轉到應用。
 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.