Skip to content

一、WeiXinInterfacePlugin.js

javascript
var exec = require('cordova/exec');
/**
 * 注册微信AppID 
 * 同时传入AppSecret 后期接口调用
 * params:appId --公众平台的应用id
 * appSecret --公众平台的应用加密  
 * return: true/false
 */
exports.registerWeiXin = function (params, success, error) {
    exec(success, error, 'WeiXinInterfacePlugin', 'registerWeiXin', [params]);
};

/**
 * 检测是否安装微信 
 * @param {*} success 
 * @param {*} error 
 * @returns true/false
 */
exports.isWXAppInstalled = function (success, error) {
    exec(success, error, 'WeiXinInterfacePlugin', 'isWXAppInstalled',[]);
};

/**
 * 发起微信用户授权请求
 * @param {*} params scope state
 * @param {*} success 
 * @param {*} error 
 * @returns 
 */
exports.getAuthForWeiXin = function (params, success, error) {
    exec(success, error, 'WeiXinInterfacePlugin', 'getAuthForWeiXin', [params]);
};

/**
 * 获取微信openId
 * @param {*} success 
 * @param {*} error 
 * @returns openId access_token
 */
exports.getWeiXinCode = function (success, error) {
    exec(success, error, 'WeiXinInterfacePlugin', 'getWeiXinCode', []);
};

/**
 * 获取微信openId
 * @param {*} params code
 * @param {*} success 
 * @param {*} error 
 * @returns openId access_token
 */
exports.getWeiXinOpenId = function (params,success, error) {
    exec(success, error, 'WeiXinInterfacePlugin', 'getWeiXinOpenId', [params]);
};

二、iOS相关代码

  • WeiXinInterfacePlugin.h
/********* WeiXinInterfacePlugin.m Cordova Plugin Implementation *******/

#import <Cordova/CDV.h>
#import "WXApi.h"
#import "WXApiObject.h"
#import "AppDelegate.h"

@interface WeiXinInterfacePlugin : CDVPlugin <WXApiDelegate>{
    // NSString * callbackId;
    // NSString * appId;
    // NSString * appSecret;
    // NSMutableDictionary *resp;
}

@property (nonatomic, strong) NSString *currentCallbackId;
@property (nonatomic, strong) NSString *appId;
@property (nonatomic, strong) NSString *appSecret;
@property (nonatomic, strong) NSMutableDictionary *resp;
@property (nonatomic, strong) AppDelegate *appDelegate;



//注册公众平台
- (void)registerWeiXin:(CDVInvokedUrlCommand *)command;

//检测微信是否安装
- (void)isWXAppInstalled:(CDVInvokedUrlCommand *)command;

//向微信发起授权应用
- (void)getAuthForWeiXin:(CDVInvokedUrlCommand*)command;

//获取openId
- (void)getWeiXinOpenId:(CDVInvokedUrlCommand*)command;

//获取code
- (void)getWeiXinCode:(CDVInvokedUrlCommand*)command;


//重写微信响应
- (void)onResp:(BaseResp *)resp withAppParams:(NSDictionary *)params withCallbackId:(CDVInvokedUrlCommand*)command;

@end
  • WeiXinInterfacePlugin.m
/********* WeiXinInterfacePlugin.m Cordova Plugin Implementation *******/

#import "WeiXinInterfacePlugin.h"

@implementation WeiXinInterfacePlugin


- (void)registerWeiXin:(CDVInvokedUrlCommand*)command{

    NSLog(@"enter registerWeiXin");
    //初始化返回值
    self.resp = [@{} mutableCopy]; //返回信息
    NSMutableDictionary *data = [@{} mutableCopy]; //返回data信息
    self.appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    //判断是否有参数传入
    if ([command.arguments count] > 0)
    { //获取参数数组下标为0的参数值   
         NSDictionary *param = [command.arguments objectAtIndex:0];
         self.appId = param[@"appId"]; //app前端传入,应用Id
         self.appSecret = param[@"appSecret"]; //app前端传入,appSecret
         self.appDelegate.params4WeiXin = param;
         if([WXApi registerApp: self.appId]){
            [data setValue:self.appId forKey:@"appId"];
            [data setValue:@"1" forKey:@"isRegister"];
            [self.resp setObject:data forKey:@"data"];  
            [self.resp setValue:@"0000" forKey:@"respCode"];
            [self.resp setValue:@"注册成功" forKey:@"respDesc"];
         }else{
            [self.resp setValue:@"0001" forKey:@"respCode"];
            [self.resp setValue:@"注册失败" forKey:@"respDesc"];    
         }
    }else{
        [self.resp setValue:@"0002" forKey:@"respCode"];
        [self.resp setValue:@"获取参数失败" forKey:@"respDesc"];    
    }

    [self sendRespInfo:self.resp withCallBackID:command.callbackId];
}


