Paypal Express checkout error in production - reactjs

I am integrating Paypal express checkout with gatsby(reactjs) it's perfectly working fine with sandbox accounts but not in production. It gives me the following error
My code is
import React, { useState } from "react"
import PaypalExpressBtn from "react-paypal-express-checkout"
import notify from "../functions/notify"
import Api from "../functions/API"
import fbTrack from "../functions/fbTrack"
const client = {
sandbox: "sanbox_key",
production: "prod_key",
}
export default ({ plan, setUserData, setBillingHistory, setUserContact }) => {
const onSuccess = (payment) => {
const data = {
payment,
plan,
}
notify("The payment was succeeded!")
try {
fbTrack("track", "Purchase", plan.price)
} catch (e) {
// do nothing
}
// Sending the res call
Api.fetch("post", "make-payment-paypal", data).then(() => {
Api.fetch()
.then(user => {
setUserData(user)
})
Api.fetch("get", "get-contact")
.then(contact => {
setUserContact(contact)
})
Api.fetch("get", "get-billing-history")
.then(billing => {
setBillingHistory(billing)
})
}).catch(e => console.log(e))
}
const onCancel = (data) => {
notify("The payment was cancelled", "danger")
}
const onError = (err) => {
notify("Error occurred. Please retry.", "danger")
}
return <PaypalExpressBtn env={"production"} client={client} currency={plan.currency_code} total={plan.price} onError={onError}
onSuccess={onSuccess} onCancel={onCancel}/>
}
Response from network tab for /execute endpoint that gives 400
{
"ack": "contingency",
"contingency": "INSTRUMENT_DECLINED",
"meta": {
"calc": "e8cc408a47d1f",
"rlog": "rZJvnqaaQhLn%2FnmWT8cSUueWscmrtUHe5Y1Bd%2FeqyvyOTq66rSXAcvMRdZesXq1O38dITQfoakLPn1nG4pMu0qURH%2Be5YB%2B4_1709bb5bb49"
},
"server": "2mEzKB-B1lh9-OtP-2sBI96A-5Xu_ZnMt0Rz1fJ2a4n4noKlAHLadCNfrWklmy5YUKipx6UR0bGzcI9u9Q-a4b1v4LHPM9g6W4a6WmXYuh9wqhRDdbsHbYSzXX8ucZU3a4Xp-wZrSy6qYgnEZoDKzjuz_fjiBvxhxD2fNlGbF5tm_h_xd-G9FaYynEq4jwg1MYcCAXMgLLsxc2J81gNfe01GF7FRInwK5mbgWxtwed9fOwRRfBycXsn_diFRBuIJR7UEXAfmeZYIzkBATQbYfm"
}

{
"ack": "contingency",
"contingency": "INSTRUMENT_DECLINED",
"meta": {
"calc": "e8cc408a47d1f",
"rlog": "rZJvnqaaQhLn%2FnmWT8cSUueWscmrtUHe5Y1Bd%2FeqyvyOTq66rSXAcvMRdZesXq1O38dITQfoakLPn1nG4pMu0qURH%2Be5YB%2B4_1709bb5bb49"
},
"server": "2mEzKB-B1lh9-OtP-2sBI96A-5Xu_ZnMt0Rz1fJ2a4n4noKlAHLadCNfrWklmy5YUKipx6UR0bGzcI9u9Q-a4b1v4LHPM9g6W4a6WmXYuh9wqhRDdbsHbYSzXX8ucZU3a4Xp-wZrSy6qYgnEZoDKzjuz_fjiBvxhxD2fNlGbF5tm_h_xd-G9FaYynEq4jwg1MYcCAXMgLLsxc2J81gNfe01GF7FRInwK5mbgWxtwed9fOwRRfBycXsn_diFRBuIJR7UEXAfmeZYIzkBATQbYfm"
}
This means the card was declined.

Related

React Native + Firebase one time read doesn't resolve when logged in

