// ***********************************************************************
// Assembly : Game
// Author : Kimch
// Created : 2021-05-02
// Description :
// Last Modified By :
// Last Modified On :
// ***********************************************************************
//
//
// ***********************************************************************
#if SDK_WECHAT_WASM
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using WeChatWASM;
using WXAccountInfo = WeChatWASM.AccountInfo;
using WXSystemInfo = WeChatWASM.SystemInfo;
namespace G
{
///
///
///
partial class KPlatform
{
///
/// 平台实现
///
public class WechatPlatform : MonoBehaviour, IPlatformWapper
{
#region 初始化
private void Start()
{
this.name = "wechat";
this.Init();
}
///
/// 游戏SDK初始化,仅Android端
/// Init for Android client ios.
///
public void Init()
{
// 打印当前sdk版本号
WX.InitSDK(OnInitCallback);
}
private void OnInitCallback(int code)
{
GetSystemInfo();
GetAccountInfo();
KPlatform.Instance.OnInitSuccess();
var launchResponse = WX.GetLaunchOptionsSync();
if (launchResponse != null)
OnLaunch(launchResponse);
WX.OnShow(this.OnShow);
WX.OnHide(this.OnHide);
WX.SetKeepScreenOn(new SetKeepScreenOnOption
{
keepScreenOn = true,
});
//if (envVersion == "develop")
// WX.OpenProfileStats();
}
WXSystemInfo _wxSystemInfo;
void GetSystemInfo()
{
_wxSystemInfo = WX.GetSystemInfoSync();
}
WXAccountInfo _wxAccountInfo;
void GetAccountInfo()
{
_wxAccountInfo = WX.GetAccountInfoSync();
}
void OnLaunch(LaunchOptionsGame option)
{
var rawData = option.query;
CheckShare(rawData);
}
void OnShow(OnShowCallbackResult showResponse)
{
var rawData = showResponse.query;
CheckShare(rawData);
CheckPayiOS(rawData, showResponse.referrerInfo);
KPlatform.Instance.OnApplicationFocus(true);
}
void OnHide(GeneralCallbackResult result)
{
KPlatform.Instance.OnApplicationFocus(false);
}
void CheckShare(Dictionary rawData)
{
if (rawData != null /*&& !string.IsNullOrEmpty(rawData)*/)
{
var inviteInfo = new InviteInfo();// JsonUtility.FromJson(rawData);
//inviteInfo.userId = rawData["userId"];
rawData.TryGetValue("userId", out inviteInfo.userId);
rawData.TryGetValue("type", out inviteInfo.type);
if (inviteInfo != null && !string.IsNullOrEmpty(inviteInfo.userId))
{
KPlatform.Instance.inviteInfo = inviteInfo;
//Debug.Log("inviter " + inviteInfo.userId);
}
else
{
//Debug.Log("queryRaw " + rawData);
}
}
this.OnShare(0, "分享成功");
}
void CheckPayiOS(Dictionary query, ResultReferrerInfo from)
{
if (query != null)
{
}
if (from != null)
{
Debug.Log(from.appId);
if (from.extraData != null)
foreach (var item in from.extraData)
{
Debug.Log(item.Key + " " + item.Value);
}
}
CheckPay();
}
#endregion
#region 系统信息
///
///
///
public string appId
{
get { return _wxAccountInfo != null ? _wxAccountInfo.miniProgram.appId : null; }
}
///
///
///
public string envVersion
{
get { return _wxAccountInfo != null ? _wxAccountInfo.miniProgram.envVersion : null; }
}
///
///
///
public string version
{
get { return _wxSystemInfo != null ? _wxSystemInfo.version : "0.0.0"; }
}
///
///
///
public string platform
{
get { return _wxSystemInfo != null ? _wxSystemInfo.platform : ""; }
}
public bool iOSPlatform
{
get { return platform == "ios"; }
}
///
///
///
public int safeAreaTop
{
get
{
var safeArea = _wxSystemInfo.safeArea;
return (int)safeArea.top;
}
}
///
///
///
public int benchmarkLevel
{
get { return _wxSystemInfo != null ? (int)_wxSystemInfo.benchmarkLevel : 18; }
}
#endregion
#region 登录
///
/// 正式用户调用登录接口.
///
public void NormalLogin()
{
LoginOption option = new LoginOption
{
success = OnLoginSuccess,
fail = OnLoginFailure,
timeout = 6000,
};
//Debug.Log("Wx Login 1");
try
{
WX.Login(option);
}
catch (Exception ex)
{
Debug.Log("Wx Login ex " + ex.Message);
}
//Debug.Log("Wx Login 2");
}
///
/// 帐号切换.
///
public void SwitchAccount()
{
}
///
/// 游客帐号绑定.
///
public void VisitorBindAccount()
{
}
///
/// 是否为游客登录.
///
/// 是否为游客登录.
public bool IsVisitor()
{
return false;
}
public void ClearToken()
{
}
///
///
///
///
private void OnLoginSuccess(LoginSuccessCallbackResult response)
{
//Debug.Log("Wx LoginSuccess " + response.code + " " + response.errMsg);
try
{
KPlatform.Instance.OnLoginSuccess(response.code, "", 1, 1);
}
catch (Exception ex)
{
Debug.Log("Wx LoginSuccess" + ex.Message);
}
}
private void OnLoginFailure(GeneralCallbackResult response)
{
//Debug.Log("Wx OnLoginFailure " + response.errMsg);
try
{
KPlatform.Instance.OnLoginFailure(1, response.errMsg, 1);
}
catch (Exception ex)
{
Debug.Log("Wx OnLoginFailure" + ex.Message);
}
}
Callback2 _getUserInfoCallback;
public void GetUserNickName(Callback2 callback)
{
_getUserInfoCallback = callback;
AuthorizeOption option = new AuthorizeOption
{
scope = "scope.userInfo",
success = (authorizeResponse) => GetUserInfo(),
fail = (authorizeResponse) => ShowGetUserInfoButton(),
};
WX.Authorize(option);
}
void GetUserInfo()
{
GetUserInfoOption option = new GetUserInfoOption
{
lang = "zh_CN",
success = (getUserInfoResponse) =>
{
//Debug.Log("GetUserInfo result " + getUserInfoResponse.errCode + " " + getUserInfoResponse.errMsg);
PlayerProxy.Instance.socialAvatarUrl = getUserInfoResponse.userInfo.avatarUrl;
PlayerProxy.Instance.socialNickName = getUserInfoResponse.userInfo.nickName;
PlayerProxy.Instance.nickName = PlayerProxy.Instance.socialNickName;
GlobalNotifier.PostNotification(GlobalDefine.EVENT_NAME_CHANGED);
_getUserInfoCallback?.Invoke(0, getUserInfoResponse.errMsg);
},
fail = (getUserInfoResponse) =>
{ _getUserInfoCallback?.Invoke(0, getUserInfoResponse.errMsg); }
};
WX.GetUserInfo(option);
}
public void ShowGetUserInfoButton()
{
var btn = WX.CreateUserInfoButton(0, 0, Screen.width, Screen.height, "zh_CN", true);
btn.Show();
btn.OnTap((response) =>
{
//Debug.Log("CreateUserInfoButton result " + response.errCode + " " + response.errMsg);
if (response.errCode == 0)
{
GetUserInfo();
btn.Destroy();
}
});
}
#endregion
#region 广告
WXRewardedVideoAd _wxAd;
public void LoadRewardVideoAd_V()
{
if (_wxAd == null)
{
_wxAd = WX.CreateRewardedVideoAd(new WXCreateRewardedVideoAdParam
{
adUnitId = "adunit-ba92aa9eb2ae6720",
});
_wxAd.OnLoad(OnRewardAdLoad);
_wxAd.OnClose(OnRewardedAdClosed);
_wxAd.OnError(OnVideoError);
}
if (_wxAd != null)
_wxAd.Load();
}
public int ShowRewardAd(string scene)
{
_wxAd.Show(OnRewardAdShowSuccess, OnRewardAdShowFailure);
return 0;
}
public int ShowRewardAd(string branchId, string branchDim)
{
_wxAd.Show(branchId, branchDim, OnRewardAdShowSuccess, OnRewardAdShowFailure);
return 0;
}
private void OnRewardAdLoad()
{
Debug.Log("ad OnRewardAdLoad");
}
private void OnRewardAdShowSuccess(WXTextResponse response)
{
KPlatform.Instance.OnRewardedAdShow();
Debug.Log("ad OnRewardAdShowSuccess");
}
private void OnRewardAdShowFailure(WXTextResponse response)
{
_wxAd.Load();
Debug.Log("ad OnRewardAdShowFailure");
}
private void OnRewardedAdShow()
{
KPlatform.Instance.OnRewardedAdShow();
}
private void OnRewardClick()
{
KPlatform.Instance.OnRewardClick();
}
private void OnRewardedAdClosed(WXRewardedVideoAdOnCloseResponse response)
{
Debug.Log("ad OnRewardedAdClosed");
if (response.isEnded)
KPlatform.Instance.OnRewardVerify(true, 1f, "");
KPlatform.Instance.OnRewardedAdClosed();
_wxAd.Load();
}
private void OnVideoError(WXADErrorResponse response)
{
Debug.Log("ad OnVideoError");
KPlatform.Instance.OnVideoError();
}
#endregion
#region 兑换码
//输入的兑换码
public void Redeem(string redeemCode)
{
}
#endregion
#region AB Test
[Serializable]
class ABConfig
{
public string expt_share;
}
///
/// 获取AB测试的配置
/// Gets the ab config.
///
/// The ab config.
/// Key.
/// Default value.
/// The 1st type parameter 类型,需是JSON兼容的数据类型.
public string GetAbConfig(string key, string defaultValue)
{
var result = WX.GetExptInfoSync(new string[] { key });
Debug.Log("GetAbConfig" + result);
return result.expt_share.ToString();
}
#endregion
#region 邮件
///
/// 获取邮件.
///
public void FetchMail()
{
}
///
/// 确认邮件.
///
/// 需要确认的邮件id.
public void AckMail(int[] mailIds)
{
}
#endregion
#region 支付
Callback2 _payCallback;
PayProxy.PayInfo _payInfo;
// 查询是否支持支付
public bool QueryPay()
{
if (!KRemoteConfig.Instance.supportPay)
return false;
if (iOSPlatform && !KRemoteConfig.Instance.supportPayiOS)
return false;
return true;
}
void CheckPay()
{
if (iOSPlatform)
{
if (_payCallback != null)
_payCallback(0, "ios");
_payCallback = null;
}
}
///
/// 支付
///
///
///
public void Pay(object payData, Callback2 callback)
{
_payCallback = callback;
var payInfo = payData as PayProxy.PayInfo;
if (iOSPlatform)
{
PayWithMiniApp(payInfo);
}
else
{
PayWithMidas(payInfo);
}
}
void PayWithMidas(PayProxy.PayInfo payInfo)
{
payInfo.payMethod = 0;
var payParam = new RequestMidasPaymentOption
{
env = 0,
currencyType = "CNY",
platform = "android",
mode = "game",
offerId = "1450031767",
buyQuantity = envVersion == "develop" ? 10 : payInfo.buyAmount,
zoneId = "1",
success = OnPayResultSuccess,
fail = OnPayResultFail
};
WX.RequestMidasPayment(payParam);
}
//void PayWithService(PayProxy.PayInfo payInfo)
//{
// string severAppId = "KHQiAUtB";
// if (envVersion == "develop")
// severAppId = "KHQiAUtB&dev=1";
// string payKey = payInfo.payKey;
// var param = new OpenCustomerServiceConversationOption
// {
// sessionFrom = $"{{\"receive_param\":\"{payKey}\",\"open_param\":\"{payKey}\",\"params\":\"uid={realPayInfo.userId}&gid={payKey}&aid={severAppId}&cb={ServerProxy.SERVER_URL + "/api/iospay/delivery"}\"}}",
// showMessageCard = true,
// sendMessageImg = "https://bingdu-kunpo.oss-cn-hangzhou.aliyuncs.com/sanguo/wxShare/other/rechargeTop.png",
// success = (response) =>
// {
// },
// fail = (response) =>
// {
// _payCallback?.Invoke(1, response.errMsg);
// }
// };
// WX.OpenCustomerServiceConversation(param);
//}
void PayWithMiniApp(PayProxy.PayInfo payInfo)
{
payInfo.payMethod = 1;
if (_iOSPayData == null)
{
_iOSPayData = new Dictionary
{
{ "goods_id","" },
{ "goods_price","" },
{ "goods_name","" },
{ "player_id","" },
{ "notify_path","" },
{ "kunpo_appsecret","146d03ddeb4cd2c87aa5ec8c11fa4648" },
{ "kunpo_appid","KHQiAUtB" },
{ "openid","" },
{ "out_trade_no","" },
{ "sandbox","" },
{ "extra","" },
};
}
var dict = _iOSPayData;
dict["openid"] = KPlatform.Instance.openId;
dict["out_trade_no"] = payInfo.trade_no;
dict["goods_id"] = payInfo.payKey;
dict["goods_price"] = (payInfo.buyAmount * 10).ToString();
dict["goods_name"] = payInfo.payName;
dict["player_id"] = payInfo.userId;
dict["notify_path"] = ServerProxy.SERVER_URL + "/api/iospay/delivery";
dict["sandbox"] = envVersion == "develop" ? "1" : "";
NavigateToMiniProgramOption navigateToMiniProgramOption = new NavigateToMiniProgramOption
{
appId = "wx5576c8e128f9902f",
path = "pages/pay/pay",
extraData = dict,
};
//if (envVersion == "develop")
// navigateToMiniProgramOption.envVersion = "trial";
WX.NavigateToMiniProgram(navigateToMiniProgramOption);
}
Dictionary _iOSPayData;
private void OnPayResultSuccess(GeneralCallbackResult result)
{
_payCallback?.Invoke(0, result.errMsg);
_payCallback = null;
}
private void OnPayResultFail(MidasPaymentError response)
{
_payCallback?.Invoke(1, response.errMsg);
_payCallback = null;
}
#endregion
#region 剪切板
public void SetClipboardData(string data)
{
var param = new SetClipboardDataOption
{
data = data
};
WX.SetClipboardData(param);
}
public void GetClipboardData(Callback3 callback)
{
var param = new GetClipboardDataOption
{
success = (response) =>
{
callback?.Invoke(0, "", response.data);
},
fail = (response) =>
{
callback?.Invoke(1, response.errMsg, null);
}
};
WX.GetClipboardData(param);
}
#endregion
#region 分享和跳转
Callback2 _shareCallback;
///
///
///
///
///
public void Share(ShareInfo shareInfo, Callback2 callback)
{
_shareCallback = callback;
ShareAppMessageOption shareParam = new ShareAppMessageOption();
shareParam.query = shareInfo.data;
shareParam.title = shareInfo.title;
shareParam.imageUrl = shareInfo.imgUrl;
if (!string.IsNullOrEmpty(shareParam.imageUrlId))
shareParam.imageUrlId = shareInfo.imgUrlId;
WX.ShareAppMessage(shareParam);
}
///
///
///
///
///
private void OnShare(int error, string message)
{
_shareCallback?.Invoke(0, message);
_shareCallback = null;
}
///
///
///
///
///
public void JumpToApp(string appId, object extraData)
{
NavigateToMiniProgramOption navigateToMiniProgramOption = new NavigateToMiniProgramOption
{
appId = appId,
};
//WXNavigateToMiniProgramParam param = new WXNavigateToMiniProgramParam
//{
// appId = appId,
// extraData = extraData,
//};
WX.NavigateToMiniProgram(navigateToMiniProgramOption);
}
#endregion
#region 交互
///
/// 显示 loading 提示框。需主动调用 wx.hideLoading 才能关闭提示框
///
///
/// 是否显示透明蒙层,防止触摸穿透
public void ShowLoading(string title, bool mask)
{
var param = new ShowLoadingOption()
{
title = title,
mask = mask,
};
WX.ShowLoading(param);
}
///
/// 隐藏 loading 提示框
///
public void HideLoading()
{
var param = new HideLoadingOption();
WX.HideLoading(param);
}
///
///
///
public void ShowToast()
{
var param = new ShowToastOption();
WX.ShowToast(param);
}
public void HideToast()
{
var param = new HideToastOption();
WX.HideToast(param);
}
public void ShowModal()
{
var param = new ShowModalOption();
WX.ShowModal(param);
}
public void CreateGameClubButton()
{
var param = new WXCreateGameClubButtonParam();
WX.CreateGameClubButton(param);
}
#endregion
#region 开放域数据
public void ShowOpenData(Texture texture, int x, int y, int w, int h)
{
WX.ShowOpenData(texture, x, y, w, h);
}
public void HideOpenData()
{
WX.HideOpenData();
}
public void SetUserCloudStorage(IDictionary kvData, Callback2 callback)
{
var param = new SetUserCloudStorageOption
{
success = (response) => callback?.Invoke(0, response.errMsg),
fail = (response) => callback?.Invoke(1, response.errMsg),
};
if (kvData != null)
{
param.KVDataList = new KVData[kvData.Count];
int i = 0;
foreach (var item in kvData)
{
param.KVDataList[i++] = new KVData { key = item.Key, value = item.Value };
}
}
WX.SetUserCloudStorage(param);
}
public void RemoveUserCloudStorage(ICollection keys, Callback2 callback)
{
var param = new RemoveUserCloudStorageOption
{
success = (response) => callback?.Invoke(0, response.errMsg),
fail = (response) => callback?.Invoke(1, response.errMsg),
};
if (keys != null)
{
param.keyList = new string[keys.Count];
int i = 0;
foreach (var item in keys)
{
param.keyList[i++] = item;
}
}
WX.RemoveUserCloudStorage(param);
}
#endregion
#region 振动
string[] _vibrateType = new string[]
{
"heavy",
"medium",
"light"
};
///
/// 震动强度类型,有效值为:heavy、medium、light
///
public void VibrateShort(int type)
{
VibrateShortOption option = new VibrateShortOption
{
type = _vibrateType[type],
};
WX.VibrateShort(option);
}
public void VibrateLong()
{
VibrateLongOption option = new VibrateLongOption
{
};
WX.VibrateLong(option);
}
#endregion
#region 声音
public void PreLoadMusic()
{
}
WXInnerAudioContext _lastMusicContext;
public void PlayMusic(string musicPath, float volume)
{
if (!WXInnerAudioContext.Dict.TryGetValue(musicPath, out var musicContext))
{
musicContext = WX.CreateInnerAudioContext(new InnerAudioContextParam()
{
src = musicPath,
volume = volume,
loop = true,
needDownload = true
});
}
if (_lastMusicContext != null)
{
_lastMusicContext.Stop();
_lastMusicContext = null;
}
musicContext.OnCanplay(() =>
{
musicContext.Play();
_lastMusicContext = musicContext;
});
}
public void PauseMusic(bool pause)
{
if (_lastMusicContext != null)
if (pause)
{
_lastMusicContext.Stop();
}
else
{
_lastMusicContext.Play();
}
}
public void PreLoadShortAudio(string[] audios)
{
WX.ShortAudioPlayer.PreLoadAudio(audios);
}
public void PlayShortAudio(string audio, float volume)
{
WX.ShortAudioPlayer.StopOthersAndPlay(audio, volume);
}
#endregion
#region 上报数据
///
///
///
///
///
public void SetEventCommonHeader(string key, string value)
{
}
///
/// 上报v3事件。
/// Ons the event v3.
///
/// Label. 事件名,应用内需唯一 .
/// Parameter. 事件参数 json .
public void ReportEvent(string label, string paramJson)
{
}
/// 用于分支相关的UI组件(一般是按钮)相关事件的上报,事件目前有曝光、点击两种
///
/// 分支ID,在「小程序管理后台」获取
/// 自定义维度
/// 事件类型,1:曝光; 2:点击
public void ReportUserBehaviorBranchAnalytics(string branchId, string branchDim, int eventType)
{
WX.ReportUserBehaviorBranchAnalytics(branchId, branchDim, eventType);
}
#endregion
#region 其它
public void OpenCustomerServiceConversation()
{
var param = new OpenCustomerServiceConversationOption
{
showMessageCard = false,
sendMessageTitle = "我是小客服oooooo",
sendMessageImg = "https://bingdu-kunpo.oss-cn-hangzhou.aliyuncs.com/sanguo/wxShare/other/rechargeTop.png",
complete = (response) =>
{
Debug.Log("客服 " + response.errMsg);
}
};
WX.OpenCustomerServiceConversation(param);
}
///
/// 应用内引导评分
///
public void InAppRating()
{
}
///
/// 验证敏感词.
///
/// 输入的敏感词信息.
/// 返回的敏感词结果.
public void VerifySensitiveWords(string sensitiveWords, System.Action verifyResult)
{
verifyResult?.Invoke(0);
}
///
/// 播放品牌特效.
///
/// 游戏是否竖屏,竖屏游戏填true,横屏游戏填false.
/// 品牌特效完成回调.
public void PlaySplashBrandEffect(bool portrait, System.Action splashBrandEffectAction)
{
//LightGameSDK.PlaySplashBrandEffect(portrait, splashBrandEffectAction);
}
///
/// openwebview
///
///
public void OpenWebView(string url)
{
Application.OpenURL(url);
}
public void Logoff(Action onSuccess, Action onFail)
{
}
public void OpenUserProtocol()
{
}
public void OpenPrivacyProtocol()
{
}
public void OpenIdentifyProtocol()
{
}
public void ClearCache()
{
if (WX.CleanAllFileCache())
{
WX.ExitMiniProgram(new ExitMiniProgramOption
{
success = reslut => { },
fail = result => { },
});
}
}
#endregion
}
}
}
#endif