Firebase function is not triggering - android

I am using expo-payments-stripe API for the payment of an android app. And Stripe payment API is getting called from the following firebase function:
exports.payWithStripe = functions.https.onRequest((request, response) => {
stripe.charges.create({
amount: request.body.amount,
currency: request.body.currency,
source: request.body.token,
}).then((charge) => {
response.send(charge);
})
.catch(err =>{
console.log(err);
});
});
Here is the code for the client-side that calls the firebase functions:
payment = async () => {
if (this.state.token) {
fetch(
"https://us-central1-<>.cloudfunctions.net/payWithStripe",
{
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
},
body: JSON.stringify({
amount: this.state.amount,
currency: "usd",
token: this.state.token.tokenId,
}),
}
)
.then((response) => response.json())
.then((responseJson) => {
if (
responseJson.status === "succeeded" &&
responseJson.paid == true
) {
this.setState({ status: "succeeded", loading: false });
}
console.log(responseJson);
})
.catch((error) => {
this.setState({ status: "failed", loading: false });
console.error(error);
});
}
};
doPayment = async () => {
const params = {
number: this.state.number,
expMonth: parseInt(this.state.expMonth),
expYear: parseInt(this.state.expYear),
cvc: this.state.cvc,
};
const token = await Stripe.createTokenWithCardAsync(params);
this.setState({ token: token, loading: true });
setTimeout(() => {
this.payment();
}, 5000);
console.log(token);
};
Everything works fine in the test mode. But after deploying the app to the Play store Firebase function is not triggered. Any suggestions on why this might be happening? Also without ejecting expo what other options do I have to make payments from expo react native app for android?

Can you check adding await to the fetch or removing async from the payment function? Also why did you add setTimeout to the payment function call?

Related

React native Xiaomi Phone axios not working

We developed an application with react native.
I will leave the link of the application below, I do not know if this is prohibited.
I pull data with axios, it works on all android devices. But it doesn't work on Xiaomi phones. I could not find the reason for this.
const api = "apiadress/deneme.php?lesid="+getLessonId;
axios.get(api).then((response)=>{
db.transaction((tx) => {
tx.executeSql('UPDATE lessons SET downloaded=? WHERE id=?', ['1',getLessonId]);
});
response.data.map((item) => {
db.transaction((tx) => {
tx.executeSql('INSERT INTO questions (questionname,lessonname,answerbame,aoptionname,boptionname,coptionname,doptionname,eoptionname,lessonid,oldidq) VALUES (?,?,?,?,?,?,?,?,?,?)',
[item.QuestionName,item.LessonName,item.AnswerName,item.AOption,item.BOption,item.COption,item.DOption,item.EOption,item.id,item.Id]);
});
});
console.log("Tüm sorular başarıyla kayıt edildi.");
});
An image of the code
link
I'm not sure what is the problem, but I had the a similar problem with axios (server requests didn't work after deployment)
You should consider leave axios and try using fetch:
POST:
fetch('http://mywebsite.com/endpoint/', {
method: "POST",
headers: {
// Authorization: "Bearer " + Token,
Accept: 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
// sending data userID username, password, etc
}),
})
.then((response) => response.json())
.then((responseJson) => {
// Response will here
})
.catch((error) => {
alert(error);
});
GET:
fetch('http://mywebsite.com/endpoint/', {
method: "GET",
headers: {
// Authorization: "Bearer " + Token,
// OR USER name PASSworrd
Accept: 'application/json',
'Content-Type': 'application/json'
},
})
.then((response) => response.json())
.then((responseJson) => {
// Response will here
})
.catch((error) => {
alert(error);
});

deviceNotReady error : "Registration failed" react-native-twilio-programmable-voice

