Rewards Ads in Flutter using Admob with Server Side Verification (SSV)

Server-Side Verification in Rewarded Ads for Flutter Apps

Rewarded ads offer a valuable way to engage users and monetize your Flutter app. However, relying solely on the ad network’s reporting can leave you vulnerable to fraudulent activity. Thankfully, server-side verification (SSV) provides a robust solution to ensure users truly complete the ad before granting rewards. This blog post dives into implementing SSV for rewarded ads in Flutter apps, boosting your app’s security and ad revenue.

Understanding SSV:

SSV shifts the verification process from the client-side app to your server. The ad network sends a signed message containing details about the ad completion to your server. Your server then verifies the signature and data using the ad network’s public key, confirming the ad completion legitimacy before rewarding the user.

Implementation Steps:

1. Configure Ad Unit:

  • Enable SSV in your AdMob ad unit settings.
  • Set up a callback URL on your server where AdMob will send the verification message.

2. Server-Side Setup:

  • Choose a server-side language (e.g., Node.js, Java).
  • Set up a web server to handle the callback URL.
  • Integrate the ad network’s SDK or library for signature verification.
  • Implement logic to grant rewards based on successful verification.

3. Flutter App Integration:

  • Use the Flutter plugin for your chosen ad network (e.g., google_mobile_ads).
  • Set the RewardedAdListener and handle the onRewardedAdUserEarnedReward event.
  • Within the event handler, use the ad network’s API to send a verification request to your server endpoint (usually by including the reward details in the request).

4. Testing and Deployment:

  • Use test ad units and custom data for initial testing.
  • Thoroughly test your server-side verification logic in various scenarios.
  • Deploy with production ad units only after successful testing.

Additional Tips:

  • Securely store and manage your ad network’s public key on your server.
  • Consider using a dedicated server for handling ad verification requests.
  • Monitor your server logs and ad analytics for suspicious activity.

Benefits of SSV:

  • Enhanced security against fraudulent ad completion claims.
  • Improved reliability of reported ad revenue.
  • More control over the reward granting process.
  • Potential for higher earning potential by mitigating fraudulent activity.

Implementing server-side verification (SSV) for rewarded ads in Flutter apps using Dart

I. Project Setup:

  • Create a new Flutter project using the command flutter create my_rewarded_ad_app.
  • Add the required dependencies to your pubspec.yaml file:
dependencies:
  flutter:
    sdk: flutter
  google_mobile_ads: ^1.7.0+4 # AdMob plugin
  http: ^0.13.5 # For making HTTP requests to your server

II. AdMob Configuration:

  • Create an AdMob account and ad unit.
  • Enable SSV for your ad unit in the AdMob dashboard.
  • Obtain the following from your ad unit settings:
  • Note the callback URL you provide when configuring SSV; you’ll use it later.

III. Flutter App Implementation:

1. Initialize AdMob:

import 'package:flutter/material.dart';
import 'package:google_mobile_ads/google_mobile_ads.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  MobileAds.instance.initialize(); // Initialize AdMob SDK
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  // ... (rest of your app's code)
}

2. Create RewardedAd:

RewardedAd _rewardedAd;

// Load and show the rewarded ad when needed
void _loadRewardedAd() {
  _rewardedAd = RewardedAd(
    adUnitId: your_ad_unit_id, // Insert your actual ad unit ID
    listener: _onRewardedAdListener,
  );
  _rewardedAd.load();
}

void _showRewardedAd() {
  if (_rewardedAd.isLoaded) {
    _rewardedAd.show();
  } else {
    print('The rewarded ad hasn\'t loaded yet.');
  }
}

void _onRewardedAdListener(RewardedAdEvent event) {
  if (event == RewardedAdEvent.userEarnedReward) {
    _verifyRewardOnServer(event.reward); // Send reward details to server for verification
  }
}

3. Implement Reward Verification:

Future<bool> _verifyRewardOnServer(RewardItem reward) async {
  try {
    final response = await http.post(
      Uri.parse('your_server_endpoint_url'), // Replace with your actual endpoint
      body: {
        'userId': reward.userId,
        'type': reward.type,
        'amount': reward.amount,
      },
    );

    if (response.statusCode == 200) {
      final data = jsonDecode(response.body);
      return data['isValidReward'];
    } else {
      print('Error verifying reward on server: ${response.statusCode}');
      return false;
    }
  } catch (error) {
    print('Error sending reward verification request: $error');
    return false;
  }
}

IV. Server-Side Verification (Implementation varies depending on your server-side technology and preferences):

Here is an example using Node.js

Prerequisites 📋

  • Node >= 12.0.0

If you are using firebase cloud functions, you can safely choose to have nodejs 12 runtime. Add a function to listent to incoming http requests.

Installing 🔧

Install via NPM

$ npm install --save admob-rewarded-ads-ssv
const admobSSV = require('admob-rewarded-ads-ssv');
 
//Add callback to your rewarded ads in your admob account.
//Make sure you listen to 'get' request.
 
app.get('/ssv-verify', (req, res, next) => {
    // If you want to debug then send second param as true
    // admobSSV.verify(req.url, true);
    admobSSV.verify(req.url)
        .then(() => {
          //Verification Successful
        })
        .catch((e) => {
          //Verification Failed
          //console.error(e.message);
        });
});

Leave a Reply