using NLDPB;
using System;
using UnityEngine;
using Gameplay.Net;
using GameWrapper.Pay;
using LC.Newtonsoft.Json;
using Cysharp.Threading.Tasks;
using System.Collections.Generic;
using System.Text.RegularExpressions;
namespace Gameplay.Pay
{
public class WxPayServiceImpl : IPaymentService
{
#region 微信支付相关数据
private const string AppID = "wxa286fb2f1bcb664c"; // AppID
private const string PayMethodName = "WxPayByApp"; // 调起微信支付的方法
private const string InitMethodName = "WechatInit"; // 调起微信初始化方法
private const string WxAndroidClassName = "com.phxh.official.nld.wx.MainActivity";
private AndroidJavaObject utils;
private const string PayPost = "orders/wechat";
[Serializable]
private class PayRequestData
{
public string items;
public int actor_id;
public PayRequestData(string items, int actorID)
{
this.items = items;
actor_id = actorID;
}
}
[Serializable]
private class Items
{
public string product_id;
public int count;
public int param;
}
// 请求结果
private class WebRequestResult
{
public int code;
public string message;
public WxData data;
}
private class WxData
{
public string noncestr;
public string package;
public string partnerid;
public string prepayid;
public string sign;
public string timestamp;
}
///
/// 是否有回调结果
///
private bool isCallBack;
///
/// 开始支付
///
private bool starPay;
#endregion
public void Initialize()
{
InitWxPay();
}
public bool IsAppInitialized()
{
return CheckWxInit();
}
public void BuyGoods(string currencyID, int count, int param = 0)
{
WaitingForServer.Instance.EventWaiting(WaitingForServer.EventName.Pay, false);
starPay = true;
WxPayRequest(currencyID, count, param);
}
public async void OnPaymentCallback(string result)
{
// 返回结果 0 成功
// -1 错误 可能的原因:签名错误、未注册APPID、项目设置APPID不正确、注册的APPID与设置的不匹配、其他异常原因等
// -2 用户取消
starPay = false;
isCallBack = true;
WaitingForServer.Instance.EventDone(WaitingForServer.EventName.Pay);
try
{
DebugUtil.Log("微信支付回调, 结果码:{0}", result);
if (int.TryParse(result, out var code))
{
switch (code)
{
case -2:
// UITipsManager.ShowTips("取消支付");
// break;
case -1:
// UITipsManager.ShowTips("支付失败,请重试");
await UI_ChargeShopPurchaseController.Open();
break;
}
}
}
catch (Exception e)
{
DebugUtil.LogError("WXPayHandle.WxPayCallback error:{0}", e);
}
}
public void OnApplicationPause(bool pauseStatus)
{
if (starPay && !isCallBack && !pauseStatus)
{
Debug.Log("用户直接回到应用");
starPay = false;
WaitingForServer.Instance.EventDone(WaitingForServer.EventName.Pay);
}
}
public bool IsPaying()
{
return starPay;
}
private void InitWxPay()
{
try
{
Debug.Log("开始初始化微信支付");
using AndroidJavaClass unityPlayer = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
var currentActivity = unityPlayer.GetStatic("currentActivity");
utils = new AndroidJavaObject(WxAndroidClassName);
utils.Call(InitMethodName, currentActivity);
}
catch (Exception e)
{
Debug.Log($"初始化微信支付异常: {e}");
}
}
private bool CheckWxInit()
{
try
{
if (utils == null)
return false;
var result = utils.Call("IsWechatInstalled");
return result;
}
catch (Exception e)
{
Debug.LogError($"WxPayHandle.CheckWxInit Error: {e}");
return false;
}
}
///
/// 请求服务器
///
private async void WxPayRequest(string currencyID, int count, int param = 0)
{
var actorID = (int)Actor.Instance.Base.GetProp(ActorProp.ActorId);
var payUrl = PostHeader.PostUrl + PayPost;
DebugUtil.Log("发送拉起微信支付请求地址: " + payUrl);
var itemsList = new List { new() { product_id = currencyID, count = count, param = param } };
var itemJsonData = JsonConvert.SerializeObject(itemsList);
DebugUtil.Log("items.jsonData:{0}", itemJsonData);
PayRequestData sendData = new PayRequestData(itemJsonData, actorID);
var headData = PostHeader.PostHeaderInfo(new Dictionary
{
{ "items", sendData.items },
{ "actor_id", sendData.actor_id.ToString() },
{ "timestamp", DateTimeOffset.UtcNow.ToUnixTimeSeconds().ToString() }
});
try
{
var res = await HttpHelper.PostAsync(payUrl, sendData, headData);
if (res.code != 0)
{
CommonUtils.ShowMessageTips("支付失败,请重试");
DebugUtil.LogError(res.message);
starPay = false;
WaitingForServer.Instance.EventDone(WaitingForServer.EventName.Pay);
return;
}
DebugUtil.Log("http消息请求成功!\n返回内容:" + res.message);
WebRequestResult result = JsonConvert.DeserializeObject(res.message);
if (result.code == 0)
{
BuyGoodsInWechat(result.data);
DebugUtil.Log("拉起微信支付SDK成功");
}
else
{
DebugUtil.LogError("拉起微信支付SDK失败");
UITipsManager.ShowTips("支付失败,请重试");
starPay = false;
WaitingForServer.Instance.EventDone(WaitingForServer.EventName.Pay);
}
}
catch (UnityWebRequestException e)
{
DebugUtil.LogError(e);
var pattern = @"\{.*\}";
var match = Regex.Match(e.Message, pattern);
if (match.Success)
{
var json = match.Value;
WebRequestResult res = JsonConvert.DeserializeObject(json);
DebugUtil.LogError("请求失败, 服务器有错误响应: " + res.message);
UITipsManager.ShowTips("无法购买");
}
else
{
UITipsManager.ShowTips("无法购买");
DebugUtil.LogError("请求失败!");
}
starPay = false;
WaitingForServer.Instance.EventDone(WaitingForServer.EventName.Pay);
}
}
///
/// 微信请求购买商品
///
private void BuyGoodsInWechat(WxData wxData)
{
if (wxData == null)
{
Debug.LogError("请求支付数据为空");
return;
}
isCallBack = false;
// PayMethodName // 支付方法
// req.appId = APP_ID; // 应用IDx
// 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; // 支付回调方法
Debug.Log("开始调起微信支付");
UIManager.Instance.CloseWindow(UINameConst.UI_Pay);
utils.Call(PayMethodName, AppID, wxData.partnerid, wxData.prepayid, wxData.package, wxData.noncestr,
wxData.timestamp, wxData.sign, "WXPayHandle",
"WxPayCallback");
}
}
public static class PayServiceAdapter
{
// 注册支付实现
public static void InitializeServices()
{
PaymentServiceLocator.WxPaymentService = new WxPayServiceImpl();
// 支付宝 ...
// PaymentServiceLocator.AliPaymentService = new AliPayServiceImpl();
}
}
}