I am working on react native application and want to integrate the Phone masking feature like Uber do. I have choosen Twilio Phone Masking for this. I have used react-native-twilio-programmable-voice package.
I have integrated this using this link:: https://medium.com/#edzh1/create-a-twilio-voip-calls-in-a-react-native-app-35a729a9613d
I have done server setup successfully, using php. But getting error deviceNotReady error : "Registration failed". I have no idea what I am doing wrong here.
This is initial function I am calling here::
initTwilio = async () => {
const token = await this.getAuthToken();
if (Platform.OS === 'android') {
await this.getMicrophonePermission();
}
const success = await TwilioVoice.initWithToken(token);
if (success.initialized) {
TwilioVoice.addEventListener('deviceReady', () => {
this.setState({ twilioInited: true });
});
TwilioVoice.addEventListener('deviceNotReady', function (data) {
console.log('data', data) // getting error here
});
if (Platform.OS === 'ios') { //required for ios
TwilioVoice.configureCallKit({
appName: 'ReactNativeTwilioExampleApp',
});
}
}
};
getAuthToken = () => {
return fetch('https://myurl/accessToken.php', {
method: 'get',
})
.then(response => response.text())
.catch((error) => console.error(error));
}
Please help, and suggest me what I am doing wrong here.

React-Native Facebook Social Login behavior issue with Android kitkat 4.4

I have integrated facebook login and it is working fine on all versions above kitkat.
In kitkat there is a strange behavior when tapped on Facebook login button
it takes the app to background while loading.
Code I am using for login :
const doFacebookLogin = async dispatch => {
const { type, token } = await LoginManager.logInWithReadPermissions(["public_profile", "email", "pages_show_list"])
.then(
(result) => {
if (result.isCancelled) {
return dispatch({ type: FACEBOOK_LOGIN_CANCEL });
} else {
AccessToken.getCurrentAccessToken()
.then(async (data) => {
await setValue('fb_token', data.accessToken);
let facebookApiData = await initUser(data.accessToken);
await setValue('facebook_data', JSON.stringify(facebookApiData));
dispatch({ type: FACEBOOK_LOGIN_PROCRESSING});
// let response = await api.post('api/account/AddUser',JSON.parse('{"BrowserName":"MobileApp","BrowserVersion":"46", "Email":"'+ facebookApiData.email +'","FacebookID":"'+facebookApiData.id+'","FirstName":"'+facebookApiData.first_name+'","MiddleName":"'+facebookApiData.middle_name+'", "FullName": "'+facebookApiData.name+'", "Gender":"'+facebookApiData.gender+'","LastName":"'+facebookApiData.last_name+'", "ProfileLink":"'+facebookApiData.link+'","image":"'+facebookApiData.picture.data.url+'","Location":null}}'));
// await setValue('LoginId', response.LoginId);
return dispatch({ type: FACEBOOK_LOGIN_SUCCESS, payload: data.accessToken });
});
}
},
(error) => {
Alert.alert('Sign in error', error);
},
);
if (type === "cancel") {
return dispatch({ type: FACEBOOK_LOGIN_FAIL });
}
await setValue("fb_token", token);
return dispatch({ type: FACEBOOK_LOGIN_SUCCESS, payload: token });
};
Screenshot is attached
Dependencies I am using
"dependencies": {
"react": "16.4.0",
"react-native": "0.55.4",
"react-native-fbsdk": "^0.7"
},

