一、在微信開放平臺註冊開發者帳號,建立應用提交審覈,審覈經過過,得到相應的AppID和AppSecret。html
二、下載iOS微信SDK。ios
三、導入微信SDK到工程,手動和自動均可以。c++
四、添加系統依賴庫sql
「SystemConfiguration.framework」;json
「CoreTelephony.framework」;api
「libsqlite3.0.tbd」;微信
「libstdc++.tbd」;微信開發
「libz.tbd」;app
"libWeChatSDK.a"url
五、ios9須要設置白名單並設置其它
在info.plist文件中加入 LSApplicationQueriesSchemes
TARGETS ->info ->URL type-> 添加URL type
Identifier 填寫:可自定義
URL Scheme填寫:wx1234567
六、iOS9默認使用https,如今先還原成http請求方式
第一步:在plist中添加NSAppTransportSecurity項,此項爲NSDictionary
第二步:在NSAppTransportSecurity下添加 NSAllowsArbitraryLoads類型爲Boolean,value爲YES
七、向微信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];
- }
-
- }
八、請求受權登陸微信,第三方移動應用會在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);
- }];
- }