cocos creator android studio 实现游戏微信登录功能(官方接入方式)

一:cocos creator端js调用java代码实现微信登录功能:JS部分

 废话不多说直接上代码:

wechatLogin : function(){
        jsb.reflection.callStaticMethod("org/cocos2dx/javascript/AppActivity", "wxLogin", "()V");//调用java代码进行微信登录
        this.getAccessTokenByCode();    //根据java返回的code获得accessToken
    },
    //获取微信登录所必须的code
    getWechatCode : function(){
        var self = this;
        var isGetCode;
        var code;
        //发送获得code的请求
        return new Promise(function(resolve,reject){
            console.log("进入Promise");
            self.schedule(function(){    //java端微信请求是有延迟的在这里我们等待获取code的状态为true的时候在获取code
                isGetCode = jsb.reflection.callStaticMethod("org/cocos2dx/javascript/AppActivity", "getCodeSuccess", "()Z");
                console.log("isGetCode is " ,isGetCode);
                if(isGetCode){
                    console.log("------------>",isGetCode);
                    //取消所有计时器
                    self.unscheduleAllCallbacks();
                    //如果获得code证明是成功获得微信的响应
                    code = jsb.reflection.callStaticMethod("org/cocos2dx/javascript/AppActivity", "getCode", "()Ljava/lang/String;");
                    console.log("==============>>code is " + code);
                    resolve(code);
                }
            }.bind(self),0.5);
        });
    },
    getAccessTokenByCode : function(){
        var self = this;
        this.getWechatCode().then(function(code){ //获取微信code的承诺返回了正常的结果
            console.log("已经获得code");
            console.log("in AccessTokenByCode " + code);
            self.getAccessToken(code);
        });
    },
    getAccessToken : function(code){        //获取accessToken
        var url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=自己的appId&secret=自己的appId秘钥&code=" + code + "&grant_type=authorization_code";
        var self = this;
        var xhr = new XMLHttpRequest();
        xhr.onreadystatechange = function(){
            if (xhr.readyState == 4 && (xhr.status >= 200 && xhr.status < 400)) {
                var response = xhr.responseText;
                console.log("response===>>>",response);
                var msg = JSON.parse(response);
                var access_token = msg.access_token;
                var refresh_token = msg.refresh_token;
                var openid = msg.openid;
                //如果超时进行重新刷新accessToken
                if(msg.expires_in >= 7200){
                    //刷新accesstoken
                    self.freshAccessToken(refresh_token).then(function(data){
                       console.log("刷新accessToken 是",data);
                       access_token = data;
                       self.getUserInfo(access_token,openid);
                       cc.director.loadScene("helloworld");
                    });
                    console.log("这个accessToken是刷新出来的token",access_token);
                }else{
                    self.getUserInfo(access_token,openid);
                    cc.director.loadScene("helloworld");
                }
                
            }
        };
        xhr.open("GET",url,true);
        xhr.send();
    },
    getUserInfo : function(access_token,openid){       //获取用户信息
        console.log("accessToken is " + access_token);
        console.log("openid is " + openid);
        var url = "https://api.weixin.qq.com/sns/userinfo?access_token="+access_token + "&openid="+openid;
        var self = this;
        var xhr = new XMLHttpRequest();
        xhr.onreadystatechange = function(){
            if (xhr.readyState == 4 && (xhr.status >= 200 && xhr.status < 400)) {
                var response = xhr.responseText;
                console.log("response===>>>",response);
                var msg = JSON.parse(response);
                console.log("msg is " , msg);
                console.log("nickName is " + msg.nickname);
                console.log("city is " + msg.city);
                console.log("country " + msg.country);
                console.log("sex is  " + msg.sex);
            }
        };
        xhr.open("GET",url,true);
        xhr.send();

    },
    freshAccessToken : function(refresh_token){
        var url = "https://api.weixin.qq.com/sns/oauth2/refresh_token?appid=自己的appId&grant_type=refresh_token&refresh_token="+refresh_token;
        var self = this;
        var xhr = new XMLHttpRequest();
        var ac;
        return new Promise(function(resolve,reject){
            xhr.onreadystatechange = function(){
                if (xhr.readyState == 4 && (xhr.status >= 200 && xhr.status < 400)) {
                    var response = xhr.responseText;
                    console.log("response===>>>",response);
                    var msg = JSON.parse(response);
                    ac = msg.access_token;
                    console.log("ac is " + ac);
                    resolve(ac);
                }
            };
            xhr.open("GET",url,true);
            xhr.send();
        });
        
    },