- (void)isWXAppInstalled:(CDVInvokedUrlCommand *)command
{
    NSLog(@"enter isWXAppInstalled");

    CDVPluginResult *commandResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsBool:[WXApi isWXAppInstalled]];

    [self.commandDelegate sendPluginResult:commandResult callbackId:command.callbackId];
}

- (void)getAuthForWeiXin:(CDVInvokedUrlCommand*)command
{
    
    NSLog(@"enter getAuthForWeiXin");
    
    SendAuthReq* req =[[SendAuthReq alloc] init];//申请空间、初始化SendAuthReq
    
    if ([command.arguments count] > 0)
    {
         NSDictionary *param = [command.arguments objectAtIndex:0];
         req.scope = param[@"scope"]; //app前端传入,
         req.state = param[@"state"]; //app前端传入,
    }

    NSLog(@"getAuthForWeiXin req.scope --->%@ req.state--->%@",req.scope,req.state);

    BOOL isSendAuthReq = [WXApi sendAuthReq:req viewController:self.viewController delegate:self];
    NSMutableDictionary *data = [@{} mutableCopy]; //返回data信息
    //如果授权请求成功
    if (isSendAuthReq)
    {
        
        NSLog(@"getAuthForWeiXin sendAuthReq");
        // AppDelegate *appDelegate = (AppDelegate*)[UIApplication sharedApplication].delegate;
        // self.resp = appDelegate.resp4weChat;
        self.appDelegate.command = command;
        [data setValue:@"1" forKey:@"isSendAuthReq"];
        [self.resp setObject:data forKey:@"data"];
        [self.resp setValue:@"0000" forKey:@"respCode"];
        [self.resp setValue:@"授权请求发送成功" forKey:@"respDesc"];
    }
    else
    {
        NSLog(@"getAuthForWeiXin sendAuthReq error");
        [self.resp setValue:@"0001" forKey:@"respCode"];
        [self.resp setValue:@"授权请求发送失败" forKey:@"respDesc"];
        
    }
    NSLog(@"getAuthForWeiXin sendAuthReq sendRespInfo");
    [self sendRespInfo:self.resp withCallBackID:command.callbackId];
}

- (void)getWeiXinCode:(CDVInvokedUrlCommand*)command{

    NSLog(@"enter getWeiXinCode ");

    AppDelegate *appDelegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];

    NSLog(@"getWeiXinCode code is %@",appDelegate.code);

    NSMutableDictionary *data = [@{} mutableCopy]; //返回data信息
    if(appDelegate.code){
        [data setValue:appDelegate.code forKey:@"code"];
        [self.resp setObject:data forKey:@"data"];
        [self.resp setValue:@"0000" forKey:@"respCode"];
        [self.resp setValue:@"code获取成功" forKey:@"respDesc"];  
    }else{
        [self.resp setValue:@"0001" forKey:@"respCode"];
        [self.resp setValue:@"code获取失败" forKey:@"respDesc"];  
    }

    [self sendRespInfo:self.resp withCallBackID:command.callbackId];
}


- (void)getWeiXinOpenId:(CDVInvokedUrlCommand*)command;
{
    NSLog(@"enter getWeiXinOpenId ");
    if ([command.arguments count] > 0)
    {
        NSDictionary *param = [command.arguments objectAtIndex:0];
        NSString *code = param[@"code"]; //app前端传入code,
        NSLog(@"getWeiXinOpenId code is %@",code);
        NSLog(@"getWeiXinOpenId appId is %@",self.appId);
        NSLog(@"getWeiXinOpenId appSecret is %@",self.appSecret);
        NSString *urlStr = [NSString stringWithFormat:@"https://api.weixin.qq.com/sns/oauth2/access_token?appid=%@&secret=%@&code=%@&grant_type=authorization_code",self.appId,self.appSecret,code];
        NSLog(@"urlStr-->%@",urlStr);
        //3.转码
        urlStr = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        //URL里面不能包含中文
        NSURL *url = [NSURL URLWithString:urlStr];
        //4.创建请求对象
        NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; // 默认就是GET请求
        request.timeoutInterval = 5; // 设置请求超时
        //5.发送请求
        [self sendAsync:request withCallbackId:command];    
         
    }
}


