Using Lambda/API Gateway in ReactJS - reactjs

I have a frontend that I designed in ReactJS on AWS Amplify with my Senior Project team and am looking to bring in data from API Gateway. I have a link I deployed that I tested in Lambda on the AWS console which works correctly. I am looking for some guidance on pulling in the data from that url to the frontend to use for a list. I can supply more information if you would like, please let me know what you need and any tips would be great! Thank you.

Assumption :
As mentioned in your question i assume that you already aware how to create API Gateway,deploy API and now you have API gateway url to access rest API.
Fetch data into react :
Example you have following cruds API
GET /students List all students
GET /students/1 Load a studentsby id
POST /students Create a students
PUT /students Update a students
DELETE /students/1 Delete a students by id
Fetching data:
import { API } from 'aws-amplify';
API.get('students', '/students', {}).then(result => {
this.todos = JSON.parse(result.body);
}).catch(err => {
console.log(err);
})
Security :
You need to secure rest API either use API key or Authorizer
https://github.com/vaquarkhan/aws-amplify-workshop-react
https://www.freecodecamp.org/news/going-serverless-with-react-and-aws-amplify-part-2-creating-and-using-serverless-services-d401ba346eeb/
https://gerard-sans.medium.com/create-a-rest-api-integrated-with-amazon-dynamodb-using-aws-amplify-and-vue-5be746e43c22

Related

Correct way to consume 3rd party API with query in Django + React (Backend + Frontend)

I'm using Django on my backend and React on my frontend. I want to consume the OpenWeatherMap API. For security reasons, I want to keep my API key on the backend. Currently, I have this working on my Django app. When a POST request is made, the Django view renders the information required from OpenWeatherMap. How can the user type the query in React, send the query to to the backend and get the results on the frontend?
I have a very hacky way of doing this currently:
I POST (using axios) the city that the user enters in React to a REST API that I built in Django.
The backend queries the OpenWeatherMap API with the city that the user enters and POSTs the data that it gets from OpenWeatherMaps back to my API.
After this, the frontend uses a GET request on my API to show the information to the user.
I'm pretty sure this isn't the correct way to do this but I couldn't find any other questions on this, and I'm pretty new to web development.
First two steps are just fine. Instead of step 3. return the response from OpenWeather as a response to POST request from step 1. and resolve it in your React code.
On the second thought and to be fine with REST guidelines:
use GET to call your API with user's provided city name (POST is usually called to create a new resource - it's just a convention)
inside your API call OpenWeatherMap API with the city name
return the result to your React app as a response to GET from point 1.
More on REST API guidelines: https://restfulapi.net/

Reading returned data from Stripe OAuth Redirect-URI (Stripe OAuth, Firebase back-end, React front-end)

