UserFacebook.m 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251
  1. /****************************************************************************
  2. Copyright (c) 2014 Chukong Technologies Inc.
  3. http://www.cocos2d-x.org
  4. Permission is hereby granted, free of charge, to any person obtaining a copy
  5. of this software and associated documentation files (the "Software"), to deal
  6. in the Software without restriction, including without limitation the rights
  7. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. copies of the Software, and to permit persons to whom the Software is
  9. furnished to do so, subject to the following conditions:
  10. The above copyright notice and this permission notice shall be included in
  11. all copies or substantial portions of the Software.
  12. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  13. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  14. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  15. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  16. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  17. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  18. THE SOFTWARE.
  19. ****************************************************************************/
  20. #import "UserFacebook.h"
  21. #import <FacebookSDK/FacebookSDK.h>
  22. #import "UserWrapper.h"
  23. #import "ParseUtils.h"
  24. #define OUTPUT_LOG(...) if (self.debug) NSLog(__VA_ARGS__);
  25. @implementation UserFacebook
  26. @synthesize mUserInfo;
  27. @synthesize debug = __debug;
  28. bool _isLogin = false;
  29. NSString *_userId = @"";
  30. NSString *_accessToken = @"";
  31. - (void) configDeveloperInfo : (NSMutableDictionary*) cpInfo{
  32. }
  33. - (void) login{
  34. [self _loginWithPermission:@[@"public_profile"]];
  35. }
  36. -(void) loginWithPermission:(NSString *)permissions{
  37. NSArray *permission = [permissions componentsSeparatedByString:@","];
  38. [self _loginWithPermission:permission];
  39. }
  40. -(void)_loginWithPermission:(NSArray *) permission{
  41. [FBSession openActiveSessionWithReadPermissions:permission
  42. allowLoginUI:YES
  43. completionHandler:
  44. ^(FBSession *session, FBSessionState state, NSError *error) {
  45. [self sessionStateChanged:session state:state error:error];
  46. // Retrieve the app delegate
  47. }];
  48. }
  49. - (void) logout{
  50. if (FBSession.activeSession.state == FBSessionStateOpen
  51. || FBSession.activeSession.state == FBSessionStateOpenTokenExtended) {
  52. // Close the session and remove the access token from the cache
  53. // The session state handler (in the app delegate) will be called automatically
  54. [FBSession.activeSession closeAndClearTokenInformation];
  55. // If the session state is not any of the two "open" states when the button is clicked
  56. }
  57. }
  58. - (BOOL) isLogined{
  59. return _isLogin;
  60. }
  61. -(NSString *)getUserID{
  62. return _userId;
  63. }
  64. - (BOOL) isLoggedIn{
  65. return _isLogin;
  66. }
  67. -(NSString *) getPermissionList{
  68. NSString *msg;
  69. if(FBSession.activeSession.state != FBSessionStateOpen && FBSession.activeSession.state != FBSessionStateOpenTokenExtended){
  70. msg =[ParseUtils MakeJsonStringWithObject:@"session closed please login first" andKey:@"error_message"];
  71. }else{
  72. NSArray *permissionList = [FBSession.activeSession permissions];
  73. msg = [ParseUtils MakeJsonStringWithObject:permissionList andKey:@"permissions"];
  74. }
  75. return msg;
  76. }
  77. -(NSString *)getAccessToken{
  78. return _accessToken;
  79. }
  80. - (NSString*) getSessionID{
  81. return @"";
  82. }
  83. - (void) setDebugMode: (BOOL) debug{
  84. __debug = debug;
  85. }
  86. - (NSString*) getSDKVersion{
  87. return [FBSettings sdkVersion];
  88. }
  89. - (void) setSDKVersion: (NSString *)sdkVersion{
  90. [FBSettings setSDKVersion:sdkVersion];
  91. }
  92. - (NSString*) getPluginVersion{
  93. return @"";
  94. }
  95. -(void)activateApp{
  96. [FBAppEvents activateApp];
  97. }
  98. -(void)logEventWithName:(NSString*) eventName{
  99. [FBAppEvents logEvent:eventName];
  100. }
  101. -(void)logEvent:(NSMutableDictionary*) logInfo{
  102. if(logInfo.count == 2){
  103. NSString *eventName = [logInfo objectForKey:@"Param1"];
  104. id param2 = [logInfo objectForKey:@"Param2"];
  105. if([param2 isKindOfClass:[NSDictionary class]]){
  106. NSDictionary *dic = (NSDictionary *)param2;
  107. [FBAppEvents logEvent:eventName parameters:dic];
  108. }else{
  109. double floatval = [[logInfo objectForKey:@"Param2"] floatValue];
  110. [FBAppEvents logEvent:eventName valueToSum:floatval];
  111. }
  112. }else if(logInfo.count == 3){
  113. NSString *eventName = [logInfo objectForKey:@"Param1"];
  114. double floatval = [[logInfo objectForKey:@"Param2"] floatValue];
  115. NSDictionary *para = [logInfo objectForKey:@"Param3"];
  116. [FBAppEvents logEvent:eventName valueToSum:floatval parameters:para];
  117. }
  118. }
  119. -(void)sessionStateChanged:(FBSession *)session state:(FBSessionState) state error:(NSError *)error{
  120. // If the session was opened successfully
  121. if (!error && state == FBSessionStateOpen){
  122. _accessToken = session.accessTokenData.accessToken;
  123. OUTPUT_LOG(@"Session opened");
  124. [FBRequestConnection startForMeWithCompletionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
  125. if (!error) {
  126. NSDictionary *dic = (NSDictionary *)result;
  127. _userId = [dic objectForKey:@"id"];
  128. _isLogin = true;
  129. NSMutableDictionary *result = [NSMutableDictionary dictionaryWithObjectsAndKeys:[FBSession.activeSession permissions],@"permissions",session.accessTokenData.accessToken,@"accessToken", nil];
  130. NSString *msg = [ParseUtils NSDictionaryToNSString:result];
  131. [UserWrapper onActionResult:self withRet:kLoginSucceed withMsg:msg];
  132. } else {
  133. NSString *msg = [ParseUtils MakeJsonStringWithObject:@"loginFailed" andKey:@"error_message"];
  134. [UserWrapper onActionResult:self withRet:kLoginFailed withMsg:msg];
  135. }
  136. }];
  137. }
  138. if (state == FBSessionStateClosed || state == FBSessionStateClosedLoginFailed){
  139. NSString *msg = [ParseUtils MakeJsonStringWithObject:@"loginFail Session closed" andKey:@"error_message"];
  140. if(!_isLogin){
  141. [UserWrapper onActionResult:self withRet:kLoginFailed withMsg:msg];
  142. }
  143. _isLogin = false;
  144. OUTPUT_LOG(@"Session closed");
  145. }
  146. // Handle errors
  147. if (error){
  148. _isLogin = false;
  149. NSString *errorText = @"";
  150. if ([FBErrorUtility shouldNotifyUserForError:error] == YES){
  151. errorText = [FBErrorUtility userMessageForError:error];
  152. } else {
  153. if ([FBErrorUtility errorCategoryForError:error] == FBErrorCategoryUserCancelled) {
  154. OUTPUT_LOG(@"User cancelled login");
  155. } else if ([FBErrorUtility errorCategoryForError:error] == FBErrorCategoryAuthenticationReopenSession){
  156. errorText = @"Your current session is no longer valid. Please log in again.";
  157. } else {
  158. NSDictionary *errorInformation = [[[error.userInfo objectForKey:@"com.facebook.sdk:ParsedJSONResponseKey"] objectForKey:@"body"] objectForKey:@"error"];
  159. errorText = [NSString stringWithFormat:@"Please retry. \n\n If the problem persists contact us and mention this error code: %@", [errorInformation objectForKey:@"message"]];
  160. }
  161. }
  162. errorText = [ParseUtils MakeJsonStringWithObject:errorText andKey:@"error_message"];
  163. [UserWrapper onActionResult:self withRet:kLoginFailed withMsg:errorText];
  164. OUTPUT_LOG(errorText);
  165. [FBSession.activeSession closeAndClearTokenInformation];
  166. }
  167. }
  168. -(void)requestPermissions:(NSString *)permision{
  169. if(FBSession.activeSession.state != FBSessionStateOpen && FBSession.activeSession.state != FBSessionStateOpenTokenExtended){
  170. NSString *msg = [ParseUtils MakeJsonStringWithObject:@"Session closed please login first" andKey:@"error_message"];
  171. [UserWrapper onPermissionsResult:self withRet:kPermissionFailed withMsg:msg];
  172. return;
  173. }
  174. NSArray *permission = [permision componentsSeparatedByString:@","];
  175. [FBSession.activeSession requestNewReadPermissions:permission
  176. completionHandler:^(FBSession *session, NSError *error) {
  177. if (!error) {
  178. // Permission granted
  179. OUTPUT_LOG(@"new permissions %@", [FBSession.activeSession permissions]);
  180. NSString *msg =[ParseUtils MakeJsonStringWithObject:[FBSession.activeSession permissions] andKey:@"permissions"];
  181. if(msg!=nil){
  182. [UserWrapper onPermissionsResult:self withRet:kPermissionSucceed withMsg:msg];
  183. }else{
  184. msg = [ParseUtils MakeJsonStringWithObject:@"parse permission data fail" andKey:@"error_message"];
  185. [UserWrapper onPermissionsResult:self withRet:kPermissionFailed withMsg:msg];
  186. }
  187. // We can request the user information
  188. } else {
  189. // An error occurred, we need to handle the error
  190. // Check out our error handling guide: https://developers.facebook.com/docs/ios/errors/
  191. NSString *msg = [ParseUtils MakeJsonStringWithObject:error.description andKey:@"error_message"];
  192. [UserWrapper onPermissionsResult:self withRet:(int)error.code withMsg:msg];
  193. OUTPUT_LOG(@"error %@", msg);
  194. }
  195. }];
  196. }
  197. -(void)api:(NSMutableDictionary *)params{
  198. NSString *graphPath = [params objectForKey:@"Param1"];
  199. int methodID = [[params objectForKey:@"Param2"] intValue];
  200. NSString * method = methodID == 0? @"GET":methodID == 1?@"POST":@"DELETE";
  201. NSDictionary *param = [params objectForKey:@"Param3"];
  202. int cbId = [[params objectForKey:@"Param4"] intValue];
  203. [FBRequestConnection startWithGraphPath:graphPath
  204. parameters:param HTTPMethod:method
  205. completionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
  206. if(!error){
  207. NSString *msg = [ParseUtils NSDictionaryToNSString:(NSDictionary *)result];
  208. if(nil == msg){
  209. NSString *msg = [ParseUtils MakeJsonStringWithObject:@"parse result failed" andKey:@"error_message"];
  210. [UserWrapper onGraphResult:self withRet:kGraphResultFail withMsg:msg withCallback:cbId];
  211. }else{
  212. OUTPUT_LOG(@"success");
  213. [UserWrapper onGraphResult:self withRet:kGraphResultSuccess withMsg:msg withCallback:cbId];
  214. }
  215. }else{
  216. NSString *msg = [ParseUtils MakeJsonStringWithObject:error.description andKey:@"error_message"];
  217. [UserWrapper onGraphResult:self withRet:(int)error.code withMsg:msg withCallback:cbId];
  218. OUTPUT_LOG(@"error %@", error.description);
  219. }
  220. }];
  221. }
  222. -(void)logPurchase:(NSMutableDictionary *)purchaseInfo{
  223. if(purchaseInfo.count == 2){
  224. NSNumber *count = [purchaseInfo objectForKey:@"Param1"];
  225. NSString *currency = [purchaseInfo objectForKey:@"Param2"];
  226. [FBAppEvents logPurchase:[count floatValue] currency:currency];
  227. }else if(purchaseInfo.count == 3){
  228. NSNumber *count = [purchaseInfo objectForKey:@"Param1"];
  229. NSString *currency = [purchaseInfo objectForKey:@"Param2"];
  230. NSDictionary *dict = [purchaseInfo objectForKey:@"Param3"];
  231. [FBAppEvents logPurchase:[count floatValue] currency:currency parameters:dict];
  232. }
  233. }
  234. @end