目录

Advertising

Petal Ads Publisher Service is an advertising service provided by Huawei to help you monetize mobile data by leveraging Huawei devices and data capabilities. After integrating the advertising service, you can present precise, visually stunning, and high-value ad content within your quick game to generate advertising revenue. The process of integrating this service is as follows:

You can integrate the following ad types:

Prerequisites

Soliciting User Consent

Petal Ads Publisher Service supports personalized and non-personalized ads, and provides APIs for soliciting user consent and requesting ads based on user consent status.

  1. When your quick app is launched for the first time, determine whether to display a pop-up to obtain user consent.
  1. Call qg.requestConsentUpdate to update the status of user consent.
    • Upon failure callback, request non-personalized ads.
    • Upon success callback, return ad technology provider information and check the value of isNeedConsent.
      • If the value of isNeedConsent is false, personalized ads can be requested without soliciting user consent.
      • If the value of isNeedConsent is true and the value of consentStatus is 2, a pop-up needs to be displayed to solicit user consent.
  2. Solicit user consent.

    You need to solicit the consent (for example, in a custom pop-up) from a user and display the complete list of ad technology providers. The following demo is for your reference only.

    Figure 1 Pop-up

    Figure 2 Provider list displayed when "here" in Figure 1 is tapped

  3. Call qg.setConsentStatus to set the user consent obtained in step 3.
    • You must allow users to change or withdraw their consent. If they do so, call this API to update the consent status.
    • In the Chinese mainland, you can choose whether to call qg.setConsentStatus to set the user consent.
  4. Call qg.setTagForUnderAgeOfPromise by ad type and mark users under the age of consent.
  5. Call qg.setNonPersonalizedAd to set the ad type (personalized or non-personalized).
  6. Request the ad. If a user skips the pop-up, your app can request only non-personalized ads.

    You can call APIs to integrate native ads, rewarded ads, or banner ads.

For more details, please refer to the demo.

Native Ads

  1. Create an ad element using the following code: let nativeAd=qg.createNativeAd.
  2. Call nativeAd.load() to load ad data.

    The nativeAd.onLoad callback is executed upon success.

    nativeAd.onLoad((adlist) => {
    })

    The nativeAd.onError callback is executed upon a failure.

    nativeAd.onError((errorObj) => {
    })
  3. Call nativeAd.showDownloadButton to display the control button for users to download/open the app.
  4. Call nativeAd.reportAdShow to report ad impressions.
  5. Call nativeAd.reportAdClick to report each ad tap.
  6. Call nativeAd.hideDownloadButton to hide the control button when the ad page disappears.

For details, please refer to the demo.

Rewarded Ads

  1. Create an ad element using the following code: let rewardedVideoAd=qg.createRewardedVideoAd.
  2. Call rewardedVideoAd.load to obtain ad data. If successful, the ad playback entry is displayed.

    The rewardedVideoAd.onLoad callback is executed upon success.

    rewardedVideoAd.onLoad((adlist) => {
    })

    The rewardedVideoAd.onError callback is executed upon a failure.

    rewardedVideoAd.onError((errorObj) => {
    })
  3. Call rewardedVideoAd.show to report ad impressions.
  4. Call rewardedVideoAd.onClose to listen for the closing of the rewarded ad.
  5. Call rewardedVideoAd.load to load the next ad before closing the current one.
  6. When destroying the app page, call rewardedVideoAd.destroy to destroy the rewarded ad as well.

For details, please refer to the demo.

Banner Ads

  1. Create an ad element using the following code: let bannerAd=qg.createBannerAd.
  2. Call bannerAd.show to obtain the ad.

    The bannerAd.onLoad callback is executed upon success.

    bannerAd.onLoad(()=>{
        console.log('bannerAd onload success')
    })

    The bannerAd.onError callback is executed upon a failure.

    bannerAd.onError((e)=>{
        console.log('bannerAd onError '+ JSON.stringify(e))
    }) 
  3. Call bannerAd.hide and bannerAd.show to hide and show the ad, respectively.
  4. Call bannerAd.onClose to listen for the closing of the banner ad.
  5. Call bannerAd.destroy to destroy the banner ad. Any ad re-created after destruction will be a new one.