I am creating an app with TypeScript + Firebase. I've followed this website to set it up: https://rnfirebase.io. After I finished with authentication I wanted to get a value from the real time database. However making the request doesn't resolve. I've also put it in the await version however that didn't resolve either.
import React, { useEffect } from "react";
import { Text } from "react-native";
import { firebase } from "#react-native-firebase/database";
import { REALTIME_DATABASE_ENV } from "react-native-dotenv";
const TestPage = () => {
useEffect(() => {
const reference = firebase
.app()
.database(REALTIME_DATABASE_ENV)
.ref("particularities/")
.once("value")
.then((snapshot) => {
console.log(`snapshot: ${snapshot.val()}`);
//expected result:
// {
// sickness: {
// label: "Sickness",
// },
// allergic: {
// label: "Allergic",
// },
// };
})
.catch((e: unknown) => {
console.log(`catch: ${e}`);
});
}, []);
return (
<Text>Test page</Text>
);
};
export default TestPage;
The rules that are applied to the real time database:
{
"rules": {
".read": false,
".write": false,
// ...
"particularities": {
".read": true,
".write": true,
},
}
}
Thing we found: logging out of the app does resolve all the requests made. Testing while logged in and all rules set to public gives the same result as before with the promise not resolving
As per the documentation here is how you can read the data once.
https://rnfirebase.io/database/usage#one-time-read
You don't need to pass database ref other than an 'us-central1'
import database from '#react-native-firebase/database';
database()
.ref('particularities/')
.once('value')
.then(snapshot => {
console.log('Data: ', snapshot.val());
})
.catch((e: unknown) => {
console.log(`catch: ${e}`);
});

message is not receiving from https://testfcm.com/ in react native android device

