Why EXPO standalone app shows url_invalid? - react-native

i am working with Expo project using stripe react native , its work fine in local, publish but not working as expected in standalone app,
here i use stripe for payment and when i enter card info its returns erorr 400
400 Error
POST /v1/payment_intents/pi_3JSeHwSJwGztdZyL1BuqSJQq/confirm
"return_url": "myappname:///--/://safepay",
url_invalid - return_url Not a valid URL
here is my code :
<StripeProvider
publishableKey="xyz"
urlScheme={Linking.createURL('') + '/--/'}
setUrlSchemeOnAndroid = {true}
.............................../>
const handleDeepLink = useCallback(
async (url: string | null) => {
if (url && url.includes('safepay')) {
await handleURLCallback(url);
console.log('url',url)
navigation.navigate('Checkout', { url });
}
},
[navigation, handleURLCallback]
);
useEffect(() => {
const getUrlAsync = async () => {
const initialUrl = await Linking.getInitialURL();
handleDeepLink(initialUrl);
console.log('initialUrl',initialUrl)
};
const urlCallback = (event: { url: string }) => {
handleDeepLink(event.url);
};
getUrlAsync();
Linking.addEventListener('url', urlCallback);
return () => Linking.removeEventListener('url', urlCallback);
}, [handleDeepLink]);
how to achive deep link and how to resole this ?
Using: Standalone app, Expo 42, stripe-react-native :0.1.4

Related

DeviceNotRegistered: "ExponentPushToken[***]" is not a registered push notification recipient

I'm trying to implement expo push notifications on react native app built with expo !
I did everything mentioned on their docs ! i'm getting the token successfully but when i try sending a push notification to that token using their api or the tool they provide i get this error
DeviceNotRegistered: "ExponentPushToken[***]" is not a registered push notification recipient
This is how i'm getting the token !
export const useNotifications = () => {
const registerForPushNotificationsAsync = async () => {
if (Device.isDevice) {
const { status: existingStatus } =
await Notifications.getPermissionsAsync();
let finalStatus = existingStatus;
if (existingStatus !== "granted") {
const { status } = await Notifications.requestPermissionsAsync();
finalStatus = status;
}
if (finalStatus !== "granted") {
alert("Failed to get push token for push notification!");
return;
}
const token = (await Notifications.getExpoPushTokenAsync()).data;
console.log("TOKEN------------", token);
alert(token);
} else {
alert("Must use physical device for Push Notifications");
}
if (Platform.OS === "android") {
Notifications.setNotificationChannelAsync("default", {
name: "default",
importance: Notifications.AndroidImportance.MAX,
vibrationPattern: [0, 250, 250, 250],
lightColor: "#FF231F7C",
});
}
};
const handleNotification = (notification = Notifications.Notification) => {
// could be useful if you want to display your own toast message
// could also make a server call to refresh data in other part of the app
};
// This listener is fired whenever a user taps on or interacts with a notification (works when app is foregrounded, backgrounded, or killed)
const handleNotificationResponse = (
response = Notifications.NotificationResponse
) => {
const data = ({ url } = response.notification.request.content.data);
if (data?.url) Linking.openURL(data.url);
};
return {
registerForPushNotificationsAsync,
handleNotification,
handleNotificationResponse,
};
};
useEffect(() => {
registerForPushNotificationsAsync();
Notifications.setNotificationHandler({
handleNotification: async () => ({
shouldShowAlert: true,
shouldPlaySound: false,
shouldSetBadge: true,
}),
});
const responseListener =
Notifications.addNotificationResponseReceivedListener(
handleNotificationResponse
);
return () => {
if (responseListener) {
Notifications.removeNotificationSubscription(responseListener);
}
};
}, []);
i run the eas build eas build -p android --profile preview so i can test it on a real device since push notifications works only on real devices and after that i pushed the cloud messaging server key that i got from my firebase project with this command expo push:android:upload --api-key <your-token-here>
As i said i successfully get the token but the i get the error when trying to send the notification!
am i missing a step or something ?
I tried run the build on two devices and both not working !

Twitch API 401 error with React Native Expo