For details, please refer to the demo.

Interstitial Ads

  1. Create an interstitial ad using the following code: const interstitialAd=qg.createInterstitialAd.
  2. Call interstitialAd.load to load ad data.

    The interstitialAd.onLoad callback is executed upon a success. Then interstitialAd.show is called to display the ad.

    interstitialAd.onLoad(function (data) {
        console.log('onLoad data ' + JSON.stringify(data));
        interstitialAd.show();
    });

    The interstitialAd.onError callback is executed upon a failure.

    interstitialAd.onError((e)=>{
        console.log('interstitialAd onError '+ JSON.stringify(e))
    })
  3. Call interstitialAd.onClick to listen for taps on the interstitial ad.
  4. Call interstitialAd.onClose to listen for the closing of the interstitial ad. If the ad is closed, call interstitialAd.destroy to destroy it.
    interstitialAd.onClose(()=>{
        console.log('interstitialAd closed');
        interstitialAd.destroy();
    })

For details, please refer to the demo.

Testing and Releasing Ads

You need to test integrated ads prior to commercial release, and submit them to Huawei for acceptance.

Before the testing, ensure that:

  1. You are using a Huawei device for debugging and have obtained a test ad unit ID.

    Use the test ad unit ID in the test phase.

  2. HMS Core (APK) 4.0.0.300 or later has been installed on your test phone. You can download or update HMS Core (APK) on AppGallery.
  3. The system time of your test phone is the current time.
  4. The Allow all apps to track parameter is enabled on the test phone. (You can set this parameter under Settings > Privacy > Ads and privacy.)

Perform self-check based on the following rules:

  1. Do not set a timer to cyclically request ads.
  2. Do not repeatedly request ads after a failure.

    [Incorrect] Request the ad again in onError after the failure. If onError is triggered every time, it creates an infinite loop of "request ad -> failure -> request ad".

    [Recommended] Do not send a request again regardless of whether the request is successful or fails. The service can have one more try only for rewarded ads.

  3. Avoid reusing an ad for multiple displays. Ensure that a fresh ad is requested and retrieved in real-time following each completed impression.

    [Incorrect] Display the same global ad in multiple scenarios.

    [Recommended] The ad object in each scenario is independent. Use the createXX method to create an ad and register a callback.

  4. For pre-cached ads such as rewarded ads, ensure that there is an appropriate time interval between calling the load and show APIs. If the interval exceeds 1 hour, request another ad. Otherwise, the ad display will not be counted as valid for settlement.
  5. You are advised to preload a rewarded ad before calling the show API. In case of a load failure, the ad entry point should be hidden to prevent users from encountering a blank screen due to incomplete data loading.

    [Recommended] Add a delay of several seconds or minutes before calling the show API in the onLoad callback.

    The delay cannot exceed 1 hour. Otherwise, the ad will not be counted as valid for settlement.

  6. Ads should not be placed on screens that have no content or are not content-based.
  7. An ad must have a close button, especially for native ads with a custom layout.
  8. Ad assets must be displayed in full size and at their original aspect ratio. Ads can only be resized proportionally, with the aspect ratio unchanged.
  9. Do not set the ad background as a tappable area. Only specific ad assets, such as images, titles, and buttons, can trigger a redirection to the landing page.
  10. Do not request or display ads using prohibited methods.
  11. The reportAdClick API needs to be called to report each native ad tap.

    [Incorrect] Only one tap event is reported for multiple taps on a native ad.

  1. Each time a native ad is displayed, an impression event needs to be reported.

    [Incorrect] Only one impression event is reported when a native ad is displayed multiple times. For example, when an ad is displayed to a user for the first time, the reportAdShow API is called to report an impression. However, when the user returns to the ad page from another scenario, the ad remains visible but no impression event is reported.

    [Recommended] When the user returns to the ad page and the native ad is still displayed, an impression event needs to be reported. Generally, this logic is processed in onShow.

  2. When a user taps the native ad image, the reportAdClick API needs to be called to redirect the user to the landing page.
  3. For a native ad, the ad title (title) and source (source) need to be displayed.
  4. Rewarded ads need to be pre-loaded. Other types of ads are displayed upon request success in real time.

    [Incorrect] A native ad is requested but not displayed.

  5. Ads can be requested and displayed only after user consent to the privacy statement is obtained.