React Native Fetch API - can't access json or body of response [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
Trying to call an API to my backend with Fetch, but I can't access the response body. There's a loot of different notation and syntax about this on the internet and I can't figure out how to do it properly.
I've tried response.json() and responseJson, and stringyfying both. I don't get what I want which is the actual body of the response. It's meant to have a key/token that I then save.
responseJson returns this: responseJson:
{"_40":0,"_65":0,"_55":null,"_72":null}
This is my function:
export function LogIn(em, pass) {
return (dispatch) => {
console.log('LogIn called');
dispatch(logInIsLoading(true));
//from phone
*fetch('http://192.168.1.18:8080/rest-auth/login/', {
method: 'POST',
headers: {
// 'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
'email': em,
'password': pass,
})
}).then((response) => {
console.log("response " + JSON.stringify(response));
if (!response.ok) {
console.log("ERROR: " + response.statusText);
throw Error(response.statusText);
}
dispatch(logInIsLoading(false));
return response;
})
.then((response) => {
responseJson = response.json();
console.log("responseJson: " + JSON.stringify(response.json()));
return responseJson
})
.then((responseJson) => {
AsyncStorage.multiSet([['key', responseJson.key], ['loggedIn', true]], () => {
console.log(responseJson.key);
dispatch(isLoggedIn(true));
dispatch(getKey(responseJson.key));
});
})*
.catch(() => dispatch(logInHasErrored(true)));
};
}
This is the response, but I can't get to the key in the body:
response {"type":"default","status":200,"ok":true,"headers":{"map":
{"allow":["POST, OPTIONS"],"set-cookie":
["csrftoken=DOMxD5IhNz5Vwm9a3niAR1tRyqBfNzUqnQMAEgk7AGwtwCgnRnZo9x0AMTM2IfK
q; expires=Fri, 22-Feb-2019 17:31:58 GMT; Max-Age=31449600; Path=/,
sessionid=er3fujv8ji96t41n1n8dlzb3zz1itwuj; expires=Fri, 09-Mar-2018
17:31:58 GMT; httponly; Max-Age=1209600; Path=/"],"content-type":
["application/json"],"content-length":["50"],"x-frame-options":
["SAMEORIGIN"],"vary":["Accept, Cookie"],"server":["WSGIServer/0.1
Python/2.7.14"],"date":["Fri, 23 Feb 2018 17:31:58
GMT"]}},"url":"http://192.168.1.18:8080/rest-auth/login/","_bodyInit":"
{\"key\":\"a9951fd6abff4fed35d9a8d1c275bf1212887513\"}","_bodyText":"
{\"key\":\"a9951fd6abff4fed35d9a8d1c275bf1212887513\"}"}
response.json() return Promise
AsyncStorage.multiSet - return Promise. Second parameter of multiSet is Function that will be called with an array of any key-specific errors found
export function LogIn(em, pass) {
return (dispatch) => {
console.log('LogIn called');
dispatch(logInIsLoading(true));
fetch('http://192.168.1.18:8080/rest-auth/login/', {
method: 'POST',
headers: {
// 'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
'email': em,
'password': pass,
})
}).then((response) => {
if (!response.ok) {
console.log("ERROR: " + response.statusText);
throw Error(response.statusText);
}
dispatch(logInIsLoading(false));
return response;
})
.then((response) => {
return response.json()
})
.then((responseJson) => {
console.log('responseJson', responseJson);
return AsyncStorage.multiSet([['key', responseJson.key],['loggedIn', true]], () => {
dispatch(logInHasErrored(true));
})
.then(() => {
dispatch(isLoggedIn(true));
dispatch(getKey(responseJson.key));
})
})
.catch(() => dispatch(logInHasErrored(true)));
};
}
This is pretty straight forward with axios.
First install axios by doing npm install --save axios
Then inside your Component do this:
handleInput = async() => {
const res = await axios.post('http://192.168.1.18:8080/rest-auth/login/', {
email: this.state.email,
password: this.state.password
});
const data = await res.json();
console.log(data);
}
Make sure you've stored email and password in this.state.email and this.state.password respectively and call handleInput when user presses the Submit button.
Don't forget to import axios import axios from 'axios'

React Native - Sending information so as to receive a response for simple login screen but receiving JSON parse error instead

I have tried several times to send the data and receive a response, but it does not seem to be sending the data put in by the user. I have tried going about this in several ways,I will share the code for the last two.
ONE
state = {
phoneNo: '',
pin: '',
isLoggingIn: false,
message: ''
}
_userLogin = () => {
console.log("userLogin");
this.setState({isLoggingIn: true, message:''});
var params = {
phoneNo: this.state.phoneNo,
pin: this.state.pin
};
var proceed = false;
fetch("https://"+"<url>", {
method: "POST",
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(params)
})
.then(
(response) => response.json())
.then((response) => {
if (response.status == 200) {
proceed = true;
}
else {
this.setState({ message: response.message });
console.log(message); }
})
.then(() => {
this.setState({ isLoggingIn: false })
if (proceed) this.props.onLoginPress();
})
.catch(err => {
console.log(err.message);
this.setState({ message: err.message });
this.setState({ isLoggingIn: false })
});
}
Two
The only difference here is how I am handling the response so I will only add that section. I thought that the issue might be due to syntax at this point.
.then(function(response){
return response.json();
})
.then(function(data){
console.log(data)
I have been through various tutorials, github and stackoverflow pages addressing the issue but I seem to be missing something. I keep getting a JSON parse error and I am convinced that perhaps the data is never being sent to the url because I get the error regardless of user input.
Both input fields have a ref and the button points to the user login function.
<TextInput
ref = {component => this._pin = component}
placeholder="pin"
onChangeText = {(pin) => this.setState({pin})}
secureTextEntry = {true}
onSubmitEditing={this._userLogin}
/>
<TouchableOpacity
onPress={this._userLogin}
title = "Submit"
disabled={this.state.isLoggingIn||!this.state.phoneNo||!this.state.pin}>
<Text style={styles.loginText}>Sign In</Text>
</TouchableOpacity>
try something like this.
I also get problem acceding both status code & data from fetch call, so i made "processResponse" function
processResponse=(response) =>{
const statusCode = response.status;
const data = response.json();
return Promise.all([statusCode, data]).then(res => {
return ({
statusCode: res[0], // the status code
data: res[1] // the data of the GET/POST returned by fetch call
})
}
);
}
_userLogin = () => {
console.log("userLogin");
this.setState({isLoggingIn: true, message:''});
var params = {
phoneNo: this.state.phoneNo,
pin: this.state.pin
};
fetch("https://"+"<url>", {
method: "POST",
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(params)
})
/*processResponse return both status and data , because when you make
.then((response) => response.json()) you return only data and status is removed
*/
.then(this.processResponse)
.then(res => {
console.log("response of fetch",res);
const { statusCode, data } = res;
if (statusCode > 200) {
this.props.onLoginPress()
}else{
this.setState({ message: data.message });
console.log("data message" , data.message);
}
this.setState({ isLoggingIn: false })
})
.catch(err=> {
console.error(err);
this.setState({ message: err.message});
this.setState({isLoggingIn: false})
});
});
}
AlainIb was very helpful and this helped contribute to what worked in the end. Using form data seemed to assist with the JSON Parse error. Hope this helps anyone else who is having any troubles.
state = {
message: ''
}
_processResponse = (response) =>{
const statusCode = response.status;
console.log("resp", response);
const data = response.json();
console.log("data", data);
return Promise.all([statusCode, data]).then(res => {
return ({
statusCode: res[0], // the status code
data: res[1] // the data of the GET/POST returned by fetch call
})
});
}
_userLogin = () => {
console.log("userLogin");
this.setState({isLoggingIn: true, message:''});
var params = {
phoneno: this.state.phoneno,
pin: this.state.pin
};
var formData = new FormData();
formData.append("phoneno", this.state.phoneno);
formData.append("pin", this.state.pin);
console.log(formData);
let data = {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type':'multipart/form-data'
},
body: formData
}
console.log(data);
fetch("https://"+"url", data)
.then(this._processResponse)
.then(res => {
console.log("response of fetch",res);
const { statusCode, data } = res;
if (statusCode == 200) {
console.log("in if statement");
if(data.login_success== 1){
console.log("name to be passed", data.name);
console.log("log in to profile");
this.props.navigation.navigate('ProfileRoute');
}else {
console.log("fail");
this.setState({message:"Password or Phone Number is Wrong"});
}
}else{
this.setState({ message: data.message });
console.log("data message" , data.message);
}
this.setState({ isLoggingIn: false })
})
.catch(err=> {
console.error(err);
this.setState({ message: err.message});
this.setState({isLoggingIn: false})
});
}

Categories

Resources