// 微信授权登录发送异步:GET请求
- (void)sendAsync:(NSURLRequest *)request withCallbackId:(CDVInvokedUrlCommand*)command
{
    NSOperationQueue *queue = [NSOperationQueue mainQueue];
    [NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
       
        NSMutableDictionary *resp = [@{} mutableCopy]; //返回resp信息
        if (data) { // 请求成功
            NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
            NSString *error = dict[@"errcode"];
            // self.resp4weChat = [@{} mutableCopy]; //返回信息
            NSMutableDictionary *data = [@{} mutableCopy]; //返回data信息
            if (error) { // 登录失败
                NSLog(@"sendAsync error %@",error);
                //赋值失败返回
                 [resp setValue:@"0001" forKey:@"respCode"];
                 [resp setValue:@"授权登录请求失败" forKey:@"respDesc"];
            } else { // 登录成功
                NSString *access_token = dict[@"access_token"]; // 接口调用凭证(有效期2h)
                NSString *openid = dict[@"openid"]; // 授权用户唯一标识
                //赋值成功返回
                [data setValue:access_token forKey:@"access_token"];
                [data setValue:openid forKey:@"openid"];
                [resp setObject:data forKey:@"data"];
                [resp setValue:@"0000" forKey:@"respCode"];
                [resp setValue:@"授权登录请求成功" forKey:@"respDesc"];
                NSLog(@"openid is %@ access_token is %@ " ,openid,access_token);
            }
           
        } else { // 请求失败
             [resp setValue:@"0002" forKey:@"respCode"];
             [resp setValue:@"网络繁忙, 请稍后再试" forKey:@"respDesc"];
        }
// CDVPluginResult *commandResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:resp];
// [self.commandDelegate sendPluginResult:commandResult callbackId:command.callbackId];
        
          [self sendRespInfo:resp withCallBackID:command.callbackId];
    }];
}


/**
 普通接口返回信息
 @param resp <#resp description#>
 @param callbackId <#callbackId description#>
 */
- (void)sendRespInfo:(NSDictionary *)resp withCallBackID: (NSString *)callbackId {
    NSLog (@"sendRespInfo is :%@", [self objToString:resp]);
    
    CDVPluginResult *result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:resp];
    //因为只能使用 callbackId 一次除非你告诉Cordova不要清除 callbackId 将 CDVPluginResult.keepCallback 设置为YES 。
    [result setKeepCallbackAsBool:YES];
    
    [self.commandDelegate sendPluginResult:result callbackId:callbackId];
}


/**
 对象转json字符串
 @param object <#object description#>
 @return <#return value description#>
 */
-(NSString*)objToString:(id)object
{
    NSString *jsonString = nil;
    NSError *error;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:object
                                                       options:NSJSONWritingPrettyPrinted // Pass 0 if you don't care about the readability of the generated string
                                                         error:&error];
    if (! jsonData) {
        NSLog(@"objToString get an error: %@", error);
    } else {
        jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    }
    return jsonString;
}




#pragma mark "CDVPlugin Overrides"

// - (void)handleOpenURL:(NSNotification *)notification
// {
// NSURL* url = [notification object];

// if ([url isKindOfClass:[NSURL class]] && [url.scheme isEqualToString:self.wechatAppId])
// {
// [WXApi handleOpenURL:url delegate:self];
// }
// }


- (void)successWithCallbackID:(NSString *)callbackID
{
    [self successWithCallbackID:callbackID withMessage:@"OK"];
}

- (void)successWithCallbackID:(NSString *)callbackID withMessage:(NSString *)message
{
    CDVPluginResult *commandResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:message];
    [self.commandDelegate sendPluginResult:commandResult callbackId:callbackID];
}

- (void)failWithCallbackID:(NSString *)callbackID withError:(NSError *)error
{
    [self failWithCallbackID:callbackID withMessage:[error localizedDescription]];
}

- (void)failWithCallbackID:(NSString *)callbackID withMessage:(NSString *)message
{
    CDVPluginResult *commandResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:message];
    [self.commandDelegate sendPluginResult:commandResult callbackId:callbackID];
}

@end