After the test and Huawei acceptance have been complete, you can prepare the commercial launch of your ads.

Sample Code

Watch video

[h2]Soliciting User Consent

checkAdConsent(){
  var _this = this;
    console.log("checkAdConsent start");
    // Note: setUnderAgeOfPromise is optional.
    // To request ads for users under the age of consent, call setUnderAgeOfPromise to set the tag for such users before calling requestConsentUpdate().
    qg.setUnderAgeOfPromise(false);
    // The value true indicates that the user is under the age of consent, and personalized ads cannot be requested. In this case, a failure callback is always executed upon the call of requestConsentUpdate, and no pop-up needs to be displayed.
    // Call qg.setUnderAgeOfPromise(false) to obtain user consent.
    // Display a pop-up.

    // Call requestConsentUpdate to update the status based on the choice made by the user in the pop-up.
    qg.requestConsentUpdate({
      success: function (data) {
        console.log("requestConsentUpdate success data " + JSON.stringify(data));
        //  If the value of isNeedConsent is false, personalized ads can be requested from Ads SDK. If the value is true, the user is in the EEA or another sensitive region, and user consent must be obtained.
        if (data.isNeedConsent==true) {
          if (data.consentStatus == 2){
            // Call showModal() to display the pop-up for soliciting user consent and call qg.setConsentStatus to set the user consent status. You can also query the user consent status stored locally.

            let check=cc.sys.localStorage.getItem("isTrue");
            if(check){
                console.log ('According to the history, the user has given consent before, and personalized ads can be requested.');
            }else{
              setTimeout(function () {
                 showModal();
              }, 100);
            }

          } else if(data.consentStatus == 1){
            // Only non-personalized ads are received.

            qg.setConsentStatus(1)
            qg.setNonPersonalizedAd(1)
          }
        }else{

             // Personalized ads can be requested.
            qg.setConsentStatus(0)
            qg.setNonPersonalizedAd(0)

            setTimeout(_this.showModal.bind(_this), 100); 

        }
        console.log("4444")
      },
      fail: function (data) {
          // The failure callback is executed. Request non-personalized ads. 
        console.log("requestConsentUpdate fail data " + JSON.stringify(data));
        qg.setConsentStatus(1)
        qg.setNonPersonalizedAd(1)
      },
      complete: function () { console.log("5555")}
    });
},
// Display a pop-up to solicit user consent and then display a list of all ad technology providers. 
// Determine the parameters to be padded when calling the qg.setConsentStatus and qg.setNonPersonalizedAd methods based on the user's consent status.
// Request personalized or non-personalized ads based on the user consent status.
showModal(){ 
    qg.showModal({
        title: 'Consent Example',
        content: 'SKIP or AGREE',
        success (res) {
            if (res.confirm) {
                console.log ('The user taps OK.')
                cc.sys.localStorage.setItem("isTrue",true)
                qg.setConsentStatus(0)
                qg.setNonPersonalizedAd(0)
            } else if (res.cancel) {
                console.log('The user taps Cancel.')
                cc.sys.localStorage.setItem("isTrue",false)
                qg.setConsentStatus(1)
            qg.setNonPersonalizedAd(1)
            }
        }
    })
},

