獎勵廣告會在使用者與影片廣告、可試玩廣告和問卷調查互動後,提供應用程式內商品做為獎勵。詳情請參閱「獎勵廣告單元總覽」。
本指南說明如何將獎勵廣告整合至 React Native 原生應用程式。
必要條件
請先完成下列事項,再繼續操作:
- 設定 Google Mobile Ads SDK for React Native。
- 啟用測試廣告,並使用下列測試廣告單元:
僅適用於搭載 Android
ca-app-pub-3940256099942544/5224354917
iOS
ca-app-pub-3940256099942544/1712485313
載入廣告
如要載入獎勵廣告,請在 RewardedAd 類別上呼叫 load 方法。
以下範例會在成功時載入獎勵廣告,失敗時則記錄錯誤:
export async function loadRewardedAd(
adUnitId: string,
): Promise<RewardedAd | null> {
try {
const ad = await RewardedAd.load({adUnitId});
return ad;
} catch (error) {
const loadError = error as LoadAdError;
console.error('Failed to load rewarded ad:', loadError.message);
return null;
}
}
監聽廣告事件
顯示廣告前,請在載入的 RewardedAd 執行個體上設定 adEventCallback 事件監聽器。這個事件監聽器會接收廣告生命週期事件的回呼,例如廣告顯示在畫面上,或使用者輕觸廣告。如要查看可用的回呼,請參閱 AdEventCallback。
以下範例設定了回呼,用於監聽廣告事件:
export function registerAdEvents(ad: RewardedAd) {
ad.adEventCallback = {
// Called when the ad is presented on screen.
onAdShowedFullScreenContent: () => {
console.log('Rewarded ad showed full screen content.');
},
// Called when the ad is closed by the user.
onAdDismissedFullScreenContent: () => {
console.log('Rewarded ad dismissed full screen content.');
ad.destroy();
},
// Called when presentation fails.
onAdFailedToShowFullScreenContent: (error) => {
console.error('Failed to show rewarded ad:', error);
ad.destroy();
},
// Called when an impression is recorded.
onAdImpression: () => {
console.log('Rewarded ad recorded an impression.');
},
// Called when the user taps the ad.
onAdClicked: () => {
console.log('Rewarded ad was clicked.');
},
// Called when the ad is estimated to have earned money.
onAdPaid: (adValue) => {
console.log(
`Rewarded ad paid: ${adValue.amountMicros} ${adValue.currencyCode}`,
);
},
};
}
此外,這個範例也會在使用者關閉廣告或廣告無法顯示時,呼叫 destroy 方法。這個程序會釋出廣告使用的資源。
顯示廣告
如要顯示獎勵廣告,請呼叫 show 方法,並使用回呼處理使用者獲得的獎勵:
export function showRewardedAd(
ad: RewardedAd,
onRewardEarned: (reward: Reward) => void,
) {
ad.show(onRewardEarned);
}
選用:驗證伺服器端驗證回呼
如果應用程式需要在伺服器端驗證 (SSV) 回呼中加入自訂驗證參數 (例如使用者 ID 或自訂獎勵中繼資料),請在顯示廣告前,於載入的廣告例項上設定 serverSideVerificationOptions 屬性。
您設定的值會傳遞至 SSV 回呼查詢參數:
userId:傳遞至user_id查詢參數,用於識別使用者。customData:傳遞至custom_data查詢參數,以轉送自訂中繼資料。
以下範例會在顯示廣告前,於獎勵廣告物件上設定 ServerSideVerificationOptions (customData 和 userId):
查看完整範例
本節提供完整範例,說明如何將獎勵廣告整合至 React Native 原生應用程式。
以下範例將廣告整合至 React Native 元件、管理狀態中的廣告例項,並提供載入及顯示廣告的控制項:
後續步驟
整合獎勵廣告後,請參閱下列主題: