-
Notifications
You must be signed in to change notification settings - Fork 117
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
Merged
Merged
Changes from all commits
Commits
Show all changes
10 commits
Select commit
Hold shift + click to select a range
2e34bc9
feat: rewarded ad sample app
peterporfy 1445a19
feat(ads): standalone adsTester sample app
peterporfy 0ced4eb
chore(ads): revert purchaseTester changes
peterporfy d40f096
fix(ads): add debug.keystore
peterporfy 75b4792
fix(ads): fix close handler
peterporfy f96f0d7
fix(ads): remove dead code
peterporfy 5c04be0
fix(ads): better state handling
peterporfy 5d064ee
chore(ads): add eslint
peterporfy ba3f223
chore(ads): add circleci
peterporfy 3da0e52
fix(ads): change to real uuid
peterporfy 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
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,4 @@ | ||
| module.exports = { | ||
| root: true, | ||
| extends: '@react-native', | ||
| }; |
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,34 @@ | ||
| # 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 | ||
| *.keystore | ||
| !debug.keystore | ||
|
|
||
| # 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,184 @@ | ||
| import 'react-native-get-random-values'; | ||
| import React, {useCallback, useEffect, 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'; | ||
| import {v4 as uuidv4} from 'uuid'; | ||
|
|
||
| // 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); | ||
|
|
||
| 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 = uuidv4(); | ||
| setImpressionId(id); | ||
|
|
||
| let token; | ||
| try { | ||
| token = await Purchases.generateRewardVerificationToken(id); | ||
| } catch (e) { | ||
| setStatus(`❌ Failed to generate verification token: ${e}`); | ||
| setReady(true); | ||
| return; | ||
| } | ||
|
|
||
| // Forward the token to AdMob's server-side verification options. | ||
| const ad = RewardedInterstitialAd.createForAdRequest(AD_UNIT_ID, { | ||
| serverSideVerificationOptions: { | ||
| userId: token.appUserID, | ||
| customData: token.customData, | ||
| }, | ||
| }); | ||
|
|
||
| const unsubLoaded = ad.addAdEventListener( | ||
| RewardedAdEventType.LOADED, | ||
| () => { | ||
| setStatus('Ad loaded. Showing…'); | ||
| ad.show(); | ||
| }, | ||
| ); | ||
|
|
||
| let finished = false; | ||
|
|
||
| const cleanup = () => { | ||
| unsubLoaded(); | ||
| unsubEarned(); | ||
| unsubError(); | ||
| unsubClosed(); | ||
| }; | ||
|
|
||
| // When the user earns the reward, poll RevenueCat for the verified result. | ||
| const unsubEarned = ad.addAdEventListener( | ||
| RewardedAdEventType.EARNED_REWARD, | ||
| async () => { | ||
| setStatus('Reward earned. Verifying…'); | ||
| try { | ||
| 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'); | ||
| } finally { | ||
| finished = true; | ||
| setReady(true); | ||
| } | ||
| }, | ||
| ); | ||
|
|
||
| const unsubError = ad.addAdEventListener(AdEventType.ERROR, error => { | ||
| setStatus(`❌ Ad error: ${error.message}`); | ||
| finished = true; | ||
| setReady(true); | ||
| cleanup(); | ||
| }); | ||
|
|
||
| const unsubClosed = ad.addAdEventListener(AdEventType.CLOSED, () => { | ||
| if (!finished) { | ||
| finished = true; | ||
| setReady(true); | ||
| } | ||
| cleanup(); | ||
| }); | ||
|
peterporfy marked this conversation as resolved.
cursor[bot] marked this conversation as resolved.
|
||
|
|
||
| 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'}, | ||
| }); | ||
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.
Uh oh!
There was an error while loading. Please reload this page.