Egret白鹭开发微信小游戏分享功能

今天给大家分享一下微信被动转发功能,话不多说,直接干

1.在egret中打开Platfrom.ts文件,添加代码如下(当然,你也可以直接复制粘贴)

/** 
 * 平台数据接口。
 * 由于每款游戏通常需要发布到多个平台上,所以提取出一个统一的接口用于开发者获取平台数据信息
 * 推荐开发者通过这种方式封装平台逻辑,以保证整体结构的稳定
 * 由于不同平台的接口形式各有不同,白鹭推荐开发者将所有接口封装为基于 Promise 的异步形式
 */
declare interface Platform {

    getUserInfo(): Promise<any>;

    login(): Promise<any>;
        //转发菜单
    showShareMenu(): Promise<any>;

}

class DebugPlatform implements Platform {
    async getUserInfo() {
        return { nickName: "username" }
    }
    async login() {
    }
        //被动分享
    async showShareMenu() {
    }
    
}
if (!window.platform) {
    window.platform = new DebugPlatform();
}
declare let platform: Platform;

declare interface Window {

    platform: Platform
}

2.在Main.ts中调用Platfrom.ts新增加的方法

    private async runGame() {
        await this.loadResource()
        this.createGameScene();
        // const result = await RES.getResAsync("description_json")
        // this.startAnimation(result);
        await platform.login();
        const userInfo = await platform.getUserInfo();
        console.log(userInfo);
        await platform.showShareMenu();
    }

 3.打包成微信小游戏

4.使用微信开发者工具打开微信小游戏项目,打开platfrom.js,添加代码

 showShareMenu() {
    return new Promise((resolve, reject) => {
      wx.showShareMenu({
        withShareTicket: true
      })
      wx.onShareAppMessage(function () {
        return {
          title: '好东西要一起分享',
          imageUrl: "resource/assets/logo.png"
        }
      })
    })
  }

参数可根据实际情况写。

其他分享API同理,API及参数详见https://developers.weixin.qq.com/minigame/dev/document/share/wx.getShareInfo.html

platform.js主动分享代码:

  shareAppMessage() {
    return new Promise((resolve, reject) => {

      wx.shareAppMessage(function() {
        return {
          title: '主动分享',
          imageUrl: "resource/assets/egret_icon.png",
          query: ""
        }
      })
    })
  }

注意:主动分享功能可能在微信开发工具上不体现,因此,博主建议在手机上预览。

下面介绍一个主动分享成功后显示传入参数的方法

在打开微信开发工具,在game.js中添加代码如下:

wx.showShareMenu({
  withShareTicket: true
})
wx.onShareAppMessage(function () {
  return {
    title: '被动分享',
    imageUrl: "resource/assets/bg.jpg",
    query: 'a=7&b=8',
    success: (res) => {
      console.log("转发成功", res);
    },
    fail: (res) => {
      console.log("转发失败", res)
    },
  }
})
wx.onShow((option) => {
  console.log(option);
})

 在手机上预览,进行被动转发,从分享链接打开分享的小游戏,在控制台可以查看到传入的参数如下:

猜你喜欢

转载自www.cnblogs.com/shirln/p/9413234.html