三、Android相关代码

  • 主要逻辑代码
java
package com.ai.ced.weixin;
import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.LOG;
import org.apache.cordova.PluginResult;
import android.app.Activity;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;


import android.util.Log;

import com.ai.wsl.gz.BuildConfig;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import android.content.Context;
import android.content.SharedPreferences;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.ai.wsl.gz.wxapi.WXEntryActivity;



/**
 * 贵州沃受理app集成微信转账
 * @author yangdong
 *
 */
public class WeiXinInterfacePlugin extends CordovaPlugin {


    public static final String TAG = "WeiXinInterfacePlugin";
    public static final String PREFS_NAME = "weiXinInterfacePlugin";
    public static final String WXAPPID_PROPERTY_KEY = "wxAppId";
    public static final String WXAPPSECRET_PROPERTY_KEY = "wxAppSecret";

    public static CallbackContext callbackContext; //cordova调用上下文
    public static Activity activity;
    protected static IWXAPI wxAPI;//定义微信api
// protected static String appId;//定义微信的appId
// protected static String appSerect;//定义微信的appId


    // @Override
    // protected void pluginInitialize() {

    // super.pluginInitialize();
    // Log.d(TAG, "plugin initialized.");
    // }


    @Override
    public boolean execute(String action, JSONArray args,
                           CallbackContext callbackContext) throws JSONException {

        Log.d(TAG,"execute");
                       
        this.callbackContext = callbackContext;
        this.activity = this.cordova.getActivity();

        //根据前台需要调用的接口,走不同的分支处理,调用相对应的微信接口
        if (action.equals("registerWeiXin")) {
            Log.d("registerWeiXin exe...", "registerWeiXin");
            JSONObject params = args.getJSONObject(0); // 获取json对象参数
            Log.d("PortalPlugin param is", params.toString());
            //注册微信appId
            registerWeiXin(params);
        }else if(action.equals("isWXAppInstalled")){
            Log.d("isWXAppInstalled exe...", "isWXAppInstalled");
            isWXAppInstalled();
        }else if(action.equals("getAuthForWeiXin")){
            Log.d("getAuthForWeiXin exe...", "getAuthForWeiXin");
            JSONObject params = args.getJSONObject(0); // 获取json对象参数
            Log.d("PortalPlugin param is", params.toString());
            getAuthForWeiXin(params);
        }else if(action.equals("getWeiXinCode")){
            Log.d("getWeiXinCode exe...", "getWeiXinCode");
            getWeiXinCode();
        } else if (action.equals("getWeiXinOpenId")) {
            Log.d("getWeiXinOpenId exe...", "getWeiXinOpenId");
            JSONObject params = args.getJSONObject(0); // 获取json对象参数
            Log.d("PortalPlugin param is", params.toString());
            getWeiXinOpenId(params);
            Log.d("getWeiXinOpenId exe...", "getWeiXinOpenId");

        }

        return true;
    }

    /**
     * 微信注册
     * @param params
     * @throws JSONException
     */
    public void registerWeiXin(final JSONObject params) throws JSONException {
       //获取前台传入的appId
       String appid = params.getString("appId");
       //获取前台传入的appSecret
       String appSecret = params.getString("appSecret");
        //返回结果
       JSONObject resp = new JSONObject();
       //判断传入的值是否为空
       if((!appid.isEmpty())&&(!appSecret.isEmpty())){
           //保存微信appid、appSecret
           saveAppId(this.activity,WXAPPID_PROPERTY_KEY,appid);
           saveAppId(this.activity,WXAPPSECRET_PROPERTY_KEY,appSecret);
           //获取wxapi 对象
           IWXAPI wxapi = getWxAPI(this.activity);
          //发送注册微信appId请求
           if (wxapi != null) {
               //调用微信注册接口
               if(wxapi.registerApp(appid)){
                   //data节点对象
                   JSONObject data = new JSONObject();
                   data.put("isRegister","1");
                   data.put("appId",appid);
                   resp.put("data",data);
                   resp.put("respCode","0000");
                   resp.put("respDesc","微信注册成功");
               }else {
                   resp.put("respCode","0001");
                   resp.put("respDesc","微信注册失败");
               }
           }else {
               resp.put("respCode","0003");
               resp.put("respDesc","获取微信接口对象异常");
           }
       }else {
           resp.put("respCode","0002");
           resp.put("respDesc","获取参数失败");
       }
       //返回报文
       sendRespInfo(resp,this.callbackContext);
    }