[h2]Native Ads

var nativeAd;
var adId;
createNativeAd(){
     console.log("ad demo : loadNativeAd");
    nativeAd = qg.createNativeAd({
        adUnitId: "testu7m3hc4gvm",
        success: function(code) {
            console.log("loadNativeAd loadNativeAd : success");
        },
        fail: function(data, code) {
            console.log("loadNativeAd loadNativeAd fail: " + data + "," + code);
        },
        complete: function() {
            console.log("loadNativeAd loadNativeAd : complete");
        }
    });        
    nativeAd.offLoad();
    nativeAd.onLoad(function (test) {
        adId = test.adList[0].adId;
        console.log("ad demo loadNativeAd onLoad NativeAd enter length : " + test.adList.length);
        console.log(JSON.stringify(test));         
        var imgUrlList = test.adList[0].imgUrlList;
        console.log("ad demo : loadNativeAd onLoad imgUrlList : " + imgUrlList);
        cc.sys.localStorage.setItem("ImageList",imgUrlList);              
    });
    nativeAd.offError();
    nativeAd.onError(function (test) {
        console.log("ad demo : loadNativeAd onError enter" + test.errCode);
        console.log("ad demo : loadNativeAd onError enter" + test.errMsg);
    });  
     nativeAd.load();
}
loadPics(){  
    // remoteUrl: Image URL.
    let remoteUrl=cc.sys.localStorage.getItem("ImageList");
    console.log("remoteUrl"+remoteUrl);
    cc.assetManager.loadRemote(remoteUrl,{ext:".image"},(err, texture)=>{
        console.log("err"+err);
        var spriteFrame=new cc.SpriteFrame(texture);
        // let newNode=new cc.Node();
        // newNode.addComponent(cc.Sprite).spriteFrame=spriteFrame;
        this.sprite_node.getComponent(cc.Sprite).spriteFrame=spriteFrame;
        this.sprite_node.active=true;
        // this.node.addChild(newNode);
        // this.node.getComponent(cc.Sprite).spriteFrame = spriteFrame;
    });
}
loadNativeAdAd(){      
      this.loadPics();      
}
showDownloadButton(){
    nativeAd.showDownloadButton({
        // adId indicates the ad ID, which is returned by the nativeAd.onLoad callback.
        adId : adId,
        style : {
            left:300,
            top:500,
            heightType:'normal',
            width:300,
            minWidth:200,
            maxWidth:500,
            textSize:50,
            horizontalPadding:50,
            cornerRadius:22,
            normalTextColor:'#FFFFFF',
            normalBackground:'#5291FF',
            pressedColor:'#0A59F7',
            normalStroke:5,
            normalStrokeCorlor:'#FF000000',
            processingTextColor:'#5291FF',
            processingBackground:'#0F000000',
            processingColor:'#000000',
            processingStroke:10,
            processingStrokeCorlor:'#0A59F7',
            installingTextColor:'#000000',
            installingBackground:'#FFFFFF',
            installingStroke:15,
            installingStrokeCorlor:'#5291FF'
        },
        success: (code) => {
            console.log("showDownloadButton: success");
        },
        fail: (data, code) => {
            console.log("showDownloadButton fail: " + data + "," + code);
        },
        complete: () => {
            console.log("showDownloadButton : complete");
        }
    });
}
hideDownloadButton(){
    nativeAd.hideDownloadButton({
        // adId indicates the ad ID, which is returned by the nativeAd.onLoad callback.
        adId : adId,
        success: (code) => {
            console.log("hideDownloadButton: success");
       },
        fail: (data, code) => {
            console.log(" hideDownloadButton fail: " + data + "," + code);
        },
        complete: () => {
            console.log("hideDownloadButton : complete");
        }
    });
}

[h2]Rewarded Ads

