I'm using firebase messaging in my flutter app but when I run my project it show Stringtoken=FirebaseInstanceId.getInstance().getToken(senderId, "*"); - flutter

I'm using firebase messaging in my flutter app but when I run my project it show String token = FirebaseInstanceId.getInstance().getToken(senderId, "*");
when I run my application it shows this error in the console:
C:\Users\cerbi\AppData\Local\Pub\Cache\hosted\pub.dartlang.org\firebase_messaging-9.1.4\android\src\main\java\io\flutter\plugins\firebase\messaging\FlutterFirebaseMessagingPlugin.java:166: error: cannot find symbol
String token = FirebaseInstanceId.getInstance().getToken(senderId, "*");
^
symbol: variable FirebaseInstanceId
location: class FlutterFirebaseMessagingPlugin
Note: Some input files use or override a deprecated API.
Note: Recompile with -Xlint:deprecation for details.
What went wrong:
Execution failed for task ':firebase_messaging:compileDebugJavaWithJavac'.
and when I navigate to the specific file stated in the error message here is the code in there
private Task<Map<String, Object>> getToken(Map<String, Object> arguments) {
return Tasks.call(
cachedThreadPool,
() -> {
String senderId =
arguments.get("senderId") != null
? (String) arguments.get("senderId")
: Metadata.getDefaultSenderId(FirebaseApp.getInstance());
String token = FirebaseInstanceId.getInstance().getToken(senderId, "*");
return new HashMap<String, Object>() {
{
put("token", token);
}
};
});
}
What can I do to resolve this problem, it seems that the existing code is not working anymore

You should use
FirebaseMessaging.getInstance().token
to get token, since
FirebaseInstanceId.getInstance().getToken
is deprecated.

To retrieve the current registration token for an app instance, you need to call
FirebaseMessaging.instance.getToken(); as stated here in their official guide.

Related

Get product list from Huawei In app purchase

So, i want to get my products list from my Huawei developer account, i integrate the sdk and all it's fine. the issue here in this code :
Future<List<ProductInfo>> getConsumableProducts() async {
try {
ProductInfoReq req = ProductInfoReq(); // The named parameter 'skuIds' is required, but there's no corresponding argument.Try adding the required argument.dartmissing_required_argumentThe named parameter 'priceType' is required, but there's no corresponding argument.Try adding the required argument.dartmissing_required_argument
req.priceType = IapClient.IN_APP_CONSUMABLE;
req.skuIds = ["prod_01", "prod_02"];
ProductInfoResult res = await IapClient.obtainProductInfo(req);
return res.productInfoList; // A value of type 'List<ProductInfo>?' can't be returned from the method 'getConsumableProducts' because it has a return type of 'Future<List<ProductInfo>>'
} on PlatformException catch (e) {
log(e.toString());
return null;
}
}
i mention the issues in the code. P.S : i made a search and verify that this code is the same code which public
If you want to obtain purchase information, you could follow the code below:
List<String> productIdList = new ArrayList<>();
// Only those products already configured in AppGallery Connect can be queried.
productIdList.add("ConsumeProduct1001");
ProductInfoReq req = new ProductInfoReq();
// priceType: 0: consumable; 1: non-consumable; 2: subscription
req.setPriceType(0);
req.setProductIds(productIdList);
// Obtain the Activity object that calls the API.
final Activity activity = getActivity();
// Call the obtainProductInfo API to obtain the details of the product configured in AppGallery Connect.
Task<ProductInfoResult> task = Iap.getIapClient(activity).obtainProductInfo(req);
Check here for more info.

How to Resove Error Related to HttpClient in WebAssembly App

