一:下载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
2
3 #import "WeChatSDK_64/WXApi.h"
4
5 @interface AppDelegate : UIResponder
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 @end
10
11 @implementation AppDelegate
12
13
14 - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
15 {
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 *)url
27 {
28 return [WXApi handleOpenURL:url delegate:self];
29 }
30
31 - (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
32 {
33 return [WXApi handleOpenURL:url delegate:self];
34 }
35
36 - (void)onReq:(BaseReq*)req
37 {
38 /*
39 onReq是微信终端向第三方程序发起请求,要求第三方程序响应。第三方程序响应完后必须调用sendRsp返回。在调用sendRsp返回时,会切回到微信终端程序界面。
40 */
41 }
42
43 - (void)onResp:(BaseResp*)resp
44 {
45 /*
46 如果第三方程序向微信发送了sendReq的请求,那么onResp会被回调。sendReq请求调用后,会切到微信终端程序界面。
47 */
48 [root.weixinViewController getWeiXinCodeFinishedWithResp:resp];
49 }
六:发起授权请求
1 - (void)loginButtonClicked
2 {
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 }