美文网首页
5+微信授权登录无法满足开发需求,怎么办?

5+微信授权登录无法满足开发需求,怎么办?

作者: 最晴天 | 来源:发表于2018-08-28 19:46 被阅读36次

    5+中的微信授权登录,获取到的code,会直接被用掉以获取token并用户信息等,而我们的实际开发中,考虑用户信息安全问题,通常需要的是将获取到的code,发送给自己的服务器,由服务器另行向微信服务端请求获取token。
    因此,在以HTML为主开发的app中,我们需要以插件的形式封装微信授权登录模块。
    先行阅读官方文档,IOS平台第三方插件开发指导http://ask.dcloud.net.cn/docs/#//ask.dcloud.net.cn/article/67
    而后可参照官方实例:IOS指纹识别插件开发方法http://ask.dcloud.net.cn/article/1348

    至此,基本上就对插件开发有了全面的了解,也知道如何入手了,甚至会觉得相当简单。
    开始之前,先行按照官方文档配置好5+SDK的配置,并且调试成功。

    1.注册插件
    确定插件名字,并配置feature.plist文件。

    2.在此,简单贴出个人在项目中用到的微信授权登录插件部分的代码,分为js和原生代码两部分,以供参考。

    原生代码部分:

    //
    //  WXPluginHandle.h
    //  TCM
    //
    //  Created by 晗 on 2018/8/24.
    //  Copyright © 2018年 晗. All rights reserved.
    //
    
    #import "PGPlugin.h"
    #import "PGMethod.h"
    
    @interface WXPluginHandle : PGPlugin
    
    - (void) onAppStarted:(NSDictionary*)options;
    
    //js 调用
    - (void)sendAuthRequest:(PGMethod *)command;
    
    @end
    
    
    //
    //  WXPluginHandle.m
    //  TCM
    //
    //  Created by 晗 on 2018/8/24.
    //  Copyright © 2018年 晗. All rights reserved.
    //
    
    #import "WXPluginHandle.h"
    #import "WXApi.h"
    
    #define WX_AppID @"wxc19dd06331e9b5f0"
    
    #define HHCodeNotiName @"wxplugin.code"
    
    @interface WXPluginHandle()<WXApiDelegate>
    
    @property (nonatomic,copy) NSString *codeStr;
    @property(nonatomic, strong)NSDictionary *launchOptions;
    @property (nonatomic, strong) PGMethod *codeCommand;
    @property (nonatomic, copy) void(^myCodeBlock)(NSString *codeStr);
    
    @end
    
    @implementation WXPluginHandle
    
    
    - (void)onAppStarted:(NSDictionary *)options{
        _launchOptions = options;
    
        [WXApi registerApp:WX_AppID];
    }
    
    //js中调用
    - (void)sendAuthRequest:(PGMethod *)command{
        
        if(command){
             NSLog(@"添加监听事件");
            __weak typeof(self) weakSelf = self;
            [[NSNotificationCenter defaultCenter] addObserverForName:HHCodeNotiName object:nil queue:[NSOperationQueue currentQueue] usingBlock:^(NSNotification * _Nonnull note) {
                __strong typeof(weakSelf) strongSelf = weakSelf;
                if (command) {
                    NSString *codeStr = note.userInfo[@"code"];
                    NSLog(@"code:%@",codeStr);
                    [strongSelf handleResultWithValue:codeStr command:command];
                }
                
                //移除监听
                [[NSNotificationCenter defaultCenter] removeObserver:strongSelf];
            }];
            
             NSLog(@"唤醒微信");
            SendAuthReq* req = [[SendAuthReq alloc] init];
            req.scope = @"snsapi_userinfo,snsapi_base";
            req.state = @"mxth";
           [WXApi sendReq:req];
           
    //        [self handleResultWithValue:[NSNumber numberWithBool:value] command:command];
        }
    }
    
    
    
    
    
    - (void)handleResultWithValue:(id)value command:(PGMethod *)command{
        PDRPluginResult *result = nil;
        PDRCommandStatus status = PDRCommandStatusOK;
        
        if ([value isKindOfClass:[NSString class]]) {
            value  = [value stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
            result = [PDRPluginResult resultWithStatus:status messageAsString:value];
        }else if ([value isKindOfClass:[NSArray class]]) {
            result = [PDRPluginResult resultWithStatus:status messageAsArray:value];
        }else if ([value isKindOfClass:[NSDictionary class]]){
            result = [PDRPluginResult resultWithStatus:status messageAsDictionary:value];
        }else if ([value isKindOfClass:[NSNull class]]){
            result = [PDRPluginResult resultWithStatus:status];
        }else if ([value isKindOfClass:[NSNumber class]]){
            CFNumberType numberType = CFNumberGetType((CFNumberRef)value);
            if (numberType == kCFNumberIntType) {
                result = [PDRPluginResult resultWithStatus:status messageAsInt:[value intValue]];
            } else  {
                result = [PDRPluginResult resultWithStatus:status messageAsDouble:[value doubleValue]];
            }
        }else{
            NSString *error = [NSString stringWithFormat:@"unrecognized type: %@",NSStringFromClass([value class])];
            NSLog(@"%@",error);
            result = [PDRPluginResult resultWithStatus:PDRCommandStatusError messageAsString:error];
        }
        if (command == self.codeCommand) {
            result.keepCallback = true;
        }
        [self toCallback:command.arguments[0] withReslut:[result toJSONString]];
        
    }
    
    
    @end
    
    

    下面为js代码部分

    document.addEventListener('plusready', function() {
        var _BARCODE = 'WXPlugin' // 插件名称
        var B = window.plus.bridge
    
        var WXPluginHandle = {
            code: "",
            callNative: function(fname, args, successCallback) {
                var callbackId = this.getCallbackId(successCallback, this.errorCallback)
                if (args != null) {
                    args.unshift(callbackId)
                } else {
                    var args = [callbackId]
                }
                return B.exec(_BARCODE, fname, args)
            },
            getCallbackId: function(successCallback) {
                var success = typeof successCallback !== 'function' ? null : function(args) {
                    successCallback(args)
                }
                return B.callbackId(success, this.errorCallback)
            },
            errorCallback: function(errorMsg) {
                console.log('Javascript callback error: ' + errorMsg)
            },
            fireDocumentEvent: function(ename, jsonData) {
                var event = document.createEvent('HTMLEvents')
                event.initEvent(ename, true, true)
                event.eventType = 'message'
    
                jsonData = JSON.stringify(jsonData)
                var data = JSON.parse(jsonData)
                event.arguments = data
                document.dispatchEvent(event)
            },
    
            //Public
            sendAuthRequest: function(callback) {
                this.callNative("sendAuthRequest", null, callback);
            },
    
            init: function() {
                if (plus.os.name == 'Android') {
                    this.callNative('init', null, null)
                }
            },
    
        }
        WXPluginHandle.init()
        window.plus.WXPlugin = WXPluginHandle
    }, true)
    
    

    相关文章

      网友评论

          本文标题:5+微信授权登录无法满足开发需求,怎么办?

          本文链接:https://www.haomeiwen.com/subject/ibnqwftx.html