CocosCeator 微信登录实现

let http = require("HTTP.IO");
let common = require("Common");
cc.Class({
    extends: cc.Component,

    properties: {
        progressBar: {
            default: null,
            type: cc.ProgressBar
        },
        label_progress: {
            default: null,
            type: cc.Label
        },
        progress: 0,
        completeCount: 0,
        totalCount: 0,
        resource: null
    },

    // LIFE-CYCLE CALLBACKS:

    onLoad() {
        let _this = this;
        wx.getUserInfo({
            success: function (res) {
                var userInfo = res.userInfo;
                if ("getUserInfo:ok" == res.errMsg) {
                    _this.login(userInfo.nickName,userInfo.avatarUrl,1,'','')
                }else{
                    _this.addBtn()  
                }
            },
            fail: function () {
                _this.addBtn()
            }
        })
        
    },
    /** 
     * name 用户名称
     * photo 用户头像
     * types 0抖音1微信
     * openid 抖音必须传
     * inviter 邀请人u_id 
     */
    // 登录
    login(name, photo, types, openid, inviter){
        let _this = this;
        wx.login({
            success (res) {
                console.log(res)
                if (res.code) {
                  //发起网络请求
                  http.login(res.code,name, photo, types, openid, inviter,function(msg){
                    if(msg.error==1){
                        common.playerData = msg.data;
                        console.log("loading==>" + common.playerData);
                            
                        _this.progressBar.node.active = true;
                        _this.label_progress.node.active = true;
                        _this.progressBar.progress = 0;
                        cc.loader.loadResDir("/", _this.progressCallback.bind(_this), _this.completeCallback.bind(_this));
                    }
                  })
                } else {
                  console.log('登录失败!' + res.errMsg)
                }
              }
        })
    },
    // 创建授权按钮
    addBtn() {
        let _this = this;
        var button = wx.createUserInfoButton({
            type: "text",
            text: "\u83b7\u53d6\u7528\u6237\u4fe1\u606f",
            style: {
                left: (wx.getSystemInfoSync().screenWidth - 200) / 2,
                top: (wx.getSystemInfoSync().screenHeight - 40) / 2,
                width: 200,
                height: 40,
                lineHeight: 40,
                backgroundColor: "#ff0000",
                color: "#ffffff",
                textAlign: "center",
                fontSize: 16,
                borderRadius: 4
            }
        });
        button.onTap(function (res) {
            console.log(res);
            if ("getUserInfo:ok" == res.errMsg) {
                let userInfo = res.userInfo;
                button.destroy();
                _this.login(userInfo.nickName,userInfo.avatarUrl,1,'','')
            } else {
                wx.showToast({
                    title: "先授权,然后继续游戏"
                });
            }
        });
    },
    // 加载进度回调
    progressCallback(completeCount, totalCount, res) {
        this.progress = completeCount / totalCount;
        this.resource = res;
        this.completeCount = completeCount;
        this.totalCount = totalCount;
    },
    // 加载完成回调
    completeCallback(errors, assetRes, urlRes) {
        // console.log("LoadingScene.completeCallback==>");
        // console.table(urlRes);
    },

    update(dt) {
        if (!this.resource) {
            return;
        }

        let progress = this.progressBar.progress;
        if (progress >= 1) {
            console.log("加载完成");
            // 加载完成
            this.progressBar.node.active = false;
            this.enabled = false;
            cc.director.loadScene("GameScene");
            return;
        }

        if (progress < this.progress) {
            progress += dt;
        }

        this.progressBar.progress = progress;

        let number_progress = Math.floor(progress * 100);
        if (number_progress >= 100) {
            number_progress = 100;
        }
        let str_progress = cc.js.formatStr("progress: %d", number_progress);
        this.label_progress.string = str_progress;
    }
});

HTTP.IO.js

HttpPost(url, params, callback) {

 

let xhr = cc.loader.getXMLHttpRequest();

// let xhr = new XMLHttpRequest();

xhr.open("POST", url, true);

// xhr.open("POST", url);

// xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

// xhr.setRequestHeader('Content-Type', 'multipart/form-data');

// xhr.setRequestHeader('Content-Type', 'application/octet-stream');

let cookie = wx.getStorageSync('cookieKey');

xhr.setRequestHeader('Content-Type','application/json');

if(cookie){

xhr.setRequestHeader('Cookie',cookie);

}

let self = this;

xhr.onreadystatechange = function () {

// cc.log("xhr.responseText" + xhr.responseText);

// HttpManage.SetHintInfo("xhr.responseText === "+xhr.responseText);

if (xhr.readyState == 4 && (xhr.status >= 200 && xhr.status < 400)) {

let resultjson = JSON.parse(xhr.responseText);

callback(resultjson);

}

};

xhr.send(params);

},

 

//-----------------------------------------------------------------------

// 登录模块

//-----------------------------------------------------------------------

// 登录接口

login(code, name, photo, types, openid, inviter, callBack) {

let params={

code:code,

name:name,

photo:photo,

types:types,

openid:openid,

inviter:inviter

};

let url = this._url + "/user/user_login";

// this.HttpPost(url, params, function (resultjson) {

// cc.log("resultjson==>" + JSON.stringify(resultjson));

// if (callBack) {

// callBack(resultjson);

// }

// });

wx.request({

url: url,

method: 'POST',

header: { 'content-type': 'application/json' },

data: params,

success: function (res) {

callBack && callBack(res.data);

if (res && res.header && res.header['Set-Cookie']) {

wx.setStorage({key:'cookieKey', data:res.header['Set-Cookie']});//保存Cookie到Storage

}

}

})

},

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

VCHH

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值