Cocos Creator2D游戏开发(12)-飞机大战(10)---调用微信小游戏API

现在为止,小游戏已经发布体验版了; 但是小游戏是小游戏,微信是微信; 怎么把这俩货关联在一起,这是一个问题;
我是一个javaer,小游戏这个算是跨行; 所以我只能去抄;

微信和小游戏关联起来的第一步: 小游戏登陆
要实现的功能是: 微信小游戏自动获取到openId(使用code换取微信openId)
官方说法: 小程序可以通过微信官方提供的登录能力方便地获取微信提供的用户身份标识,快速建立小程序内的用户体系
微信前端文档: https://developers.weixin.qq.com/minigame/dev/api/open-api/login/wx.login.html
微信服务端文档: https://developers.weixin.qq.com/minigame/dev/api-backend/open-api/login/auth.code2Session.html

服务端: 代码如下(这个要布置成后台服务: 同时还要弄成https)

    public JSONObject getVxInfoBycode(String code) {
        String appid = "AppID(小程序ID)";
        String appSecret = "AppSecret(小程序密钥)";
        Map<String, Object> params = Maps.newHashMap();
        params.put("appid", appid);
        params.put("secret", appSecret);
        params.put("js_code", code);
        params.put("grant_type", "authorization_code");
        String response = HttpUtils.get("https://api.weixin.qq.com/sns/jscode2session", params);
        JSONObject jsonObject = JSONObject.parseObject(response);
        Integer errCode = jsonObject.getInteger("errcode");
        if (Objects.isNull(errCode)) {
            return jsonObject;  // 返回openId时 没有errCode 
        } else {
            throw new ResultException("微信code过期" + errCode);
        }
    }

我在网上找了好久,没找到我想要的, 一度怀疑我是废物:
后来在b站找到了这个【CocosCreator调用微信小游戏的API】 https://www.bilibili.com/video/BV1xz4y1H7ve/?share_source=copy_web&vd_source=c145fb6738cac12bc70d254f2f567948
发现可以实现我想要的了;

1: 安装npm 下载 npm install minigame-api-typings
下载完之后出现了node_modules
在这里插入图片描述
2 在node_modules中创建@types 将 minigame-api-typings文件夹复制一份放入@types中
在这里插入图片描述
3. 在需要调用微信小游戏api的地方 引入 import “minigame-api-typings”
我把它放在 重试按钮下的脚本中
在这里插入图片描述
ButtonRetry.ts 代码如下

import { _decorator, Component, director, Node } from 'cc';
const { ccclass, property } = _decorator;
import "minigame-api-typings"

@ccclass('ButtonRetry')
export class ButtonRetry extends Component {

    start() {

    }

    update(deltaTime: number) {
        
    }

    // 跳转到主场景
    gotoMainScene() {
        director.loadScene("main_scene");
        console.log("获取登陆信息")
        this.login();
    }

    login(){
        wx.login({
            success (res) {
              if (res.code) {
                //发起网络请求
                wx.request({
                  url:  'https://你自己的服务端路径',
                  data: {
                    code: res.code
                  }
                })
              } else {
                console.log('登录失败!' + res.errMsg)
              }
            }
          })
    }
}



  1. 在构建发布中构建, 构建之后在微信小程序开发工具中打开
    在这里插入图片描述
  2. 不校验https
    在这里插入图片描述
  3. 微信小游戏 编译 预览 等出现重试按钮,点击 然后就能看到微信小游戏调用接口了
    在这里插入图片描述
  • 5
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值