1、在微信开放平台注册开发者账号,创建应用提交审核,审核通过过,获得相应的AppID和AppSecret。
2、下载iOS微信SDK。
3、导入微信SDK到工程,手动和自动都可以。
4、添加系统依赖库
“SystemConfiguration.framework”;
“CoreTelephony.framework”;
“libsqlite3.0.tbd”;
“libstdc++.tbd”;
“libz.tbd”;
"libWeChatSDK.a"
5、ios9需要设置白名单并设置其它
在info.plist文件中加入 LSApplicationQueriesSchemes
TARGETS ->info ->URL type-> 添加URL type
Identifier 填写:可自定义
URL Scheme填写:wx1234567
6、iOS9默认使用https,现在先还原成http请求方式
第一步:在plist中添加NSAppTransportSecurity项,此项为NSDictionary
第二步:在NSAppTransportSecurity下添加 NSAllowsArbitraryLoads类型为Boolean,value为YES
7、向微信App程序注册第三方应用,并在第三方应用实现从微信App返回
- #import "WXApi.h"
- //微信开发者ID
- #define URL_APPID @"app id"
- - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
- //向微信注册应用。
- [WXApi registerApp:URL_APPID withDescription:@"wechat"];
- return YES;
- }
- #pragma mark - iOS9之前的代理设置
- - (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
- {
- if ([[url absoluteString] hasPrefix:@"tencent"]) {
- return [TencentOAuth HandleOpenURL:url];
- }else {
- return [WXApi handleOpenURL:url delegate:self];
- }
- }
- - (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url
- {
- if ([[url absoluteString] hasPrefix:@"tencent"]) {
- return [TencentOAuth HandleOpenURL:url];
- }else {
- return [WXApi handleOpenURL:url delegate:self];
- }
- }
- #pragma mark - iOS9之后的代理设置
- -(BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<NSString *,id> *)options{
- if ([[url absoluteString] hasPrefix:@"tencent"]) {
- return [TencentOAuth HandleOpenURL:url];
- }else {
- return [WXApi handleOpenURL:url delegate:self];
- }
- }
8、请求授权登录微信,第三方移动应用会在App本地拉起微信应用进行授权登录,微信用户确认后微信将拉起第三方移动应用,并带上授权临时票据(code)
《a》AppDelegate.m文件实现代码:
// 微信登录触发按钮
- - (IBAction)wechatLoginClick:(id)sender {
- if ([WXApi isWXAppInstalled]) {
- SendAuthReq *req = [[SendAuthReq alloc] init];
- req.scope = @"snsapi_userinfo";
- req.state = @"App";
- [WXApi sendReq:req];
- }
- else {
- [self setupAlertController];
- }
- }
#pragma mark - <WXApiDelegate>
// 微信回调,不管是登录还是分享成功与否,都是走这个方法 发送一个sendReq后,收到微信的回应
- 1. -(void) onResp:(BaseResp*)resp{
- NSLog(@"resp %d",resp.errCode);
- /*
- enum WXErrCode {
- WXSuccess = 0, 成功
- WXErrCodeCommon = -1, 普通错误类型
- WXErrCodeUserCancel = -2, 用户点击取消并返回
- WXErrCodeSentFail = -3, 发送失败
- WXErrCodeAuthDeny = -4, 授权失败
- WXErrCodeUnsupport = -5, 微信不支持
- };
- */
- if ([resp isKindOfClass:[SendAuthResp class]]) { //授权登录的类。
- if (resp.errCode == 0) { //成功。
- //这里处理回调的方法 。 通过代理吧对应的登录消息传送过去。
- if ([_wxDelegate respondsToSelector:@selector(loginSuccessByCode:)]) {
- SendAuthResp *resp2 = (SendAuthResp *)resp;
- [_wxDelegate loginSuccessByCode:resp2.code];
- }
- }else{ //失败
- NSLog(@"error %@",resp.errStr);
- UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"登录失败" message:[NSString stringWithFormat:@"reason : %@",resp.errStr] delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil nil];
- [alert show];
- }
- }
- }
《b》 ViewController.m 文件实现代码:
- #import "WXApi.h"
- #import "AppDelegate.h"
- //微信开发者ID
- #define URL_APPID @"appid"
- #define URL_SECRET @"app secret"
- #import "AFNetworking.h"
- #pragma mark - 微信登录触发事件
- - (IBAction)weixinLoginAction:(id)sender {
- if ([WXApi isWXAppInstalled]) {
- SendAuthReq *req = [[SendAuthReq alloc]init];
- req.scope = @"snsapi_userinfo";
- req.openID = URL_APPID;
- req.state = @"1245";
- appdelegate = [UIApplication sharedApplication].delegate;
- appdelegate.wxDelegate = self;
- [WXApi sendReq:req];
- }else{
- //把微信登录的按钮隐藏掉。
- }
- }
- #pragma mark - 微信登录回调
- -(void)loginSuccessByCode:(NSString *)code{
- NSLog(@"code %@",code);
- __weak typeof(*&self) weakSelf = self;
- AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
- manager.requestSerializer = [AFJSONRequestSerializer serializer];//请求
- manager.responseSerializer = [AFHTTPResponseSerializer serializer];//响应
- manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/html",@"application/json", @"text/json",@"text/plain", nil nil];
- //通过 appid secret 认证code . 来发送获取 access_token的请求
- [manager GET:[NSString stringWithFormat:@"https://api.weixin.qq.com/sns/oauth2/access_token?appid=%@&secret=%@&code=%@&grant_type=authorization_code",URL_APPID,URL_SECRET,code] parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
- } success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) { //获得access_token,然后根据access_token获取用户信息请求。
- NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
- NSLog(@"dic %@",dic);
- /*
- access_token 接口调用凭证
- expires_in access_token接口调用凭证超时时间,单位(秒)
- refresh_token 用户刷新access_token
- openid 授权用户唯一标识
- scope 用户授权的作用域,使用逗号(,)分隔
- unionid 当且仅当该移动应用已获得该用户的userinfo授权时,才会出现该字段
- */
- NSString* accessToken=[dic valueForKey:@"access_token"];
- NSString* openID=[dic valueForKey:@"openid"];
- [weakSelf requestUserInfoByToken:accessToken andOpenid:openID];
- } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
- NSLog(@"error %@",error.localizedFailureReason);
- }];
- }
- -(void)requestUserInfoByToken:(NSString *)token andOpenid:(NSString *)openID{
- AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
- manager.requestSerializer = [AFJSONRequestSerializer serializer];
- manager.responseSerializer = [AFHTTPResponseSerializer serializer];
- [manager GET:[NSString stringWithFormat:@"https://api.weixin.qq.com/sns/userinfo?access_token=%@&openid=%@",token,openID] parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
- } success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
- NSDictionary *dic = (NSDictionary *)[NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
- NSLog(@"dic ==== %@",dic);
- } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
- NSLog(@"error %ld",(long)error.code);
- }];
- }