I am trying to test HttpClient in a small WebAssemply App (created using .NET 5).
The program.cs contains following statement to add HttpClient service:
builder.Services.AddScoped(sp => new HttpClient { BaseAddress = new Uri(builder.HostEnvironment.BaseAddress) });
The source code of my test Razor Component is posted at the end. Following exception occurred when executing the statement: "HttpResponseMessage response = await http.GetAsync(apiUrl)". The same error occurred when using http.GetFromJsonAsync<>.
I was able to Web API to get data from same website in Blazor Server app. For some reason, I could not make it work in WebAssembly app. Any help will be appreciated.
ERROR MESSAGE
mono_wasm_start_single_stepping 2
crit: Microsoft.AspNetCore.Components.WebAssembly.Rendering.WebAssemblyRenderer[100]
Unhandled exception rendering component: TypeError: Failed to fetch
System.Net.Http.HttpRequestException: TypeError: Failed to fetch
at System.Net.Http.BrowserHttpHandler.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
at System.Net.Http.HttpClient.SendAsyncCore(HttpRequestMessage request, HttpCompletionOption completionOption, Boolean async, Boolean emitTelemetryStartStop, CancellationToken cancellationToken)
at WebAssemblyUseWebApi.Pages.Weather.OnInitializedAsync() in C:\projects\my_tryout\WebAssemblyUseWebApi\WebAssemblyUseWebApi\Pages\Weather.razor:line 27
at Microsoft.AspNetCore.Components.ComponentBase.RunInitAndSetParametersAsync()
at Microsoft.AspNetCore.Components.RenderTree.Renderer.GetErrorHandledTask(Task taskToHandle)
=============================================================================
SOURCE CODE
page "/weather"
#inject HttpClient http
<h3>Weather Data</h3>
#if (!string.IsNullOrEmpty(errorMessage))
{
<p>#errorMessage</p>
}
else if (string.IsNullOrEmpty(data))
{
<p>Loading ...</p>
}
else
{
<p>#data</p>
}
#code {
string errorMessage = string.Empty;
public string data;
protected override async Task OnInitializedAsync()
{
string apiUrl = "https://www.metaweather.com/api/location/2471217/";
HttpResponseMessage response = await http.GetAsync(apiUrl);
if (response.IsSuccessStatusCode)
{
data = response.Content.ReadAsStringAsync().Result;
}
else
{
errorMessage = response.ReasonPhrase;
}
}
}
That site does not seem to allow requests from a Browser.
There is no CORS header (access-control-allow-origin=...) in the response.
You can use either Blazor Serverside or add an API server to your WebAssembly project. Do have a look at the Wasm Hosted template before you try to reinvent the wheel.
The issue was resolved when I created an ASPCoreWebAPI app on the server side with following config settings in startup.cs program. These settings allow the WebAssembly app to retrieve data using HTTPClient.
1. In ConfigureServices, Add following
-------------------------------------------------------------------------
services.AddCors(options =>
{
options.AddPolicy(
"Open",
builder => builder.AllowAnyOrigin().AllowAnyHeader());
});
------------------------------------------------------------------------
2. In Configurations, add following
------------------------------------------------------------------------
app.UseCors("Open");
-----------------------------------------------------------------------

.Net Core: Validate Anti Forgery Token with Ionic front end