Push notification is not receiving in react native android device at first it was working but suddenly don't know what happenend..its not working..can anyone help me with this first file where i have generated the device token and second file for foreground
//notificationServices
import messaging from '#react-native-firebase/messaging';
import AsyncStorage from '#react-native-async-storage/async-storage';
export async function requestUserPermission() {
const authStatus = await messaging().requestPermission();
const enabled =
authStatus === messaging.AuthorizationStatus.AUTHORIZED ||
authStatus === messaging.AuthorizationStatus.PROVISIONAL;
if (enabled) {
console.log('Authorization status:', authStatus);
getFcmToken();
}
}
const getFcmToken = async () => {
let fcmToken = await AsyncStorage.getItem("fcmToken");
console.log(fcmToken,'token old');
if(!fcmToken) {
try {
const fcmToken = await messaging().getToken();
if(fcmToken){
console.log(fcmToken,'the new token');
await AsyncStorage.setItem("fcmToken",fcmToken)
}
}
catch (error) {
console.log(error,'error in fcmtoken');
}
}
}
export const notificationListener = async () => {
messaging().onNotificationOpenedApp(remoteMessage => {
console.log(
'Notification caused app to open from background state:',
remoteMessage.notification,
);
});
messaging()
.getInitialNotification()
.then(remoteMessage => {
if (remoteMessage) {
console.log(
'Notification caused app to open from quit state:',
remoteMessage.notification,
);
}
});
}
//foregroundhandler.js
import PushNotification, {Importance} from 'react-native-push-notification';
import messaging from '#react-native-firebase/messaging'
import React , {useEffect} from 'react'
const ForegroundHandler = () => {
const channel = new firebase.notifications.Android.Channel('test-channel', 'Test
Channel', firebase.notifications.Android.Importance.Max)
.setDescription('My apps test channel');
// Create the channel
firebase.notifications().android.createChannel(channel);
useEffect(() => {
const unsubscribe = messaging().onMessage((remoteMessage) => {
console.log("handle in foreground" , remoteMessage)
const {notification , messageId} = remoteMessage
PushNotification.createChannel(
{
channelId: "channel_id_1", // (required)
channelName: "My channel", // (required)
playSound: false, // (optional) default: true
soundName: "default", // (optional) See `soundName` parameter of
`localNotification` function
importance: Importance.HIGH, // (optional) default: Importance.HIGH. Int value of the Android notification importance
vibrate: true, // (optional) default: true. Creates the default vibration pattern if true.
},
(channelId) => console.log(`createChannel returned '${channelId}'`) // (optional) callback returns whether the channel was created, false means it already existed.
);
PushNotification.localNotification({
channelId:'channel_id_1',
id:messageId,
body:'android body',
title :'android notif title',
soundName:'default',
vibrate:true,
playSound:true
})
})
return unsubscribe
}, [])
return null
}
export default ForegroundHandler

Graphql useSubscription not giving response everytime

I am using Graphql useSubscription hook to hit a websocket api but there seems to be an issue. I am only receiving data when i enter the component for the first time or when i go back to some other component and come back again, when trying to refresh majority of the times I do not get the data.
Below is my setup for the following.
/* eslint-disable flowtype/no-types-missing-file-annotation */
import Cookies from 'js-cookie'
import { split, HttpLink, InMemoryCache, ApolloClient } from '#apollo/client'
import { setContext } from '#apollo/client/link/context'
import { WebSocketLink } from '#apollo/client/link/ws'
import { getMainDefinition } from '#apollo/client/utilities'
import { onError } from 'apollo-link-error'
import { ApolloLink } from 'apollo-link'
const env = process.env.NODE_ENV
const domain = env === 'development' ? 'localhost' : '.xyz'
const url = env === 'development' ? 'https://staging-xxx.xxxx.xx' : process.env.REACT_APP_API_URL;
const wsURL = env === 'development' ? 'wss://staging-xxx.xxxxx.xx/subscriptions' : process.env.REACT_APP_WSS_URL;
const httpLink = new HttpLink({
uri: url,
credentials: 'include'
})
const authLink = setContext((_: any, { headers }: any) => {
const app_token = Cookies.get('xxxxx', { domain: domain })
let token = app_token || 'insta-checkout'
return {
headers: {
...headers,
MUDEY_AUTH_TOKEN: token
}
}
})
const wsLink = new WebSocketLink({
uri: wsURL,
options: {
reconnect: true,
connectionParams: async () => {
const app_token = await Cookies.get('xxxxx', { domain: domain })
return {
credentials: 'include',
MUDEY_AUTH_TOKEN: app_token,
Authorization: 'Basic xxxxxxxxxxxxxxxxxxx'
}
}
}
})
const link = split(
({ query }: any) => {
const definition = getMainDefinition(query)
return definition.kind === 'OperationDefinition' && definition.operation === 'subscription'
},
wsLink,
authLink.concat(httpLink)
)
const client = new ApolloClient({
cache: new InMemoryCache(),
link: ApolloLink.from([link])
})
export default client
Now when i go my component for the first time, i am calling the subscriptions api by
import React from "react";
import { useMutation, useSubscription } from "#apollo/react-hooks";
export const NewComponent = () => {
const {
loading: loadingPackages,
data,
error,
} = useSubscription(SUBSCRIBE_CAR_PACKAGES, {
onSubscriptionData: useCallback((res: any) => {
const {
subscribeCarJourneyPackages: { message: stopWS, data: packagesResult },
} = res.subscriptionData.data;
if (packagesResult !== null) {
console.log("packarray", packagesResult);
setIsSubsLoading(true);
}
if (stopWS === "SUBSCRIPTION_COMPLETE") {
dispatch({ type: SET_ALL_PACKAGES, payload: packArray });
setIsSubsLoading(false);
} else {
// setIsSubsLoading(true)
}
}, []),
onError: useCallback((err: any) => {
apiErrorHandler(err);
}, []),
variables: { id: journeyID },
});
return null;
};
So the response i see is
But once i start refreshing the page , i only see
So what the issue in my frontend, for not getting the response 100% of the time ? should we need to close the connection everytime we receive response ?
Also i see the subscription api hitting even when i am in my homepage, where ideally it should hit in the results page where i want it, do this happens the moment we define connection and is it normal?
I know it's late but it maybe help someone else !
try giving fetchPolicy: 'cache-and-network' as option below your variables field.
like this :
variables: {... your variables },
fetchPolicy: 'cache-and-network'

Using ra-data-graphql with AppSync GraphQL API

I'm trying to use react-admin with AWS Amplify library and AWS AppSync SDK.
I can't wrap my head around how to use use ra-data-graphql/ra-data-graphql-simple with AWS AppSync API for querying/mutating data. Trying to do a very basic test with master/examples/demo from https://github.com/marmelab/react-admin/.
Any guidance will be appreciated.
Currently I'm trying to use dataProvider similar to below:
src/dataProvider/appsync.js:
import gql from 'graphql-tag';
import AWSAppSyncClient, { AUTH_TYPE } from 'aws-appsync';
import buildGraphQLProvider, { buildQuery } from 'ra-data-graphql-simple';
import { __schema as schema } from './schema';
const client = new AWSAppSyncClient({
url: "https://xxxx.appsync-api.us-east-1.amazonaws.com/graphql",
region: "us-east-1,
auth: {
type: AUTH_TYPE.AMAZON_COGNITO_USER_POOLS,
jwtToken: async () => (await Auth.currentSession()).getIdToken().getJwtToken(),
}
const myBuildQuery = introspection => (fetchType, resource, params) => {
const builtQuery = buildQuery(introspection)(fetchType, resource, params);
if (resource === 'listings' && fetchType === 'GET_LIST') {
return {
...builtQuery,
query: gql`
query getListings {
data: getListings {
items {
listingId
}
}
}`,
};
}
return builtQuery;
}
export default buildGraphQLProvider({ client: client, introspection: { schema }, buildQuery: myBuildQuery })
src/dataProvider/index.js:
export default type => {
switch (type) {
case 'graphql':
return import('./graphql').then(factory => factory.default());
case 'appsync':
return import('./appsync');
default:
return import('./rest').then(provider => provider.default);
}
};
src/App.js:
...
import dataProviderFactory from './dataProvider';
...
class App extends Component {
state = { dataProvider: null };
async componentDidMount() {
const dataProvider = await dataProviderFactory(
process.env.REACT_APP_DATA_PROVIDER
);
this.setState({ dataProvider });
}
...
src/dashboard/Dashboard.js:
...
fetchData() {
this.fetchListings();
}
async fetchListings() {
const { dataProvider } = this.props;
const { data: reviews } = await dataProvider(GET_LIST, 'listings');
console.log(listings)
}
...
Currently no data is returned from the API and the exception is thrown on await dataProvider(GET_LIST, 'listings'); saying call: [object Model] is not a function, however I see that buildGraphQLProvider promise was resolved succesfully to a function.
Can anyone suggest what I am doing wrong and what is the right way to approach the task?

Apollo subscription issue - updateQuery not firing

I have a functioning web socket created with Apollo's WebSocketLink interface. I managed to subscribe to an event using subscribeToMore and a message is pushed by the server (can see it in the network tab). Unfortunately updateQuery function is never triggered. I wonder whether it's the message structure that is incorrect (therefore a wrong server implementation) or is it something wrong in my client code.
For reference I added the message sent from server:
and here the graphql config for my component:
import { graphql } from "react-apollo/index";
import Insights from 'components/insights/Insights';
import gql from "graphql-tag";
import { withRouter } from "react-router-dom";
import get from 'lodash/get';
const query = gql`
query CampaignInsights($campaignId: ID) {
campaigns (id: $campaignId) {
edges {
node {
insights {
campaignPlanningInsight {
campaign
plannedTotals {
totalOptimizationRules
totalOfferGroups
totalOffers
}
liveTotals {
totalOptimizationRules
totalOfferGroups
totalOffers
}
}
}
}
}
}
}
`;
const insightsSubscription = gql`
subscription onInsightsUpdated($campaignId: ID) {
campaignPlanningInsightUpdated(id: $campaignId) {
id
plannedTotals {
totalOptimizationRules
totalOfferGroups
totalOffers
}
liveTotals {
totalOptimizationRules
totalOfferGroups
totalOffers
}
}
}
`;
const InsightsWithData = graphql(query, {
options: (props) => {
return {
variables: {
campaignId: props.match.params.campaignId
}
}
},
props: ({ data: { campaigns, subscribeToMore }, ownProps: { match }
}) => {
return {
insights: get(campaigns,
'edges[0].node.insights[0].campaignPlanningInsight', null),
subscribeToInsightsUpdate: () => {
return subscribeToMore({
document: insightsSubscription,
variables: {
campaignId: match.params.campaignId
},
updateQuery: (prev, { subscriptionData }) => {
debugger; // never gets here
if (!subscriptionData.data) {
return prev;
}
}
})
}
}
}
})(Insights);
export default withRouter(InsightsWithData);
I believe the issue might be the id of the graphql-ws websocket protocol.
That id needs to match the one sent by the frontend in the GQL_START message. Otherwise, the component won't re-render on a new message.
For more details, look into the subscription-transport-ws protocol

Resources