    /**
     *校验是否安装了微信
     */
    public void isWXAppInstalled() {

        Log.d("isWXAppInstalled exe","isWXAppInstalled");
        //获取wxapi 对象
        IWXAPI wxapi = getWxAPI(this.activity);

        //调用微信检查是否安卓接口
        boolean isWXAppInstalled = wxapi.isWXAppInstalled();
        //返回校验结果
        PluginResult plugin = new PluginResult(PluginResult.Status.OK, isWXAppInstalled);
        this.callbackContext.sendPluginResult(plugin);
    }


    public void getAuthForWeiXin (final JSONObject params) throws JSONException {
        //获取wxapi 对象
        IWXAPI api = getWxAPI(this.activity);
        //返回结果
        JSONObject resp = new JSONObject();
        SendAuth.Req req = new SendAuth.Req();
        req.scope = params.getString("scope");
        req.state = params.getString("state");
        if(api.sendReq(req)){
            //返回data节点
            JSONObject data = new JSONObject();
            data.put("isSendAuthReq","1");
            resp.put("data",data);
            resp.put("respCode","0000");
            resp.put("respDesc","授权请求发送成功");
        }else {
            resp.put("respCode","0001");
            resp.put("respDesc","授权请求发送失败");
        }
        //返回报文
        sendRespInfo(resp,this.callbackContext);
    }

    /**
     * 返回请求授权 微信响应返回的code
     * @throws JSONException
     */
    public void getWeiXinCode () throws JSONException{
        //返回结果
        JSONObject resp = new JSONObject();
        if(!WXEntryActivity.code.isEmpty()){
            //返回data节点
            JSONObject data = new JSONObject();
            data.put("code",WXEntryActivity.code);
            resp.put("data",data);
            resp.put("respCode","0000");
            resp.put("respDesc","code获取成功");
        }else {
            resp.put("respCode","0001");
            resp.put("respDesc","code获取失败");
        }
        //返回报文
        sendRespInfo(resp,this.callbackContext);
    }

    /**
     * 获取openId
     */
    public void getWeiXinOpenId (final JSONObject params) throws JSONException{
        //初始化 x
        x.Ext.init(this.activity.getApplication());
        x.Ext.setDebug(BuildConfig.DEBUG); // 是否输出debug日志, 开启debug会影响性能.
        //获取传入的code
        String code = params.getString("code");
        //设置请求
        String urlStr = "https://api.weixin.qq.com/sns/oauth2/access_token";
        //设置请求参数
        RequestParams reqParams = new RequestParams(urlStr);
        reqParams.addQueryStringParameter("code",code);
        reqParams.addQueryStringParameter("appId",getSavedAppId(this.activity,WXAPPID_PROPERTY_KEY));
        reqParams.addQueryStringParameter("secret",getSavedAppId(this.activity,WXAPPSECRET_PROPERTY_KEY));
        reqParams.addQueryStringParameter("grant_type","authorization_code");

        LOG.d(TAG,"appId--->"+getSavedAppId(this.activity,WXAPPID_PROPERTY_KEY));
        LOG.d(TAG,"secret--->"+getSavedAppId(this.activity,WXAPPSECRET_PROPERTY_KEY));
        LOG.d(TAG,"url"+reqParams.getUri());

        //以get方式发送请求
        x.http().get(reqParams, new Callback.CommonCallback<JSONObject>() {
            //返回结果
            JSONObject resp = new JSONObject();
            @Override
            public void onSuccess(JSONObject result) {
                
                try {
                    JSONObject data = new JSONObject();
                    data.put("access_token",result.getString("access_token"));
                    data.put("openid",result.getString("openid"));
                    resp.put("data",data);
                    resp.put("respCode","0000");
                    resp.put("respDesc","授权登录请求成功");
                }catch (Exception e){
                    LOG.d("getWeiXinOpenId返回异常",e.getMessage());
                }
                //返回报文
                sendRespInfo(resp,WeiXinInterfacePlugin.callbackContext);
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                try {
                    resp.put("respCode","0001");
                    resp.put("respDesc","授权登录请求失败"+ex.getMessage());
                    //返回报文
                    sendRespInfo(resp,WeiXinInterfacePlugin.callbackContext);
                }catch (Exception e){
                    LOG.d("getWeiXinOpenId返回异常",e.getMessage());
                }
            }

            @Override
            public void onFinished() {

            }
        });


    }