I have looked all over and have found similar solutions, but nothing that matches exactly what I'm working on.
We have a .net core MVC website with an API Controller for handling requests from an ionic mobile app which we are also developing.
In most cases, adding [ValidateAntiForgeryToken] to the API controller actions works. I have gone through the process of generating the token, passing it to Ionic, and storing it in the request headers for validation.
Here is the code I am using to fetch and store the token:
static XSRF_TOKEN_KEY: string = "X-XSRF-TOKEN";
static XSRF_TOKEN_NAME_KEY: string = "X-XSRF-TOKEN-NAME";
constructor(){}
static getXsrfToken(http: HTTP) : {tokenName: string, token: string} {
let tokenName: string = window.sessionStorage.getItem(ValidationManager.XSRF_TOKEN_NAME_KEY);
let token: string = window.sessionStorage.getItem(ValidationManager.XSRF_TOKEN_KEY);
if(!tokenName || !token){
this.fetchXsrfToken(http);
tokenName= window.sessionStorage.getItem(ValidationManager.XSRF_TOKEN_NAME_KEY);
token = window.sessionStorage.getItem(ValidationManager.XSRF_TOKEN_KEY);
}
return {
tokenName: tokenName,
token: token
};
}
private static setXsrfToken({ token, tokenName }: { token: string, tokenName: string }) {
window.sessionStorage.setItem(ValidationManager.XSRF_TOKEN_KEY, token);
window.sessionStorage.setItem(ValidationManager.XSRF_TOKEN_NAME_KEY, tokenName);
}
private static fetchXsrfToken(http: HTTP) {
let token: string = window.sessionStorage.getItem(ValidationManager.XSRF_TOKEN_KEY);
let tokenName: string = window.sessionStorage.getItem(ValidationManager.XSRF_TOKEN_NAME_KEY);
if (!token || !tokenName) {
let apiUrl: string = AppConfig.apiUrl + "/GetAntiforgeryToken";
http.get(apiUrl, {}, {})
.then(r => this.setXsrfToken(JSON.parse(r.data)))
.catch(r => console.error("Could not fetch XSRFTOKEN", r));
} else {
this.setXsrfToken({ token: token, tokenName: tokenName });
}
}
Here is the action in my controller that serves anti forgery tokens:
[HttpGet]
public override IActionResult GetAntiforgeryToken()
{
var tokens = _antiforgery.GetAndStoreTokens(HttpContext);
return new ObjectResult(new
{
token = tokens.RequestToken,
tokenName = tokens.HeaderName
});
}
I set the headers of the http plugin by calling this function from the view's associated typescript file:
initializeHttp() {
let token = ValidationManager.getXsrfToken(this.http);
this.http.setHeader(token.tokenName, token.token);
console.log("Http Initialized: ", token);
}
then any request I make with the http plugin is validated properly in the controller's action:
this.http.post(apiUrl, {}, {}).then(response => {
that.navCtrl.setRoot(HomePage);
});
Up to this point, everything works great. The problem arises when I try to use XmlHttpRequest to for a POST instead of the built-in http plugin:
let file = {
name: e.srcElement.files[0].name,
file: e.srcElement.files[0],
};
let formData: FormData = new FormData();
formData.append('file', file.file);
let xhr: XMLHttpRequest = new XMLHttpRequest();
xhr.open('POST', apiUrl, true);
console.log("setting request header: ", tokenVal); //verify that tokenVal is correct
xhr.setRequestHeader("X-XSRF-TOKEN", tokenVal);
xhr.send(formData);
If I remove the [ValidateAntiForgeryToken] attribute from the controller's action, the file is posted properly. However, nothing I have tried has worked with the attribute being included.
I believe the issue has something to do with the validation tokens being added to a cookie automatically by Ionic, and the cookie is passed along with the request from the http plugin. However, XMLHttpRequest does not pass the cookie along (and is unable to do so?).
I have read up on the subject quite a bit over the past few days but I admit that this validation is still mostly a black box to me. Is there a way to validate the request in my action using only the token which is passed up in the header?
The reason I am running into this problem is that I need to upload a file, which I was unable to do using the http plugin. There are solutions for uploading images using Ionic's file-transfer plugin, but it has been deprecated and the release notes suggest using XmlHttpRequest instead.
Other things I have tried:
I have found solutions for .net standard which use System.Web.Helpers.AntiForgery for custom validation on the server, but this namespace is not included in .net core and I could not find an equivalent.
I tried many different ways to post the file using the http plugin (since it has no issues validating the antiForgery token). Everything I tried resulted in the action being hit but the file being posted was always null. A solution which uploads a file using the http plugin would also be acceptable.
Why is it that I was able to spend two full days on this problem, but as soon as I post a question about it, I find the answer? Sometimes I think the internet gods are just messing with me.
As it turns out, the native http plugin has an uploadFile() function that I never saw mentioned anywhere else. Here's what the solution does:
Use the fileChooser plugin to select a file from the phone's storage
Use the filePath plugin to resolve the native filesystem path of the image.
Use http.uploadFile() instead of http.post()
This works because as mentioned above, I was able to properly set the validation token in the http plugin's header to be accepted by the controller.
And here is the code:
let apiUrl: string = AppConfig.apiUrl + "/UploadImage/";
this.fileChooser.open().then(
uri => {
this.filePath.resolveNativePath(uri).then(resolvedPath => {
loader.present();
this.http.uploadFile(apiUrl,{ },{ },resolvedPath, "image")
.then(result => {
loader.dismiss();
toastOptions.message = "File uploaded successfully!";
let toast = this.toastCtrl.create(toastOptions);
toast.present();
let json = JSON.parse(result.data);
this.event.imageUrl = json.imgUrl;
})
.catch(err => {
console.log("error: ", err);
loader.dismiss();
toastOptions.message = "Error uploading file";
let toast = this.toastCtrl.create(toastOptions);
toast.present();
});
});
}
).catch(
e => console.log(e)
);