I'm trying to get user info from Twitch with React Native Expo, but it always returns 401 error.
I found that it correctly gets the OAuth token, but the problem occurs after it.
Here's my code:
WebBrowser.maybeCompleteAuthSession();
// Endpoint
const discovery = {
authorizationEndpoint: 'https://id.twitch.tv/oauth2/authorize',
tokenEndpoint: 'https://id.twitch.tv/oauth2/token',
revocationEndpoint: 'https://id.twitch.tv/oauth2/revoke',
};
// Login Screen
export function loginScreen({ navigation }) {
const [request, response, promptAsync] = useAuthRequest(
{
responseType: ResponseType.Token,
clientId: '(deleted)',
// For usage in managed apps using the proxy
redirectUri: makeRedirectUri({ useProxy: true }),
scopes: ['openid', 'user_read', 'user_subscriptions'],
},
discovery
);
React.useEffect(() => {
if (response?.type === 'success') {
fetch('https://api.twitch.tv/kraken/user', {
method: 'GET',
headers: {
'Accept': 'application/vnd.twitchtv.v5+json',
'Client-ID': '(deleted)',
'Authorization': 'OAuth ' + response.params
}
})
.then((data) => {
AsyncStorage.setItem('userData', JSON.stringify(data))
.then(() => console.log(JSON.stringify(data))) // console.log for testing
.then(() => navigation.navigate('Home'))
})
.catch((err) => alert(err))
}
}, [response]);
and I referred to this document for the authentication.
Twitch SignIn & get user information using Expo's expo-auth-session.
Step 1: Create an account and enable two-factor authentication on Twitch developer site.You will get a key.
Step 2: Install Expo's expo install expo-auth-session
Step 3: Add Scheme in App.json file
{
"expo": {
"scheme": "myapp"
}
}
In order to be able to deep link back into your app, you will need to set a scheme in your project app.config.js, or app.json, and then build your standalone app (it can't be updated with an OTA update). If you do not include a scheme, the authentication flow will complete but it will be unable to pass the information back into your application and the user will have to manually exit the authentication modal (resulting in a cancelled event).
Step 4:
import * as AuthSession from 'expo-auth-session';
// To fetch twitch user information
const getTwitchUserInformation = twitchToken => {
const url = 'https://api.twitch.tv/helix/users';
const header = {
Authorization: `Bearer ${twitchToken}`,
'Client-ID': SOCIAL_CONSTANTS.TWITCH_CLIENT_ID,
};
fetch(url, {
method: 'GET',
headers: header,
})
.then(response => response.json())
.then(response => {
const userResponse = response && response.data[0];
console.log(userResponse);
})
.catch(error => {
console.log(error);
});
};
const signInWithTwitch = async () => {
const redirectUrl = AuthSession.getRedirectUrl();
const authUrl = `https://id.twitch.tv/oauth2/authorize?client_id=${ENTER_CLIENT_ID_HERE}&redirect_uri=${redirectUrl}&response_type=token&scope=user:edit+user:read:email&force_verify=true`
const {type, params} = await AuthSession.startAsync({authUrl});
if (type === 'success') {
const {access_token, token_type} = params;
getTwitchUserInformation(access_token);
}
};
Link - https://medium.com/#rakesh.medpalli/twitch-signin-get-user-information-in-expo-using-expo-auth-session-a6a74812c096

React Native: Failed to execute 'append' on 'FormData': parameter 2 is not of type 'Blob'. at new ApolloError

I am trying to upload image from my react native app to graphql by using Apollo client with createUploadLink(). When I am trying to mutate data by passing a ReactNativeFile as a variable, then it says
"network request failed: Failed to execute 'append' on 'FormData': parameter 2 is not of type 'Blob'. at new ApolloError ".
This this the mutation which i am trying to use
mutation publishPost(
$content: String!
$LocationInput: LocationInput!
$InputPostAttachment: [InputPostAttachment!]
) {
publishPost(
content: $content
location: $LocationInput
attachments: $InputPostAttachment
) {
content
}
}
InputPostAttachment has type
type InputPostAttachment {
type: PostAttachmentType!
file: Upload!
}
Apollo client settings and i am using apollo-upload-client
const httpLink = createUploadLink({
uri: 'http://localhost:8000/graphql',
});
const authLink = setContext(async (headers: any) => {
const token = await getToken();
return {
...headers,
headers: {
authorization: token ? `Bearer ${token}` : null,
},
};
});
const link = authLink.concat(httpLink);
// create an inmemory cache instance for caching graphql data
const cache = new InMemoryCache();
// instantiate apollo client with apollo link instance and cache instance
export const client = new ApolloClient({
link,
cache,
});
File upload Function and i am using react-native-image-crop-picker for multi image selection
const [image, setimage] = useState([]);
const _pickImage = () => {
ImagePicker.openPicker({
includeBase64: true,
multiple: true,
}).then((images: any) => {
let imageData: any = [];
images.map((data: any) => {
const file = new ReactNativeFile({
uri: data.path,
name: data.filename,
type: data.mime,
});
imageData.push({
type: 'IMAGE',
file: file,
});
});
setimage(imageData);
console.log(images);
});
};
const handlePost = async () => {
const InputPostAttachment: any = [...image];
const LocationInput = {
place: place,
vicinity: vicinity,
province: province,
};
publishPost({variables: {content, LocationInput, InputPostAttachment}})
.then(({data}) => {
console.log(data);
props.navigation.navigate('Home');
})
.catch((err) => {
console.log('err happened');
console.log(err);
});
};
could someone please help me out from this?
In addition to the chrome debugger issue, this error also happens on the expo web.
To anyone uploading images on expo web (or react-native web), here's a working solution:
/** Load image from camera/roll. */
const result = await ImagePicker.launchImageLibraryAsync({
mediaTypes: ImagePicker.MediaTypeOptions.All,
allowsEditing: true,
quality: 1,
});
if (result.cancelled) {
return;
}
/** web platform: blob. */
const convertBase64ToBlob = async (base64) => {
const response = await fetch(base64);
const blob = await response.blob();
return blob;
};
/** android/ios platform: ReactNativeFile.*/
const createReactNativeFile = (uri) => {
const file = new ReactNativeFile({
uri,
type: mime.lookup(uri) || 'image',
name: `file-${Date.now()}`,
});
return file;
};
/** Use blob for web, ReactNativeFile otherwise. */
const file = Platform.OS === 'web'
? await convertBase64ToBlob(result.uri)
: createReactNativeFile(result.uri);
/** Upload image with apollo. */
mutate({ variables: { file } });
On the web platform, ImagePicker returns a base64 value instead of a file path. This problem doesn't happen if the platform is Android or iOS, as ImagePicker returns a file path, which is expected by apollo-upload-client.
The solution is to detect if the URI is base64 (which happens when the platform is "web") and convert it to a blob.
My apollo-client was configured using apollo-boost and i was using chrome debugger to intercept the network was causing me this issue.
To be more specific I was using the below code to get the network requests sent by my app in the chrome debugger
global.XMLHttpRequest =
global.originalXMLHttpRequest || global.XMLHttpRequest;
global.FormData = global.originalFormData || global.FormData;
if (window.FETCH_SUPPORT) {
window.FETCH_SUPPORT.blob = false;
} else {
global.Blob = global.originalBlob || global.Blob;
global.FileReader = global.originalFileReader || global.FileReader;
}
apollo-upload-client wont send the data in multipart data if we are using chrome debugger. We will face network issue.This issue has the answer. or I had not removed apollo-boost and some part of my app was using it that was also a issue.

Twilio voice call not working in react native

I am trying to using react-native-twilio-programmable-voice library for use Twilio voice call. I implemented library and setup code from server end I received access token and used this in below code:
initTwilio = async () => {
const token = await this.getAuthToken();
if (Platform.OS === 'android') {
await this.getMicrophonePermission();
}
await TwilioVoice.initWithToken(token);
TwilioVoice.addEventListener('deviceReady', () => {
console.log("device Ready");
this.setState({ twilioInited: true });
});
if (Platform.OS === 'ios') { //required for ios
TwilioVoice.configureCallKit({
appName: 'ReactNativeTwilioExampleApp',
});
}
};
makeCall = () => TwilioVoice.connect({ To: '+919929294578' });
When I press I didn't get "device ready" in output and nothing happened if anyone did that please advice so I can complete...Thanks!

react-native-linkdin-login is not working in ios?

I am using react-native-linkdin-login library to support linkding sigin in my application.It is working properly in android but in iOS it always ask to download an application rather than application already exist in device and redirect to the APP store. When I open and login to linkdin account, I can't come back to my react-native application, with user profile details.
Give me any suggestion as soon as possible.
async componentWillMount() {
LinkedinLogin.init(
[
'r_emailaddress',
'r_basicprofile'
]
);
}
async handleLinkedinLogin(){
LinkedinLogin.login().then((user) => {
alert("linkdin");
this.setState({ user : user });
this.getUserProfile();
}).catch((e) => {
var err = JSON.parse(e.description);
alert("ERROR: " + err.errorMessage);
alert('Error', e);
});
return true;
}
getUserProfile(user) {
LinkedinLogin.getProfile().then((data) => {
const userdata = Object.assign({}, this.state.user, data);
this.setState({ user: userdata });
const Email = userdata.emailAddress;
const Fullname = userdata.firstName+' '+userdata.lastName;
const SocialAppId = userdata.id;
const SignupType = 'Linkedin';
alert("Please wait....")
this.socialLogin(Fullname,Email,'null',SignupType);
}).catch((e) => {
alert(e);
});
}