NLDClient-yudde/ProjectNLD/Assets/Code/Scripts/Gameplay/IAP/WXPayHandle.cs

291 lines
9.4 KiB
C#
Raw Normal View History

2024-11-25 16:52:19 +08:00
using NLDPB;
2024-11-22 17:37:15 +08:00
using System;
2024-11-26 12:29:47 +08:00
using PhxhSDK;
2024-11-25 16:52:19 +08:00
using Gameplay;
using System.Text;
2024-11-22 17:37:15 +08:00
using UnityEngine;
2024-11-25 16:52:19 +08:00
using Gameplay.Net;
using Newtonsoft.Json;
using UnityEngine.Networking;
using Cysharp.Threading.Tasks;
using System.Collections.Generic;
using System.Text.RegularExpressions;
2024-11-22 17:37:15 +08:00
2024-11-26 12:29:47 +08:00
public class WXPayHandle : SingletonMono<WXPayHandle>
2024-11-22 17:37:15 +08:00
{
2024-11-26 12:29:47 +08:00
private static WXPayHandle _instance;
2024-11-28 13:04:45 +08:00
2024-11-26 12:29:47 +08:00
private void Awake()
{
if (_instance == null)
{
_instance = this;
InitWxPay();
2024-11-28 13:04:45 +08:00
DontDestroyOnLoad(gameObject);
2024-11-26 12:29:47 +08:00
}
else
{
2024-11-28 13:04:45 +08:00
Destroy(gameObject);
2024-11-26 12:29:47 +08:00
}
}
2024-11-28 13:04:45 +08:00
2024-12-26 17:26:46 +08:00
void OnApplicationPause(bool pauseStatus)
{
if (starPay && !isCallBack && !pauseStatus)
{
DebugUtil.Log("用户直接回到应用");
starPay = false;
WaitingForServer.Instance.EventDone(WaitingForServer.EventName.Pay);
}
}
2024-11-25 16:52:19 +08:00
private const string PayPost = "orders/wechat";
2024-11-22 17:37:15 +08:00
2024-11-25 16:52:19 +08:00
[Serializable]
private class PayRequestData
2024-11-22 17:37:15 +08:00
{
2024-11-25 16:52:19 +08:00
public string items;
2024-12-30 15:13:26 +08:00
public int actor_id;
2024-11-25 16:52:19 +08:00
2024-12-30 15:13:26 +08:00
public PayRequestData(string items, int actorID)
2024-11-22 17:37:15 +08:00
{
2024-11-25 16:52:19 +08:00
this.items = items;
actor_id = actorID;
2024-11-22 17:37:15 +08:00
}
}
2024-11-25 16:52:19 +08:00
[Serializable]
private class Items
2024-11-22 17:37:15 +08:00
{
2024-12-09 14:59:05 +08:00
public string product_id;
2024-11-25 16:52:19 +08:00
public int count;
2024-11-22 17:37:15 +08:00
}
2024-11-25 16:52:19 +08:00
// 请求结果
private class WebRequestResult
2024-11-22 17:37:15 +08:00
{
2024-11-25 16:52:19 +08:00
public int code;
public string message;
2024-11-25 17:47:26 +08:00
public WxData data;
}
private class WxData
{
public string noncestr;
public string package;
public string partnerid;
public string prepayid;
public string sign;
public string timestamp;
2024-11-22 17:37:15 +08:00
}
2024-12-26 17:26:46 +08:00
/// <summary>
/// 是否有回调结果
/// </summary>
private bool isCallBack;
/// <summary>
/// 开始支付
/// </summary>
private bool starPay;
/// <summary>
/// 开始支付
/// </summary>
public void BuyGoods(string currencyID, int count)
{
WaitingForServer.Instance.EventWaiting(WaitingForServer.EventName.Pay, false);
starPay = true;
WxPayRequest(currencyID, count);
}
/// <summary>
/// 请求服务器
/// </summary>
2024-12-09 14:59:05 +08:00
private async void WxPayRequest(string currencyID, int count)
2024-11-22 17:37:15 +08:00
{
2024-12-30 15:13:26 +08:00
var actorID = (int)Actor.Instance.Base.GetProp(ActorProp.ActorId);
2024-11-25 16:52:19 +08:00
var payUrl = AppConfig.Instance.LoginURL + PayPost;
DebugUtil.Log("发送拉起微信支付请求地址: " + payUrl);
2024-11-22 17:37:15 +08:00
2024-12-09 14:59:05 +08:00
var itemsList = new List<Items> { new() { product_id = currencyID, count = count } };
2024-11-25 16:52:19 +08:00
var itemJsonData = JsonConvert.SerializeObject(itemsList);
DebugUtil.Log("items.jsonData:{0}", itemJsonData);
PayRequestData sendData = new PayRequestData(itemJsonData, actorID);
var headData = PostHeader.PostHeaderInfo(new Dictionary<string, string>
{
{ "items", sendData.items },
2024-12-30 15:13:26 +08:00
{ "actor_id", sendData.actor_id.ToString() },
2024-11-25 16:52:19 +08:00
{ "timestamp", DateTimeOffset.UtcNow.ToUnixTimeSeconds().ToString() }
});
var jsonData = JsonUtility.ToJson(sendData);
DebugUtil.Log("WebRequestData.jsonData:{0}", jsonData);
var bytes = Encoding.UTF8.GetBytes(jsonData);
var www = new UnityWebRequest(payUrl, UnityWebRequest.kHttpVerbPOST)
{
uploadHandler = new UploadHandlerRaw(bytes),
downloadHandler = new DownloadHandlerBuffer(),
};
www.SetRequestHeader("Content-Type", "application/json;charset=utf-8"); //为了保证客户端发送的json格式在后端能解析
www.SetRequestHeader("signature", headData["signature"]);
www.SetRequestHeader("timestamp", headData["timestamp"]);
www.SetRequestHeader("accessKey", headData["accessKey"]);
2024-11-22 17:37:15 +08:00
try
{
2024-11-25 16:52:19 +08:00
await www.SendWebRequest();
if (www.result != UnityWebRequest.Result.Success)
{
CommonUtils.ShowMessageTips("支付失败,请重试");
DebugUtil.LogError(www.downloadHandler.text);
}
else
{
DebugUtil.Log("http消息请求成功!\n返回内容:" + www.downloadHandler.text);
WebRequestResult result = JsonConvert.DeserializeObject<WebRequestResult>(www.downloadHandler.text);
if (result.code == 0)
{
2024-11-25 17:47:26 +08:00
BuyGoods(result.data);
2024-11-25 16:52:19 +08:00
DebugUtil.Log("拉起微信支付SDK成功");
}
else
{
DebugUtil.LogError("拉起微信支付SDK失败");
2024-12-11 16:37:01 +08:00
UITipsManager.ShowTips("支付失败,请重试");
2024-12-26 17:26:46 +08:00
WaitingForServer.Instance.EventDone(WaitingForServer.EventName.Pay);
2024-11-25 16:52:19 +08:00
}
}
2024-11-22 17:37:15 +08:00
}
2024-11-25 16:52:19 +08:00
catch (UnityWebRequestException e)
2024-11-22 17:37:15 +08:00
{
2024-11-25 16:52:19 +08:00
DebugUtil.LogError(e);
var pattern = @"\{.*\}";
var match = Regex.Match(e.Message, pattern);
if (match.Success)
{
var json = match.Value;
WebRequestResult res = JsonConvert.DeserializeObject<WebRequestResult>(json);
DebugUtil.LogError("请求失败, 服务器有错误响应: " + res.message);
2024-12-11 16:37:01 +08:00
UITipsManager.ShowTips("无法购买");
2024-11-25 16:52:19 +08:00
}
else
{
2024-12-11 15:50:55 +08:00
UITipsManager.ShowTips("无法购买");
2024-11-25 16:52:19 +08:00
DebugUtil.LogError("请求失败!");
}
2024-12-25 15:16:32 +08:00
2024-12-26 17:26:46 +08:00
WaitingForServer.Instance.EventDone(WaitingForServer.EventName.Pay);
2024-11-22 17:37:15 +08:00
}
}
2024-12-26 17:26:46 +08:00
#region 与微信通信
2024-11-25 17:47:26 +08:00
private const string AppID = "wxa286fb2f1bcb664c"; // AppID
2024-12-05 19:43:27 +08:00
private const string PayMethodName = "WxPayByApp"; // 调起微信支付的方法
private const string InitMethodName = "WechatInit"; // 调起微信初始化方法
private const string WxAndroidClassName = "com.phxh.official.nld.wx.MainActivity";
2024-12-26 17:26:46 +08:00
private AndroidJavaObject utils;
2024-11-25 17:47:26 +08:00
/// <summary>
/// 初始化WXPay
/// </summary>
private void InitWxPay()
{
try
{
DebugUtil.Log("开始初始化微信支付");
2024-11-25 17:47:26 +08:00
using AndroidJavaClass unityPlayer = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
var currentActivity = unityPlayer.GetStatic<AndroidJavaObject>("currentActivity");
2024-12-05 19:43:27 +08:00
utils = new AndroidJavaObject(WxAndroidClassName);
2024-12-03 11:56:58 +08:00
utils.Call(InitMethodName, currentActivity);
2024-11-25 17:47:26 +08:00
}
catch (Exception e)
{
DebugUtil.Log("初始化微信支付异常:{0}", e);
}
}
2024-12-26 17:26:46 +08:00
public bool CheckWxInit()
2024-11-25 17:47:26 +08:00
{
2024-12-26 17:26:46 +08:00
try
2024-11-25 17:47:26 +08:00
{
2024-12-26 17:26:46 +08:00
if (utils == null)
return false;
var result = utils.Call<bool>("IsWechatInstalled");
return result;
}
catch (Exception e)
{
DebugUtil.LogError("WxPayHandle.CheckWxInit Error, e:{0} ", e);
return false;
2024-11-25 17:47:26 +08:00
}
}
/// <summary>
/// 支付回调
/// </summary>
public void WxPayCallback(string str)
{
// 返回结果 0 成功
// -1 错误 可能的原因:签名错误、未注册APPID、项目设置APPID不正确、注册的APPID与设置的不匹配、其他异常原因等
// -2 用户取消
2024-12-11 15:50:55 +08:00
try
{
2024-12-26 17:26:46 +08:00
starPay = false;
isCallBack = true;
2024-12-11 15:50:55 +08:00
DebugUtil.Log("微信支付回调, 结果码:{0}", str);
2024-12-09 14:59:05 +08:00
2024-12-11 15:50:55 +08:00
if (int.TryParse(str, out var code))
{
switch (code)
{
case -2:
UITipsManager.ShowTips("取消支付");
break;
case -1:
UITipsManager.ShowTips("支付失败,请重试");
break;
}
}
UIManager.Instance.CloseWindow(UINameConst.UI_Pay);
2024-12-26 17:26:46 +08:00
WaitingForServer.Instance.EventDone(WaitingForServer.EventName.Pay);
2024-12-11 15:50:55 +08:00
}
catch (Exception e)
{
DebugUtil.LogError("WXPayHandle.WxPayCallback error:{0}", e);
2024-12-26 17:26:46 +08:00
WaitingForServer.Instance.EventDone(WaitingForServer.EventName.Pay);
2024-12-11 15:50:55 +08:00
}
2024-11-25 17:47:26 +08:00
}
2024-12-26 17:26:46 +08:00
private void BuyGoods(WxData wxData)
2024-11-25 17:47:26 +08:00
{
2024-12-26 17:26:46 +08:00
if (wxData == null)
2024-11-25 17:47:26 +08:00
{
2024-12-26 17:26:46 +08:00
DebugUtil.LogError("请求支付数据为空");
return;
}
2024-12-26 17:26:46 +08:00
isCallBack = false;
// PayMethodName // 支付方法
// req.appId = APP_ID; // 应用ID
// req.partnerId = MCH_ID; // 商户号
// req.prepayId = prepayid; // 预支付交易会话ID
// req.packageValue = packageValue; // 包名
// req.nonceStr = noncaestr; // 随机字符串
// req.timeStamp = timestamp; // 时间戳
// req.sign = sign; // 签名
// WXPayEntryActivity.GameObjectName = callBackObjectName; // 支付回调组件
// WXPayEntryActivity.CallBackFuncName = CallBackFuncName; // 支付回调方法
DebugUtil.Log("开始调起微信支付");
utils.Call(PayMethodName, AppID, wxData.partnerid, wxData.prepayid, wxData.package, wxData.noncestr,
wxData.timestamp, wxData.sign, "WXPayHandle",
"WxPayCallback");
2024-11-25 17:47:26 +08:00
}
2024-12-26 17:26:46 +08:00
#endregion
2024-11-22 17:37:15 +08:00
}