I am completely stuck trying to figure out how to allow users to sign up a "Connected Account" via Stripe OAuth steps for my website. (I'm building a marketplace website with React front-end, Firebase back-end, and Stripe to handle payments).
Some guides I have been trying to use to help guide me are as follows:
(1) https://stripe.com/docs/connect/collect-then-transfer-guide : I am stuck on this guide at step 2.2. However this guide is not as helpful since I am using Firebase as my backend.
(2) https://medium.com/#c.nwaugha/integrate-stripe-payment-with-firebase-cloud-functions-part-2-e381babd39bc : I am stuck on this guide at around 1/3rd up the page (see yellow text of image below)
Unfortunately I'm not sure what my Stripe Redirect URI should be. I currently have it set to something similiar to "https:MyWebsiteName.com/oauth_redirect" on my Stripe settings, however this link doesn't have a React front-end yet and am not sure what code it should contain.
Simply put, how can I continue the OAuth setup process and pull the data from a returned URL. Any clarity is greatly appreciated. (PS: I did look into "Regex" as the guide suggests, but am unable to find anything that appears to be useful for this case).
UPDATE and PARSING URL SOLUTION
Thanks to hmunoz's advice, I was able to parse through the returned URL and capture the stripe OAuth Authorization Code in a string. (Please see the code below).
This is returned when this page "https://.../oauth_return" URI is reached after the user finishes the OAuth forms on stripe.
import React from 'react';
import queryString from 'query-string'; //this is a 3rd party library that is used to parse through the Redirect URL returned from Stripe.
const oauth_redirect = () => {
//Parsing over URL
const value=queryString.parse(window.location.search);
//Retrieves the "code" value.
const code=value.code;
console.log('code:', code)
//Retrieves the "state" value.
const state=value.state;
console.log('state:', state)
... //(I'm not sure how to pass these strings into a Firebase HTTP function).
}
export default (oauth_redirect)
CURRENT PROBLEM; BUILDING FIREBASE HTTP FUNCTION USING JAVASCRIPT
I am trying to build a Firebase HTTP function that uses the POST method, to return this Authorization Code. I have a function inside "index.js" of the functions/src directory of this react website. Unfortunately all of the guides on this subject have the firebase function is .typescript and I am using .javascript. Any clarity on how build this HTTP function in .javascript would be greatly appreciated!!!
Please note: I clarified the question a bit in the following post :Returning Authorization Code to Stripe using Firebase HTTP Function (Firebase, Stripe OAuth, React (JSX) frontend)
The redirect_uri in this case is the final page that you want your user to land on, once they have authenticated via Stripe.
This would have to be a web page of yours, say https://your-website.com/oauth-complete
Once on this page, your React code needs to grab the URL parameter like code: ac_123 which is the authorization code, and call a Firebase function with that authorization code.
Your Firebase function will complete the OAuth connection to this Connect account by consuming the OAuth token.
These two steps are described here: https://stripe.com/docs/connect/oauth-standard-accounts#redirected
Not sure if I've arrived too late. You can start simple uncommeting the example from the index.js in /functions.
You can test running firebase emulators:start from your terminal.
It might start in the localhost:5001/project-name/zone/newFunction
exports.newFunction = functions.https.onRequest( (req, res) => {
// your logic code here
}

Can I fulfill purchases made through Stripe Checkout Client in React without a server?

I am using the Client integration of Stripe Checkout in my create-react-app React app.
Purchasing works fine, but it seems like I have no option to search for successful payments or receive relevant information after a payment.
(Stripe Checkout Fulfilment Options)
Stripe Checkout is implemented like this:
import React, { Component } from 'react';
const stripe = window.Stripe('INSERT_API_KEY');
class Checkout extends Component {
checkout() {
stripe.redirectToCheckout({
items: [
{plan: 'INSERT_PLAN_ID', quantity: 1}
],
successUrl: 'https://localhost:3000/checkout/success',
cancelUrl: 'https://localhost:3000/checkout/success'
}).then((result) => {
// If `redirectToCheckout` fails due to a browser or network
// error, display the localized error message to your customer
// using `result.error.message`.
console.log(result)
});
}
render() {
return (
<button onClick={this.checkout}>Pay</button>
)
}
}
The success/cancel urls don't help me a lot because I can't think of a security mechanism that would only give access to users who actually made a payment.
Do you have any ideas?
Of the options for fulfilling purchases, the most reliable path is to write a backend and use server code. That said, if you feel really strongly about avoiding writing server code, I’d recommend working with a third-party plugin like Zapier to handle successful purchases and sending those into a spreadsheet or another tool that you use to manage fulfillments.
Use Stripe+Zapier to trigger workflows based on common activities in Stripe like getting a new customers, receiving a new payment, and more. https://stripe.com/works-with/zapier
Polling from the client is not recommended for a number of reasons.

Checkbox Subscribe for MailChimp with React JS web application

I'm trying to integrate a MailChimp checkbox opt-in feature on an existing React form. The entire site is a React web application. I've been checking around for solutions for hours, but still can't find anything. Any ideas?
You should use Mailchimp 3.0 API
Create an API key here: https://admin.mailchimp.com/account/api/
Send a POST request to the following endpoint with your user data
Endpoint:
https://<data_center>.api.mailchimp.com/3.0/lists/<list_id>/members/
Structure of data to send:
{
"email_address": "urist.mcvankab#freddiesjokes.com",
"status": "subscribed",
"merge_fields": {
"FNAME": "Urist",
"LNAME": "McVankab"
}
}
You can get the data_center for your Mailchimp account when you enter to your dashboard, in the web browser check the URL. If for example, you have https://us7.admin.mailchimp.com/account/api/ your data_center will be us7.
And to obtain the list_id of the list you want your users to subscribe, check the following link as there are several ways to obtain it: Find your list ID
After that you just have to handle the data for your subscriber into React state and send it on your form submit.
For more details, check Mailchimp API 3.0 documentation here

Getting No response from google drive javascript api

I'm using google drive javascript api(v2) in my reactjs project.
And I'm using this function to get files from google drive.
this.getProjectObjects = function(query, callback)
{
var request = gapi.client.drive.files.list({
corpus : 'DEFAULT',
q : query,
fields : 'items(id,description,title,properties)'
});
request.then(function(resp) {
callback(resp.result.items)
}, function(err) {
console.log(err)
});
};
After authenticate the user, I can get the files using this function.
But, when I navigate to other react component, it's no longer working.
There is no response or error, api just hangs.
Silly thing is when I refresh page, it's working. Again if I navigate to other component, it's not working.
I'm using the same query, nothing changed during navigating.
Anyone have any ideas what the issue could be?
Thanks
You may want to check the Chrome devTools to see if you are encountering any problem when switching pages. Also in the documentation - Getting Started:
There are several ways to use the JavaScript client library to make API requests, but they all follow the same basic pattern:
The application loads the JavaScript client library.
The application initializes the library with API key, OAuth client ID, and API Discovery Document(s).
The application sends a request and processes the response.
The following sections show 3 common ways of using the JavaScript client library.
Option 1: Load the API discovery document, then assemble the request.
Option 2: Use gapi.client.request
Option 3: Use CORS
See the sample for code implementation on effectively loading and making API calls.
Hope this helps.

Resources