    /**
     * 获取微信wxAPI 对象
     * @param ctx
     * @return
     */
    public IWXAPI getWxAPI(Context ctx) {
        if (wxAPI == null) {
            String appId = getSavedAppId(ctx,WXAPPID_PROPERTY_KEY);
            if (!appId.isEmpty()) {
                wxAPI = WXAPIFactory.createWXAPI(ctx, appId, true);
            }
        }
        return wxAPI;
    }

    /**
     * 从SharedPreferences中获取appid
     * @param ctx
     * @return
     */
    public String getSavedAppId(Context ctx,String key) {
        SharedPreferences settings = ctx.getSharedPreferences(PREFS_NAME, ctx.MODE_PRIVATE);
        return settings.getString(key, "");
    }


    /**
     * 将传入的微信appId、appSerect保存进SharedPreferences中
     * @param ctx
     * @param value
     */
    public void saveAppId(Context ctx, String key,String value) {
        if (value.isEmpty()) {
            return ;
        }
        SharedPreferences settings = ctx.getSharedPreferences(PREFS_NAME, ctx.MODE_PRIVATE);
        SharedPreferences.Editor editor = settings.edit();
        editor.putString(key, value);
        editor.commit();
    }



    /**
     * 返回消息给前端,这边全都算做success,只是通过respCode来区分是否成功
     * 返回的是json字符串,跟ios统一
     * @param resp
     * @param callbackContext
     */
    private void sendRespInfo(JSONObject resp, CallbackContext callbackContext){
        String message = resp.toString(); //json转换成字符串
        Log.d("WeiXinInterfacePlugin", "sendRespInfo......" + message);

        //为了一次调用能多次返回结果给前端,得用下面的方式返回结果,
        //PluginResult plugin = new PluginResult(PluginResult.Status.OK, message);
        PluginResult plugin = new PluginResult(PluginResult.Status.OK, resp);
        plugin.setKeepCallback(true);
        callbackContext.sendPluginResult(plugin);
    }
}
  • 用于处理微信回调的消息
java
package com.ai.wsl.gz.wxapi;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;

import com.tencent.mm.opensdk.constants.ConstantsAPI;
import com.tencent.mm.opensdk.modelbase.BaseReq;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler;

import org.apache.cordova.CallbackContext;


import com.ai.ced.weixin.WeiXinInterfacePlugin;
public class WXEntryActivity extends Activity implements IWXAPIEventHandler {

    private WeiXinInterfacePlugin weiXinInterfacePlugin;

    public static String code = "";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        weiXinInterfacePlugin = new WeiXinInterfacePlugin();

        IWXAPI api = weiXinInterfacePlugin.getWxAPI(this);

        if (api == null) {
            startMainActivity();
        } else {
            api.handleIntent(getIntent(), this);
        }
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);

        setIntent(intent);

        IWXAPI api = weiXinInterfacePlugin.getWxAPI(this);
        if (api == null) {
            startMainActivity();
        } else {
            api.handleIntent(intent, this);
        }

    }

    @Override
    public void onResp(BaseResp resp) {
        Log.d("onResp exe", resp.toString());

        CallbackContext ctx = WeiXinInterfacePlugin.callbackContext;

        if (ctx == null) {
            startMainActivity();
            return ;
        }

        switch (resp.errCode) {
            case BaseResp.ErrCode.ERR_OK:
                switch (resp.getType()) {
                    case ConstantsAPI.COMMAND_SENDAUTH:
                        SendAuth.Resp res = ((SendAuth.Resp) resp);
                        code = res.code;
                        break;
                    default:
                        ctx.success();
                        break;
                }
                break;
        }

        // restore appid
// final String appid = weiXinInterfacePlugin.getSavedAppId(this,WeiXinInterfacePlugin.WXAPPID_PROPERTY_KEY);
// final String savedAppId = weiXinInterfacePlugin.getSavedAppId(this,);
// if (!savedAppId.equals(appid)) {
// weiXinInterfacePlugin.saveAppId(this, weiXinInterfacePlugin.getAppId());
// }

        finish();
    }

    @Override
    public void onReq(BaseReq req) {
        finish();
    }

    protected void startMainActivity() {
        Intent intent = new Intent();
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setPackage(getApplicationContext().getPackageName());
        getApplicationContext().startActivity(intent);
    }
    
}

Released under the MIT License.