// To operate the preloaded rewarded video, you need to create a video object, and then call load to load the video, call onload to listen for video loading, or call onclose to stop listening.
var rewardedVideoAd;
reLoadVideo(){
    rewardedVideoAd = qg.createRewardedVideoAd({
      adUnitId: "testx9dtjwj8hp",
      success: (code) => {
          console.log("ad demo : loadAndShowVideoAd createRewardedVideoAd success");
      },
      fail: (data, code) => {
          console.log("ad demo : loadAndShowVideoAd createRewardedVideoAd fail: " + data + "," + code);
      },
      complete: () => {
          console.log("ad demo : loadAndShowVideoAd createRewardedVideoAd complete");
      }
    });
    rewardedVideoAd.onLoad(() => {
    console.log('ad demo :ad loaded.')
    })

    rewardedVideoAd.onError((e) => {
        console.error('load ad error:' + JSON.stringify(e));
        const errCode = e.errCode
        const errMsg = e.errMsg
    })
    rewardedVideoAd.onClose((res) => {
       // if(!this.rewardedVideoAd) return
    // this.rewardedVideoAd.offClose(null);
        console.log('ad onClose: ' + res.isEnded)
    // this.rewardedVideoAd.offLoad(null);
        if (res && res.isEnded || res === undefined) {  
console.log ('The user finishes the video playback and wins a reward.')
        }else{
console.log ('The user has not finished the video playback and does not win a reward.')
        }
    })
    rewardedVideoAd.load()
},
// A rewarded ad needs to be pre-loaded. To achieve this, the preceding logic needs to be triggered once your app is launched. When the success callback is triggered after onLoad is called, display the ad element.
// Every time a player taps the ad playback button, call rewardedVideoAd.show() to play the ad. Call rewardedVideoAd.load() to obtain the next ad during the playback time or before closing an ad. 
requestRewardAd(){    
    rewardedVideoAd.show();
    rewardedVideoAd.load();  

},

[h2]Banner Ads

createBannerAd() {
    // Obtain the parameters of the current screen. 
    var sysInfo = qg.getSystemInfoSync();
    console.log("on getSystemInfoSync: success =" + JSON.stringify(sysInfo));
   // Obtain the height of the current screen, in dp.
    var bannerTop = sysInfo.safeArea.height
    bannerAd = qg.createBannerAd({
     // console.log("createBannerAd");
      adUnitId: 'testw6vs28auh3',
      adIntervals:30,
      style:{
     // The screen height minus the ad height is the value of top. 
        top:bannerTop-57,
        left:0,
        height:57,
        width:360,
      }
    });
    setTimeout(function () {
       bannerAd.show()
    }, 1000);
},
showBannerAd(){
    console.log(bannerAd);
    setTimeout(function () {
       bannerAd.show();
    }, 100);
}, 
hideBannerAd(){    
    setTimeout(function () {
       bannerAd.hide();
    }, 100);
}, 

[h2]Interstitial Ads

var interstitialAd;
loadInterstitialVideoAd() {
  if (interstitialAd) {
    interstitialAd.destroy();
  }
  interstitialAd = qg.createInterstitialAd({
    adUnitId: testb4znbuh3n2
  });
  interstitialAd.load({
    "channelExtras": {
      "customerChannel": "1"
    }
  });
  interstitialAd.onLoad(function (data) {
    console.log(
      "requestImageAdAndShow onLoad data= " + JSON.stringify(data)
    );
    interstitialAd.show();
  });
  interstitialAd.onError(err => {
    console.log(" requestImageAdAndShow on error = " + JSON.stringify(err));
  });
  interstitialAd.onClose(() => {
    console.log("requestImageAdAndShow interstitialAd closed");
    interstitialAd.destroy(() => {
      console.log("destroy");
    });
  });
  interstitialAd.onClick(() => {
    console.log("requestImageAdAndShow interstitialAd clicked");
  });
};

Links

[h2]FAQs