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

293 lines
9.5 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

using NLDPB;
using System;
using PhxhSDK;
using Gameplay;
using System.Text;
using UnityEngine;
using Gameplay.Net;
using Newtonsoft.Json;
using UnityEngine.Networking;
using Cysharp.Threading.Tasks;
using System.Collections.Generic;
using System.Text.RegularExpressions;
public class BilibiliPayHandle : SingletonMono<BilibiliPayHandle>
{
private static BilibiliPayHandle _instance;
/// <summary>
/// 加签
/// </summary>
private const string PAY_SIGN = "orders/biliGame";
/// <summary>
/// 发货
/// </summary>
private const string PAY_SUCCESS = "orders/biliGame/success";
/// <summary>
/// 支付
/// </summary>
private Action<string, string, int> payAction;
private void Awake()
{
if (_instance == null)
{
_instance = this;
DontDestroyOnLoad(gameObject);
}
else
{
Destroy(gameObject);
}
}
[Serializable]
private class PayRequestData
{
public string items;
public int actor_id;
public string game_money;
/// <summary>
/// uid
/// </summary>
public string third_user_id;
public PayRequestData(string items, int actorID, int moneyCount, string uid)
{
this.items = items;
actor_id = actorID;
game_money = moneyCount.ToString();
third_user_id = uid;
}
}
[Serializable]
private class Items
{
public string product_id;
public int count;
}
[Serializable]
private class PaySuccessRequestData
{
public string out_trade_no;
public string bs_trade_no;
public PaySuccessRequestData(string out_trade_no, string bs_trade_no)
{
this.out_trade_no = out_trade_no;
this.bs_trade_no = bs_trade_no;
}
}
/// <summary>
/// 请求结果
/// </summary>
private class WebRequestResult
{
public int code;
public string message;
public BiliPayData data;
}
private class BiliPayData
{
/// <summary>
/// 订单号
/// </summary>
public string order_sn;
/// <summary>
/// 签名
/// </summary>
public string order_sign;
/// <summary>
/// 价格
/// </summary>
public int money;
}
/// <summary>
/// 开始支付
/// </summary>
public void BuyGoods(string currencyID, int count, int diamonCount, string uid, Action<string, string, int> pay)
{
payAction = pay;
BiliPayRequest(currencyID, count, diamonCount, uid);
}
/// <summary>
/// 加签请求服务器
/// </summary>
private async void BiliPayRequest(string currencyID, int count, int diamonCount, string uid)
{
int actorID = (int)Actor.Instance.Base.GetProp(ActorProp.ActorId);
string payUrl = AppConfig.Instance.LoginURL + PAY_SIGN;
DebugUtil.Log($"发送拉起Bilibili支付请求地址: {payUrl}");
List<Items> itemsList = new() { new() { product_id = currencyID, count = count } };
string itemJsonData = JsonConvert.SerializeObject(itemsList);
DebugUtil.Log($"items.jsonData:{itemJsonData}");
PayRequestData sendData = new(itemJsonData, actorID, diamonCount, uid);
Dictionary<string, string> headData = PostHeader.PostHeaderInfo(new Dictionary<string, string>
{
{ "items", sendData.items },
{ "actor_id", sendData.actor_id.ToString() },
{ "game_money", sendData.game_money },
{ "timestamp", DateTimeOffset.UtcNow.ToUnixTimeSeconds().ToString() },
{ "third_user_id", sendData.third_user_id }
});
string jsonData = JsonUtility.ToJson(sendData);
DebugUtil.Log($"WebRequestData.jsonData:{jsonData}");
byte[] bytes = Encoding.UTF8.GetBytes(jsonData);
UnityWebRequest www = new(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"]);
try
{
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 (0 == result.code)
{
BuyGoods(result.data);
DebugUtil.Log("拉起bili支付SDK成功");
}
else
{
DebugUtil.LogError("拉起bili支付SDK失败");
UITipsManager.ShowTips("支付失败,请重试");
}
}
}
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<WebRequestResult>(json);
DebugUtil.LogError("请求失败, 服务器有错误响应: " + res.message);
UITipsManager.ShowTips("无法购买");
}
else
{
UITipsManager.ShowTips("无法购买");
DebugUtil.LogError("请求失败!");
}
}
}
/// <summary>
/// bili支付成功
/// </summary>
/// <param name="a"></param>
/// <param name="b"></param>
/// <param name="c"></param>
public async void BiliPaySuccess(string out_trade_no, string bs_trade_no)
{
string payUrl = AppConfig.Instance.LoginURL + PAY_SUCCESS;
DebugUtil.Log($"发送拉起Bilibili发货请求地址: {payUrl}");
PaySuccessRequestData sendData = new(out_trade_no, bs_trade_no);
Dictionary<string, string> headData = PostHeader.PostHeaderInfo(new Dictionary<string, string>
{
{ "out_trade_no", sendData.out_trade_no },
{ "bs_trade_no", sendData.bs_trade_no},
{ "timestamp", DateTimeOffset.UtcNow.ToUnixTimeSeconds().ToString() }
});
string jsonData = JsonUtility.ToJson(sendData);
DebugUtil.Log($"WebRequestData.jsonData:{jsonData}");
byte[] bytes = Encoding.UTF8.GetBytes(jsonData);
UnityWebRequest www = new(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"]);
try
{
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 (0 == result.code)
{
DebugUtil.Log("bili发货成功");
}
else
{
DebugUtil.LogError(result.message);
UITipsManager.ShowTips(result.message);
}
}
}
catch (UnityWebRequestException e)
{
DebugUtil.LogError(e);
string 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);
UITipsManager.ShowTips("无法发货");
}
else
{
UITipsManager.ShowTips("无法发货");
DebugUtil.LogError("请求失败!");
}
}
}
/// <summary>
/// 购买商品
/// </summary>
/// <param name="biliPayData"></param>
private void BuyGoods(BiliPayData biliPayData)
{
if (null == biliPayData)
{
DebugUtil.LogError("请求支付数据为空");
return;
}
DebugUtil.Log("开始调起bili支付");
payAction?.Invoke(biliPayData.order_sn, biliPayData.order_sign, biliPayData.money);
}
}