-
Notifications
You must be signed in to change notification settings - Fork 115
feat: rewarded ad sample app #1897
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
peterporfy
wants to merge
3
commits into
main
Choose a base branch
from
ads-296-sample
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,32 @@ | ||
| # OSX | ||
| .DS_Store | ||
|
|
||
| # node | ||
| node_modules/ | ||
| npm-debug.log | ||
| yarn-error.log | ||
|
|
||
| # Metro | ||
| .metro-health-check* | ||
|
|
||
| # Xcode / CocoaPods | ||
| ios/build/ | ||
| ios/Pods/ | ||
| ios/Podfile.lock | ||
| ios/.xcode.env.local | ||
| *.xcuserstate | ||
| xcuserdata/ | ||
|
|
||
| # Android/IntelliJ | ||
| android/build/ | ||
| android/app/build/ | ||
| android/app/.cxx/ | ||
| android/.gradle | ||
| android/local.properties | ||
| *.iml | ||
| *.hprof | ||
|
|
||
| # TypeScript / bundles | ||
| *.jsbundle | ||
|
|
||
| .yarn/ |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,160 @@ | ||
| import React, {useCallback, useEffect, useRef, useState} from 'react'; | ||
| import { | ||
| SafeAreaView, | ||
| StyleSheet, | ||
| Text, | ||
| TouchableOpacity, | ||
| View, | ||
| } from 'react-native'; | ||
| import Purchases, { | ||
| RewardVerificationResult, | ||
| VerifiedReward, | ||
| } from 'react-native-purchases'; | ||
| import mobileAds, { | ||
| AdEventType, | ||
| RewardedAdEventType, | ||
| RewardedInterstitialAd, | ||
| TestIds, | ||
| } from 'react-native-google-mobile-ads'; | ||
|
|
||
| // Your RevenueCat public SDK key (a Test Store key works while developing). | ||
| const API_KEY = 'YOUR_REVENUECAT_API_KEY'; | ||
|
|
||
| // Google's official test rewarded-interstitial ad unit (per-platform) — safe | ||
| // to commit and always fills. Swap for your own AdMob unit (with its | ||
| // server-side verification URL pointed at RevenueCat) to grant a real reward. | ||
| const AD_UNIT_ID = TestIds.REWARDED_INTERSTITIAL; | ||
|
|
||
| function describeReward(reward: VerifiedReward): string { | ||
| switch (reward.type) { | ||
| case 'virtual_currency': | ||
| return `+${reward.amount} ${reward.code}`; | ||
| case 'entitlement': | ||
| return `entitlement "${reward.identifier}"`; | ||
| case 'no_reward': | ||
| return 'no reward'; | ||
| case 'unsupported_reward': | ||
| return 'unsupported reward'; | ||
| } | ||
| } | ||
|
|
||
| export default function App() { | ||
| const [status, setStatus] = useState('Configuring…'); | ||
| const [impressionId, setImpressionId] = useState<string | null>(null); | ||
| const [result, setResult] = useState<string | null>(null); | ||
| const [ready, setReady] = useState(false); | ||
| const adRef = useRef<RewardedInterstitialAd | null>(null); | ||
|
|
||
| useEffect(() => { | ||
| (async () => { | ||
| Purchases.setLogLevel(Purchases.LOG_LEVEL.DEBUG); | ||
| Purchases.configure({apiKey: API_KEY}); | ||
| await mobileAds().initialize(); | ||
| setStatus('Ready. Tap to load a rewarded ad.'); | ||
| setReady(true); | ||
| })(); | ||
| }, []); | ||
|
|
||
| const loadAndShow = useCallback(async () => { | ||
| setReady(false); | ||
| setResult(null); | ||
| setStatus('Generating verification token…'); | ||
|
|
||
| // react-native-google-mobile-ads doesn't expose AdMob's response id before | ||
| // the ad loads (SSV options must be set at request time), so assign your own | ||
| // unique impression ID. Reuse it for your RevenueCat ad-tracking calls to | ||
| // correlate the reward with the impression. | ||
| const id = `${Date.now()}`; | ||
| setImpressionId(id); | ||
| const token = await Purchases.generateRewardVerificationToken(id); | ||
|
|
||
| // Forward the token to AdMob's server-side verification options. | ||
| const ad = RewardedInterstitialAd.createForAdRequest(AD_UNIT_ID, { | ||
| serverSideVerificationOptions: { | ||
| userId: token.appUserID, | ||
| customData: token.customData, | ||
| }, | ||
| }); | ||
| adRef.current = ad; | ||
|
|
||
| const unsubLoaded = ad.addAdEventListener( | ||
| RewardedAdEventType.LOADED, | ||
| () => { | ||
| setStatus('Ad loaded. Showing…'); | ||
| ad.show(); | ||
| }, | ||
| ); | ||
|
|
||
| // When the user earns the reward, poll RevenueCat for the verified result. | ||
| const unsubEarned = ad.addAdEventListener( | ||
| RewardedAdEventType.EARNED_REWARD, | ||
| async () => { | ||
| setStatus('Reward earned. Verifying…'); | ||
| const res: RewardVerificationResult = | ||
| await Purchases.pollRewardVerification(token.clientTransactionId); | ||
| if (res.failed || !res.reward) { | ||
| setResult('❌ verification failed'); | ||
| } else { | ||
| const extra = | ||
| res.moreRewards.length > 0 | ||
| ? ` (+${res.moreRewards.length} more)` | ||
| : ''; | ||
| setResult(`✅ ${describeReward(res.reward)}${extra}`); | ||
| } | ||
| setStatus('Done'); | ||
| setReady(true); | ||
| }, | ||
| ); | ||
|
|
||
| const unsubError = ad.addAdEventListener(AdEventType.ERROR, error => { | ||
| setStatus(`❌ Ad error: ${error.message}`); | ||
| setReady(true); | ||
| }); | ||
|
|
||
| const unsubClosed = ad.addAdEventListener(AdEventType.CLOSED, () => { | ||
| unsubLoaded(); | ||
| unsubEarned(); | ||
| unsubError(); | ||
| unsubClosed(); | ||
| }); | ||
|
|
||
| setStatus('Loading ad…'); | ||
| ad.load(); | ||
| }, []); | ||
|
|
||
| return ( | ||
| <SafeAreaView style={styles.container}> | ||
| <View style={styles.content}> | ||
| <Text style={styles.title}>Rewarded Ad Verification</Text> | ||
| <Text style={styles.status}>{status}</Text> | ||
| {impressionId != null && ( | ||
| <Text style={styles.impression}>impressionId: {impressionId}</Text> | ||
| )} | ||
| {result != null && <Text style={styles.result}>{result}</Text>} | ||
| <TouchableOpacity | ||
| style={[styles.button, !ready && styles.buttonDisabled]} | ||
| disabled={!ready} | ||
| onPress={loadAndShow}> | ||
| <Text style={styles.buttonText}>Load & show rewarded ad</Text> | ||
| </TouchableOpacity> | ||
| </View> | ||
| </SafeAreaView> | ||
| ); | ||
| } | ||
|
|
||
| const styles = StyleSheet.create({ | ||
| container: {flex: 1, backgroundColor: '#fff'}, | ||
| content: {flex: 1, justifyContent: 'center', padding: 24, gap: 16}, | ||
| title: {fontSize: 22, fontWeight: '600', textAlign: 'center'}, | ||
| status: {fontSize: 16, textAlign: 'center', color: '#333'}, | ||
| impression: {fontSize: 13, textAlign: 'center', color: '#888'}, | ||
| result: {fontSize: 18, textAlign: 'center', fontWeight: '600'}, | ||
| button: { | ||
| backgroundColor: '#f2545b', | ||
| paddingVertical: 16, | ||
| borderRadius: 12, | ||
| alignItems: 'center', | ||
| }, | ||
| buttonDisabled: {opacity: 0.4}, | ||
| buttonText: {color: '#fff', fontSize: 16, fontWeight: '600'}, | ||
| }); | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,76 @@ | ||
| # Ads Tester | ||
|
|
||
| A minimal React Native app that exercises RevenueCat's rewarded-ad **reward | ||
| verification** primitives (`Purchases.generateRewardVerificationToken` and | ||
| `Purchases.pollRewardVerification`) end to end, using | ||
| [`react-native-google-mobile-ads`](https://github.com/invertase/react-native-google-mobile-ads) | ||
| for the AdMob rewarded-interstitial. iOS and Android. The whole flow lives in | ||
| [`App.tsx`](./App.tsx). | ||
|
|
||
| ## The flow | ||
|
|
||
| 1. Assign a unique `impressionId` and generate a verification token — | ||
| `Purchases.generateRewardVerificationToken(impressionId)` returns | ||
| `{ customData, clientTransactionId, appUserID }`. (The screen shows the | ||
| `impressionId` so you can see what flows through.) | ||
| 2. Create the ad request with `serverSideVerificationOptions: { userId: appUserID, customData }`. | ||
| 3. Show the ad, and on `EARNED_REWARD` poll with `pollRewardVerification(clientTransactionId)` | ||
| and render the result. | ||
|
|
||
| ## Run | ||
|
|
||
| ```bash | ||
| # from the repo root (Yarn Berry installs this standalone project's own lockfile) | ||
| cd examples/adsTester | ||
| yarn install | ||
| ``` | ||
|
|
||
| ### iOS | ||
|
|
||
| ```bash | ||
| cd ios && pod install && cd .. | ||
| yarn ios --simulator "iPhone Air" | ||
| ``` | ||
|
|
||
| `pod install` pulls the released `PurchasesHybridCommon` (18.25.0+, via | ||
| `react-native-purchases`), which contains the reward-verification bridge — no | ||
| local override needed. Use `--simulator` so the build doesn't grab a physical | ||
| device (which would require a signing team). | ||
|
|
||
| ### Android | ||
|
|
||
| ```bash | ||
| yarn android | ||
| ``` | ||
|
|
||
| Needs an emulator or device already running (`yarn android` installs and | ||
| launches on whichever one `adb` sees). The Android SDK/toolchain has its own | ||
| version requirements independent of this app — if the build fails with a | ||
| Gradle/JDK error, that's usually the fix (this repo has been tested with JDK | ||
| 17). | ||
|
|
||
| ## Local SDK resolution | ||
|
|
||
| `react-native-purchases` is intentionally **not** in `package.json`; it resolves | ||
| from this branch's source via `babel.config.js` (alias → `../../src/index`), | ||
| `metro.config.js` (`watchFolders` + peer-dep dedup), and `react-native.config.js` | ||
| (native autolinking). So the app always exercises the code on the current branch. | ||
|
|
||
| ## Values | ||
|
|
||
| Ships with placeholder/test values, safe to commit: | ||
|
|
||
| - `API_KEY` in `App.tsx` — set your RevenueCat public SDK key (a Test Store key | ||
| works while developing). | ||
| - `AD_UNIT_ID` in `App.tsx` — Google's public **test** rewarded-interstitial unit | ||
| (`TestIds.REWARDED_INTERSTITIAL`, resolved per-platform). | ||
| - `GADApplicationIdentifier` in `ios/adsTester/Info.plist` — Google's test | ||
| app id for iOS. | ||
| - `react-native-google-mobile-ads.android_app_id` in `app.json` — Google's test | ||
| app id for Android. | ||
|
|
||
| Out of the box the ad fills but `pollRewardVerification` returns `failed` (no | ||
| reward rule sits behind a test ad unit). For a real grant, swap these for your | ||
| own app's key, an AdMob unit whose server-side verification URL points at | ||
| RevenueCat, and your AdMob app id (both platforms) — then configure a reward | ||
| rule in the RevenueCat dashboard. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,119 @@ | ||
| apply plugin: "com.android.application" | ||
| apply plugin: "org.jetbrains.kotlin.android" | ||
| apply plugin: "com.facebook.react" | ||
|
|
||
| /** | ||
| * This is the configuration block to customize your React Native Android app. | ||
| * By default you don't need to apply any configuration, just uncomment the lines you need. | ||
| */ | ||
| react { | ||
| /* Folders */ | ||
| // The root of your project, i.e. where "package.json" lives. Default is '../..' | ||
| // root = file("../../") | ||
| // The folder where the react-native NPM package is. Default is ../../node_modules/react-native | ||
| // reactNativeDir = file("../../node_modules/react-native") | ||
| // The folder where the react-native Codegen package is. Default is ../../node_modules/@react-native/codegen | ||
| // codegenDir = file("../../node_modules/@react-native/codegen") | ||
| // The cli.js file which is the React Native CLI entrypoint. Default is ../../node_modules/react-native/cli.js | ||
| // cliFile = file("../../node_modules/react-native/cli.js") | ||
|
|
||
| /* Variants */ | ||
| // The list of variants to that are debuggable. For those we're going to | ||
| // skip the bundling of the JS bundle and the assets. Default is "debug", "debugOptimized". | ||
| // If you add flavors like lite, prod, etc. you'll have to list your debuggableVariants. | ||
| // debuggableVariants = ["liteDebug", "liteDebugOptimized", "prodDebug", "prodDebugOptimized"] | ||
|
|
||
| /* Bundling */ | ||
| // A list containing the node command and its flags. Default is just 'node'. | ||
| // nodeExecutableAndArgs = ["node"] | ||
| // | ||
| // The command to run when bundling. By default is 'bundle' | ||
| // bundleCommand = "ram-bundle" | ||
| // | ||
| // The path to the CLI configuration file. Default is empty. | ||
| // bundleConfig = file(../rn-cli.config.js) | ||
| // | ||
| // The name of the generated asset file containing your JS bundle | ||
| // bundleAssetName = "MyApplication.android.bundle" | ||
| // | ||
| // The entry file for bundle generation. Default is 'index.android.js' or 'index.js' | ||
| // entryFile = file("../js/MyApplication.android.js") | ||
| // | ||
| // A list of extra flags to pass to the 'bundle' commands. | ||
| // See https://github.com/react-native-community/cli/blob/main/docs/commands.md#bundle | ||
| // extraPackagerArgs = [] | ||
|
|
||
| /* Hermes Commands */ | ||
| // The hermes compiler command to run. By default it is 'hermesc' | ||
| // hermesCommand = "$rootDir/my-custom-hermesc/bin/hermesc" | ||
| // | ||
| // The list of flags to pass to the Hermes compiler. By default is "-O", "-output-source-map" | ||
| // hermesFlags = ["-O", "-output-source-map"] | ||
|
|
||
| /* Autolinking */ | ||
| autolinkLibrariesWithApp() | ||
| } | ||
|
|
||
| /** | ||
| * Set this to true to Run Proguard on Release builds to minify the Java bytecode. | ||
| */ | ||
| def enableProguardInReleaseBuilds = false | ||
|
|
||
| /** | ||
| * The preferred build flavor of JavaScriptCore (JSC) | ||
| * | ||
| * For example, to use the international variant, you can use: | ||
| * `def jscFlavor = io.github.react-native-community:jsc-android-intl:2026004.+` | ||
| * | ||
| * The international variant includes ICU i18n library and necessary data | ||
| * allowing to use e.g. `Date.toLocaleString` and `String.localeCompare` that | ||
| * give correct results when using with locales other than en-US. Note that | ||
| * this variant is about 6MiB larger per architecture than default. | ||
| */ | ||
| def jscFlavor = 'io.github.react-native-community:jsc-android:2026004.+' | ||
|
|
||
| android { | ||
| ndkVersion rootProject.ext.ndkVersion | ||
| buildToolsVersion rootProject.ext.buildToolsVersion | ||
| compileSdk rootProject.ext.compileSdkVersion | ||
|
|
||
| namespace "com.revenuecat.adstester" | ||
| defaultConfig { | ||
| applicationId "com.revenuecat.adstester" | ||
| minSdkVersion rootProject.ext.minSdkVersion | ||
| targetSdkVersion rootProject.ext.targetSdkVersion | ||
| versionCode 1 | ||
| versionName "1.0" | ||
| } | ||
| signingConfigs { | ||
| debug { | ||
| storeFile file('debug.keystore') | ||
| storePassword 'android' | ||
| keyAlias 'androiddebugkey' | ||
| keyPassword 'android' | ||
| } | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Missing Android debug keystoreHigh Severity Debug signing points at Reviewed by Cursor Bugbot for commit eddc627. Configure here. |
||
| } | ||
| buildTypes { | ||
| debug { | ||
| signingConfig signingConfigs.debug | ||
| } | ||
| release { | ||
| // Caution! In production, you need to generate your own keystore file. | ||
| // see https://reactnative.dev/docs/signed-apk-android. | ||
| signingConfig signingConfigs.debug | ||
| minifyEnabled enableProguardInReleaseBuilds | ||
| proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro" | ||
| } | ||
| } | ||
| } | ||
|
|
||
| dependencies { | ||
| // The version of react-native is set by the React Native Gradle Plugin | ||
| implementation("com.facebook.react:react-android") | ||
|
|
||
| if (hermesEnabled.toBoolean()) { | ||
| implementation("com.facebook.react:hermes-android") | ||
| } else { | ||
| implementation jscFlavor | ||
| } | ||
| } | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.


There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Stuck UI after early dismiss
Medium Severity
The
CLOSEDhandler only unsubscribes listeners. If the user dismisses the ad without earning a reward,EARNED_REWARDnever runs, soreadystays false and the button remains disabled until the app is restarted.Reviewed by Cursor Bugbot for commit eddc627. Configure here.