Can't use cache:true with OAuth.initialize

I am trying to use OAuth according to https://oauth.io/docs/api in an android eclipse app.
import io.oauth.*;
.....
final OAuth o = new OAuth(this);
o.initialize(KEY);
works fine.
However, I want to use the cache functionality in order not to log on every time, so I try
o.initialize(KEY, {cache: true});
Unfortunately this won't compile. I get
"Multiple markers at this line
-Syntax error on tokens, delete these tokens
-Syntax error on token(s), misplaced construct(s)"
As you can tell I am an android and Eclipse newbie, any help appreciated.
The public key is the only argument used for the initialize method.
The correct method that accepts the cache object as an argument is popup.
Example:
OAuth.initialize('x9x9x9x9x9'); //OAuth.io public key
var promise = OAuth.popup('google_mail', {cache: true});
promise.done(function (result) {
    // make API calls
});
promise.fail(function (error) {
    // handle errors
});

I am trying to update status to twitter using twitter4j but it does not work

I succeeded to get every credentials(Oauth_token,Oauth_verifier).
With it, I tried to post a text to twitter account, but it always fail with error message "No authentication challenges found"
I found some solution like
"Check the time zone automatically",
"import latest twitter4j library" etc..
but after check it, still not work.
Is there anyone can show me the way.
code is like below
public static void updateStatus(final String pOauth_token,final String pOauth_verifier) {
new Thread() {
public void run() {
Looper.prepare();
try {
TwitterFactory factory = new TwitterFactory();
AccessToken accessToken = new AccessToken(pOauth_token,pOauth_verifier);
Twitter twitter = factory.getInstance();
twitter.setOAuthConsumer(Cdef.consumerKey, Cdef.consumerSecret);
twitter.setOAuthAccessToken(accessToken);
if (twitter.getAuthorization().isEnabled()) {
Log.e("btnTwSend","인증값을 셋팅하였고 API를 호출합니다.");
Status status = twitter.updateStatus(Cdef.sendText + " #" + String.valueOf(System.currentTimeMillis()));
Log.e("btnTwSend","status:" + status.getText());
}
} catch (Exception e) {
Log.e("btnTwSend",e.toString());
}
};
}.start();
}
"No authentication challenges found"
I think you are missing Access token secret in your code. That is why you are getting this exception.
Try following :
ConfigurationBuilder configurationBuilder;
Configuration configuration;
// Set the proper configuration parameters
configurationBuilder = new ConfigurationBuilder();
configurationBuilder
.setOAuthConsumerKey(TWITTER_CONSUMER_KEY);
configurationBuilder
.setOAuthConsumerSecret(TWITTER_CONSUMER_SECRET);
// Access token
configurationBuilder.setOAuthAccessToken(ACCESS_TOKEN);
// Access token secret
configurationBuilder
.setOAuthAccessTokenSecret(ACCESS_TOKEN_SECRET);
// Get the configuration object based on the params
configuration = configurationBuilder.build();
// Pass it to twitter factory to get the proprt twitter instance.
twitterFactory = new TwitterFactory(configuration);
twitter = twitterFactory.getInstance();
// use this instance to update
twitter.updateStatus("Your status");
I finally found the reason.
I thought parameter named 'oauth_token' , 'oauth_verifier' is member of accesstoken,
but it was not true.
I just had to pass one more way to get correct key.
and this way needs 'oauth_token' , 'oauth_verifier' to get accesstoken.
This code must add one more code below:
mAccessToken = mTwitter.getOAuthAccessToken(REQUEST_TOKEN,OAUTH_VERIFIER);