基于react native的原生iOS 微信登录
微信open SDK
环境
RN@0.73.6 React@18.2 XCode@15.3
引入SDK:WechatOpenSDK-XCFramework.xcframework
xcode配置请按照ios接入指南
ios 创建CustomerWxLogin类
CustomerWxLogin.h
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
#import <React/RCTEventEmitter.h>
#import <React/RCTBridgeModule.h>
#import <WXApi.h>
@interface CustomerWxLogin : RCTEventEmitter <RCTBridgeModule, WXApiDelegate>
@end
CustomerWxLogin.m
#import "CustomerWxLogin.h"
#import "WXApiObject.h"
#import <React/RCTEventDispatcher.h>
#import <React/RCTBridge.h>
#import <React/RCTLog.h>
#define APP_ID @"wx"
#define UNIVERSAL_LINK @"https://xxx.com/"
@implementation CustomerWxLogin
#define NOT_REGISTERED (@"registerApp required.")
#define INVOKE_FAILED (@"WeChat API invoke returns false.")
RCT_EXPORT_MODULE();
- (instancetype)init
{
self = [super init];
if (self) {
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleOpenURL:) name:@"RCTOpenURLNotification" object:nil];
}
return self;
}
- (void)dealloc
{
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
- (BOOL)handleOpenURL:(NSNotification *)aNotification
{
NSString * aURLString = [aNotification userInfo][@"url"];
NSURL * aURL = [NSURL URLWithString:aURLString];
if ([WXApi handleOpenURL:aURL delegate:self])
{
return YES;
} else {
return NO;
}
}
- (dispatch_queue_t)methodQueue
{
return dispatch_get_main_queue();
}
+ (BOOL)requiresMainQueueSetup {
return YES;
}
//微信登陆
RCT_EXPORT_METHOD(sendAuthRequest:(NSString *)scope
:(NSString *)state
:(RCTResponseSenderBlock)callback)
{
// 注册微信
[WXApi registerApp:APP_ID universalLink:UNIVERSAL_LINK];
SendAuthReq* req = [[SendAuthReq alloc] init];
req.scope = scope;
req.state = state;
[WXApi sendReq:req completion:^(BOOL success) {
callback(@[success ? [NSNull null] : INVOKE_FAILED]);
}];
}
#pragma mark - wx callback
-(void) onResp:(BaseResp*)resp
{
if ([resp isKindOfClass:[SendAuthResp class]]) {
SendAuthResp *authResp = (SendAuthResp *)resp;
NSString *authCode = authResp.code;
[self sendEventWithName:@"WxLoginSuccess" body:@{@"code": authCode}];
}
}
@end
react native端调用
创建wxLogin.js用于架起桥梁连接ios原生代码
import { NativeEventEmitter, NativeModules } from 'react-native';
let { WeChat, CustomerWxLogin } = NativeModules;
if (WeChat == null) {
WeChat = CustomerWxLogin;
}
const WeChatEmitter = new NativeEventEmitter(WeChat);
/**
* @method sendAuthRequest
* @param {Array} scopes - the scopes for authentication.
* @return {Promise}
*/
export function sendAuthRequest(scopes, state) {
return new Promise((resolve, reject) => {
WeChat.sendAuthRequest(scopes, state, () => {
WeChatEmitter.addListener('WxLoginSuccess', (events) => {
resolve(events)
})
});
});
}
配置AppDelegate.h
#import <RCTAppDelegate.h>
#import <UIKit/UIKit.h>
#import "WXApi.h"
@interface AppDelegate : RCTAppDelegate<WXApiDelegate>
@end
AppDelegate.mm
#import "AppDelegate.h"
#import <React/RCTBundleURLProvider.h>
#import <React/RCTLinkingManager.h>
#ifdef NSFoundationVersionNumber_iOS_9_x_Max
#import <UserNotifications/UserNotifications.h>
#endif
@implementation AppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
self.moduleName = @"BanDaiMatch";
// You can add your custom initial props in the dictionary below.
// They will be passed down to the ViewController used by React Native.
self.initialProps = @{};
return [super application:application didFinishLaunchingWithOptions:launchOptions];
}
- (NSURL *)sourceURLForBridge:(RCTBridge *)bridge
{
return [self getBundleURL];
}
- (NSURL *)getBundleURL
{
#if DEBUG
return [[RCTBundleURLProvider sharedSettings] jsBundleURLForBundleRoot:@"index"];
#else
return [[NSBundle mainBundle] URLForResource:@"main" withExtension:@"jsbundle"];
#endif
}
//weixin
- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url {
return [WXApi handleOpenURL:url delegate:self];
}
- (BOOL)application:(UIApplication *)application
continueUserActivity:(NSUserActivity *)userActivity
restorationHandler:(void(^)(NSArray<id<UIUserActivityRestoring>> * __nullable
restorableObjects))restorationHandler {
// 触发回调方法
[RCTLinkingManager application:application continueUserActivity:userActivity restorationHandler:restorationHandler];
return [WXApi handleOpenUniversalLink:userActivity
delegate:self];
}
@end
在页面中使用
import * as WeChat from '../../common/js/wxLogin';
//微信授权登录
WeChat.sendAuthRequest('snsapi_userinfo', 'wechat_sdk_demo').then(response => {
console.log("[处理授权登录后的结果]", response.code)
})