二:java代码部分:集成微信第三方jar包

  1:打开android-studio工程,在project项目目录下找到app下的build-gradle在添加如下的依赖

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    compile project(':libcocos2dx')
    compile 'com.sina.weibo.sdk:core:2.0.3:openDefaultRelease@aar'
    compile 'com.tencent.mm.opensdk:wechat-sdk-android-with-mta:+'   //微信登录所需要的jar包
    implementation files('libs/android-support-v4.jar')
    implementation files('libs/open_sdk_r5990_lite.jar')
}

然后重新编译:

2:在AndroidManifest.xml添加如下的activity

<activity android:name="org.cocos2d.helloworld.wxapi.WXEntryActivity"
    android:label="@string/app_name"
    android:exported="true">

3:添加package WXEntryActivity的包名必须跟你应用的包名一致如我应用的包名是org.cocos2d.helloworld那么该类的包名就是org.cocos2d.helloworld.wxapi这个一定不能错

4:新建WXEntryActivity类:

public class WXEntryActivity extends Activity implements IWXAPIEventHandler{
    private static final String app_id = "自己的appId";
    //微信appId
    private IWXAPI api;
    //微信发送的请求将回调该方法
    private void regToWx(){
        api = WXAPIFactory.createWXAPI(this,app_id,true);
        api.registerApp(app_id);
        System.out.println("###############");
        System.out.println("In wxEntryActivity api is " + api);
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        System.out.println("enter the wxEntryActivity");
        regToWx();
        //这句话很关键
        try {
            api.handleIntent(getIntent(), this);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        System.out.println("intent is " + intent);
        setIntent(intent);
        api.handleIntent(intent, this);
    }
    @Override
    public void onReq(BaseReq baseReq) {

    }
    //向微信发送的请求的响应信息回调该方法
    @Override
    public void onResp(BaseResp baseResp) {
        System.out.println("Enter the onResp");
        System.out.println("api is " + api);
        if(baseResp.errCode == BaseResp.ErrCode.ERR_OK){
            String code = ((SendAuth.Resp) baseResp).code;
            System.out.println("==========code is ==========="+code);
            AppActivity.code = code;
            AppActivity.isGetCode = true;
        }
    }
}

5:接下来写AppActivity:

public class AppActivity extends Cocos2dxActivity {
    //微信appId
    private static String appId = "自己的appId";
    public static AppActivity app;
    public static IWXAPI api;
    //微信登录所必须的code
    public static String code;
    //是否获得code
    public static boolean isGetCode = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // Workaround in https://stackoverflow.com/questions/16283079/re-launch-of-activity-on-home-button-but-only-the-first-time/16447508
        if (!isTaskRoot()) {
            // Android launched another instance of the root activity into an existing task
            //  so just quietly finish and go away, dropping the user back into the activity
            //  at the top of the stack (ie: the last state of this task)
            // Don't need to finish it again since it's finished in super.onCreate .
            return;
        }
        // DO OTHER INITIALIZATION BELOW

        SDKWrapper.getInstance().init(this);
        //初始化api
        api = WXAPIFactory.createWXAPI(this,appId);
        //将应用的appid注册到微信
        api.registerApp(appId);
    }

6:微信登录方法:

//获取微信登录第一步的code
    public static void requestCode(){
        final SendAuth.Req req = new SendAuth.Req();
        req.scope = "snsapi_userinfo";
        req.state = "wechat_sdk_demo_test";
        System.out.println("req is " + req);
        //利用微信api发送请求
        api.sendReq(req);
        System.out.println("发送请求完毕");
        System.out.println("In AppActivity api is " + api);

    }
    public static boolean getCodeSuccess(){       //js端一直检测该值直到该值为true
        System.out.println("isGetCode is " + isGetCode);
        return isGetCode;
    }
    public static String getCode(){
        System.out.println("code is " + code);
        return code;
    }
    //微信登录接口
    public static void wxLogin(){
        System.out.println("Enter the wxLogin");
        requestCode();      //向微信服务器请求code
    }
至此微信登录集成完毕。如有错误欢迎小伙伴指正谢谢!

猜你喜欢

转载自blog.csdn.net/lck8989/article/details/80957199