目录
1.安装支付插件
3.配置google 支付key
4.AndroidManifest.xml添加权限
5.更新aab到googleplay控制台
6.支付管理脚本
window---package manager---In App Purchasing
⚠️ unity版本 2021.3.13f1c1
2.配置商品
⚠️配置了billing权限的安装包 提交到play后台以后,才可以配置后台商品
using System;
using System.Collections;
using System.Collections.Generic;
using Unity.Services.Core;
using Unity.Services.Core.Environments;
using UnityEngine;
using UnityEngine.Purchasing;
using UnityEngine.Purchasing.MiniJSON;
public class IAPManager : MonoBehaviour, IStoreListener
{
public MenuContr menu;
public GameObject pop_ad1;
public GameObject pop_ad2;
public GameObject pop_power;
public static IAPManager instance;
private string environment = "production";
async void Start()
{
instance = this;
#if !UNITY_EDITOR
try
{
var options = new InitializationOptions().SetEnvironmentName(environment);
await UnityServices.InitializeAsync(options).ContinueWith(task =>
{
var text = "Congratulations!\nUnity Gaming Services has been successfully initialized.";
Debug.Log(text);
StartCoroutine("InitPurchasing");
});
}
catch (Exception e)
{
Debug.LogError("unity Services init failed..." + e.Message.ToString());
}
#endif
}
IEnumerator InitPurchasing()
{
yield return new WaitForSeconds(1f);
if (m_StoreController == null)
{
this.InitializePurchasing();
}
}
public void InitializePurchasing()
{
if (this.IsInitialized())
{
Debug.Log("iap init success !");
return;
}
Debug.Log("...iap init ...");
ConfigurationBuilder configurationBuilder = ConfigurationBuilder.Instance(StandardPurchasingModule.Instance());
configurationBuilder.AddProduct(IAPManager.noAds_1, ProductType.Consumable);
configurationBuilder.AddProduct(IAPManager.power_50, ProductType.Consumable);
configurationBuilder.AddProduct(IAPManager.noAds_2, ProductType.Consumable);
UnityPurchasing.Initialize(this, configurationBuilder);
}
private bool IsInitialized()
{
//return true;
if (m_StoreController != null && m_StoreExtensionProvider != null)
{
return true;
}
else
{
return false;
}
}
public void BuyPower()
{
TenJinContr.Instance.SendMessage("体力礼包-点击"); //0点击购买 1购买成功
this.BuyProductID(IAPManager.power_50);
}
public void BuyNoAds1()
{
TenJinContr.Instance.SendMessage("广告礼包1-点击"); //0点击购买 1购买成功
this.BuyProductID(IAPManager.noAds_1);
}
public void BuyNoAds2()
{
TenJinContr.Instance.SendMessage("广告礼包2-点击"); //0点击购买 1购买成功
this.BuyProductID(IAPManager.noAds_2);
}
public void BuyProductID(string productId)
{
//Debug.LogError("购买商品:" + productId);
//下发测试
//ProcessPurchase(productId);
//return;
if (this.IsInitialized())
{
Product product = IAPManager.m_StoreController.products.WithID(productId);
if (product != null && product.availableToPurchase)
{
UnityEngine.Debug.Log(string.Format("Purchasing product asychronously: '{0}'", product.definition.id));
IAPManager.m_StoreController.InitiatePurchase(product);
}
else
{
UnityEngine.Debug.Log("BuyProductID: FAIL. Not purchasing product, either is not found or is not available for purchase");
}
}
else
{
InitializePurchasing();
Debug.Log("BuyProductID FAIL. Not initialized.");
}
}
public void RestorePurchases()
{
if (!this.IsInitialized())
{
Debug.Log("RestorePurchases FAIL. Not initialized.");
InitializePurchasing();
return;
}
if (Application.platform == RuntimePlatform.IPhonePlayer || Application.platform == RuntimePlatform.OSXPlayer)
{
UnityEngine.Debug.Log("RestorePurchases started ...");
IAppleExtensions extension = IAPManager.m_StoreExtensionProvider.GetExtension();
extension.RestoreTransactions(delegate (bool result)
{
UnityEngine.Debug.Log("RestorePurchases continuing: " + result + ". If no further messages, no purchases available to restore.");
});
}
else
{
UnityEngine.Debug.Log("RestorePurchases FAIL. Not supported on this platform. Current = " + Application.platform);
}
}
public void OnInitialized(IStoreController controller, IExtensionProvider extensions)
{
Debug.Log("iap init Success");
m_StoreController = controller;
m_StoreExtensionProvider = extensions;
//Debug.LogError("2222222222:"+ this.IsInitialized().ToString());
// 这里可以获取您在AppStore和Google Play 上配置的商品;
ProductCollection products = m_StoreController.products;
Product[] all = products.all;
for (int i = 0; i < all.Length; i++)
{
Debug.Log(all[i].metadata.localizedTitle + "|" + all[i].metadata.localizedPriceString + "|" + all[i].metadata.localizedDescription + "|" + all[i].metadata.isoCurrencyCode);
}
#if UNITY_IOS
// m_AppleExtensions.RegisterPurchaseDeferredListener(OnDeferred);
#endif
}
public void OnInitializeFailed(InitializationFailureReason error)
{
UnityEngine.Debug.Log("OnInitializeFailed InitializationFailureReason:" + error);
}
public PurchaseProcessingResult ProcessPurchase(PurchaseEventArgs args)
{
Debug.LogError("pay success, begain reward...");
//PlayerPrefs.SetFloat("RechargeAnyone", 1);
//充值任意金额
//bool flag = true;
//CrossPlatformValidator crossPlatformValidator = new CrossPlatformValidator(GooglePlayTangle.Data(), AppleTangle.Data(), Application.identifier);
//try
//{
// IPurchaseReceipt[] array = crossPlatformValidator.Validate(args.purchasedProduct.receipt);
//}
//catch (IAPSecurityException)
//{
// flag = false;
//}
//if (flag)
//{
if (string.Equals(args.purchasedProduct.definition.id, IAPManager.power_50, StringComparison.Ordinal))
{
pop_power.SetActive(false);
Const.Instance.power_cur += 50;
TenJinContr.Instance.SendMessage("体力礼包-成功"); //0点击购买 1购买成功
}
else if (string.Equals(args.purchasedProduct.definition.id, IAPManager.noAds_1, StringComparison.Ordinal))
{
pop_ad1.SetActive(false);
AdsContr.Instance.HideBanner();
PlayerPrefs.SetInt("noAds", 1);
PlayerPrefs.Save();
menu.HideShopBtn(0);
TenJinContr.Instance.SendMessage("广告礼包1-成功"); //0点击购买 1购买成功
}
else if (string.Equals(args.purchasedProduct.definition.id, IAPManager.noAds_2, StringComparison.Ordinal))
{
pop_ad2.SetActive(false);
AdsContr.Instance.HideBanner();
PlayerPrefs.SetInt("noAds", 2);
PlayerPrefs.Save();
menu.HideShopBtn(1);
TenJinContr.Instance.SendMessage("广告礼包2-成功"); //0点击购买 1购买成功
}
//}
//tenjin归因
var price = args.purchasedProduct.metadata.localizedPrice;
double lPrice = decimal.ToDouble(price);
var currencyCode = args.purchasedProduct.metadata.isoCurrencyCode;
var wrapper = Json.Deserialize(args.purchasedProduct.receipt) as Dictionary; // https://gist.github.com/darktable/1411710
if (null != wrapper)
{
var payload = (string)wrapper["Payload"]; // For Apple this will be the base64 encoded ASN.1 receipt
var shopId = args.purchasedProduct.definition.id;
#if !UNITY_EDITOR && UNITY_ANDROID
var gpDetails = Json.Deserialize(payload) as Dictionary;
var gpJson = (string)gpDetails["json"];
var gpSig = (string)gpDetails["signature"];
//CompletedAndroidPurchase(productId, currencyCode, 1, lPrice, gpJson, gpSig);
TenJinContr.Instance._ins.Transaction(shopId, currencyCode, 1, lPrice, null, gpJson, gpSig);
#elif !UNITY_EDITOR && UNITY_IOS
var transactionId = purchaseEventArgs.purchasedProduct.transactionID;
//CompletedIosPurchase(productId, currencyCode, 1, lPrice , transactionId, payload);
TenJinContr.Instance._ins.Transaction(productId, currencyCode, 1, lPrice, transactionId, payload, null);
#endif
}
return PurchaseProcessingResult.Complete;
}
public void ProcessPurchase(string id)
{
if (string.Equals(id, IAPManager.power_50, StringComparison.Ordinal))
{
Const.Instance.power_cur += 50;
}
else if (string.Equals(id, IAPManager.noAds_1, StringComparison.Ordinal))
{
PlayerPrefs.SetInt("noAds", 1);
PlayerPrefs.Save();
menu.HideShopBtn(0);
}
else if (string.Equals(id, IAPManager.noAds_2, StringComparison.Ordinal))
{
PlayerPrefs.SetInt("noAds", 2);
PlayerPrefs.Save();
menu.HideShopBtn(1);
}
}
public void OnPurchaseFailed(Product product, PurchaseFailureReason failureReason)
{
UnityEngine.Debug.Log(string.Format("OnPurchaseFailed: FAIL. Product: '{0}', PurchaseFailureReason: {1}", product.definition.storeSpecificId, failureReason));
}
private static IStoreController m_StoreController;
private static IExtensionProvider m_StoreExtensionProvider;
public static string noAds_1 = "ad1_no_ads";
public static string noAds_2 = "ad2_no_ads";
public static string power_50 = "power_50";
}