Setup Checkout Rest API for Shopify from react mobile app - react-native

I am new to shopify, can anyone help me how to setup the checkout API for shopify. I am creating a mobile app with react for a shopify website using API. I tried the one in the shopify docs but it return some error.
post: https://{apikey}:{password}#{hostname}/admin/api/2020-10/checkouts.json
body raw json
{
"checkout": {
"line_items": [
{
"product_id": 5584792125605,
"variant_id": 35877399986341,
"quantity": 1
}
]
}
}
header
X-Shopify-Access-Token : storefront access token
Response
{
"errors": "[API] Invalid API key or access token (unrecognized login or wrong password)"
}
But I've given API key and access token correctly. Is there anything else i should do( I tested this in postman)

Using react native, you have to give the apikey and the password in the Header like this.
getShopifyOrders = () => {
let authorization = base64.encode(
'${Constants.Shopify.key}:${Constants.Shopify.password}'
);
fetch(
'https://${Constants.Shopify.admin_url}/admin/api/2021-04/orders.json',
{
method: "get",
headers: new Headers({
Authorization: 'Basic ${authorization}',
}),
}
)
.then((response) => response.json())
.then((json) => {
console.log(json);
})
.catch((error) => {
console.error(error);
});
};
With Constants.Shopify.key = 'Your_api_key' and Constants.Shopify.password = 'Your_password'
Note : In this code, you have to replace the ' with backsticks ;)

Related

DialogFlow -CX with React Native

Is there any way to implement DialogFlow-cx directly with React native App as DialogFlow ES version does?
I am trying with the REST API also But not working.
I want to Call the Dialogflow CX API from my React-Native App.But I am getting 404, I have downloaded the private key as a JSON file from the service Account also.
Here is a sample code that I have tried
let data = {
"queryInput": {
"text": {
"text": "Hi!"
},
"languageCode": "en"
},
"queryParams": {
"timeZone": "Asia/Colombo"
}
}
fetch(DEFAULT_BASE_URL + this.projectId +"/locations/"+ this.location + "/agent/"+ this.agentId +"/sessions/" + this.sessionId + ":detectIntent", {
method: "POST",
headers: {
'Content-Type': 'application/json; charset=utf-8',
'Authorization': 'Bearer ' + this.accessToken,
'charset': "utf-8"
},
body: JSON.stringify(data)
})
.then(function (response) {
console.log("RESPONSE=== ");
console.log(response);
// var json = response.json().then(onResult)
})
.catch(onError);
};
I changed the agent to agents in URL and it worked.
Here is a reference doc From Google https://cloud.google.com/dialogflow/cx/docs/quick/api

csrf issue in fetch API call from react native

I am using the following code from react-native mobile application to make a social authentication call to dj-rest-auth local link. However my Facebook authentication succeeds each time and then the fetch (or axios) local API call executes, which runs perfectly for the first time/run returning me the token but thereafter on every other runs, it gives me an error saying missing or invalid csrf token. I can't used the Django docs getCookie function as it gives Document error since this is a react-native mobile application. Please guide how to properly have API calls using csrf from the mobile app, with the code being used below (which is inside an async function):
fetch(
"http://192.168.1.102:8080/dj-rest-auth/facebook/",
{
method: "POST",
headers: {
'Accept': 'application/json',
'Content-Type':'application/json',
},
xsrfCookieName:"csrftoken",
xsrfHeaderName:'X-CSRFToken',
body:JSON.stringify({access_token:resolvedToken})
}
)
.then(resp => resp.json())
.then(data => {
console.log(data);
}
)
.catch(error => console.log(error))
The logout function also give the missing or invalid csrf error, which is written below for reference:
async function Logout() {
fetch(
"http://192.168.1.102:8080/dj-rest-auth/logout/",
{
method: "POST",
headers: {
'Accept': 'application/json',
'Content-Type':'application/json',
},
xsrfCookieName:"csrftoken",
xsrfHeaderName:'X-CSRFToken'
}
)
.then(resp => resp.json())
.then(data => {console.log(data)})
.catch(error => console.log(error))
}
The issue above is resolved by removing "Session Authentication" from your default REST authentication classes in settings.py and keeping the "Basic Authentication" and "Token Authentication" enabled.
'rest_framework.authentication.BasicAuthentication',
'rest_framework.authentication.TokenAuthentication',
Source: https://github.com/Tivix/django-rest-auth/issues/164#issuecomment-860204677

Getting "Request had insufficient authentication scopes." 403 error code while importing contact from Gmail using ionic 5 & Angular 11

I am using ionic 5 and Angular 11. I want to import contacts from Gmail and display it in a ion-list.
To get the access token I am using Google-plus plugin .Below is my code to get the access token. After getting access token I am using https://developers.google.com/people/api/rest/v1/people.connections/list API to get the contacts name, phonenumber and emailAddresses.
import { GooglePlus } from '#ionic-native/google-plus/ngx';
import { HttpClient, HttpHeaders } from '#angular/common/http';
constructor(private googlePlus: GooglePlus, private http: HttpClient) { }
getContactFromGmail() {
const param = {
'scopes': 'https://www.googleapis.com/auth/contacts.readonly',
'webClientId': My webClientId,
'offline': true
};
this.googlePlus.login({ param })
.then(res => {
console.log(res);
if (res) {
let accessToken = res.accessToken;
const httpOptions = {
headers: new HttpHeaders({
'Accept': 'application/json',
'Authorization': `Bearer ${accessToken}`
})
};
var url = 'https://people.googleapis.com/v1/people/me/connections?personFields=names,emailAddresses,phoneNumbers&key=My_API_KEY'
console.log(url)
this.http.get(url, httpOptions);
}
}).catch(err => {
console.error(err)
}
}
But this is giving me 403 error.
{
"error": {
"code": 403,
"message": "Request had insufficient authentication scopes.",
"status": "PERMISSION_DENIED"
}
}
Can anybody please help me how to solve this.

How to get user email using Google Sign In expo Auth Session?

At moment im using this snippet of code to sign in to google, but i cant get user email… anyone know how to do this?
var LoginGoogle = () => {
const [request, response, promptAsync] = Google.useAuthRequest({
androidClientId: 'xxxxxxx.apps.googleusercontent.com',
expoClientId: 'xxxxxxx.apps.googleusercontent.com'
},{
scopes: ["email"]
},{});
React.useEffect(() => {
if (response?.type === 'success') {
const { authentication } = response;
console.log(response);
}
}, [response]);
return (
<GoogleSocialButton disabled={!request} onPress={() => {promptAsync()}} />
)
}
response returns object with links instead of email
I wish this is written in the expo docs. I would like to add a few points from the first answer:
First if you need code snippets on how to fetch user data after getting the access token, you can refer to this github issue: https://github.com/expo/expo/issues/8384
access token can be received by the following code after receiving the response object:
const { authentication: { accessToken } } = response;
then, you can create a function like this:
async function fetchUserInfo(token) {
const response = await fetch('https://www.googleapis.com/oauth2/v3/userinfo', {
method: 'GET',
headers: {
Accept: 'application/json',
Authorization: `Bearer ${token}`,
'Content-Type': 'application/json'
},
});
return await response.json();
}
and get the user object (which contains the user email, profile, photo, etc) by something like this inside an async function:
const user = await fetchUserInfo(accessToken);
But NOTE for the user object, using https://www.googleapis.com/oauth2/v2/userinfo and https://www.googleapis.com/oauth2/v3/userinfo, will yield slightly different result/object ; in particular for v3, since Google implements the OpenID Connect API, there is no "id" attribute anymore, "id" will be called "sub".
sources:
How to identify a Google OAuth2 user?
https://developers.google.com/assistant/identity/google-sign-in-oauth
https://github.com/expo/expo/issues/8384
Example of a user object in v3:
Object {
"email": "xxxxx#gmail.com",
"email_verified": true,
"family_name": "John Deer",
"given_name": "John",
"hd": "gmail.com",
"locale": "en",
"name": "John Deer",
"picture": "https://lh3.googleusercontent.com/a/asdfjasdklfjaslkf",
"sub": "10998837733652322",
}
Hope this helps someone in the future...!
EDIT: if you need the id_token checkout this one:
expo-auth-session/providers/google Google.useAuthRequest
I am using AuthSession as well in my RN app and I stumbled with this problem. After going through Google API Docs, found out you can pass the access token from the useAuthRequest response to https://www.googleapis.com/oauth2/v3/userinfo?access_token= ACCESS_TOKEN.

Redirect_uri mismatch in fetch and gapi

working on connecting users to google, and we're trying to get their access and refresh tokens from the google api, and we're getting an issue exchanging the OAuth2 Code for tokens. Both sets of code have the same error.
I initialize the gapi client and fill in the information needed like so:
gapi.load('client:auth2', _ => {
gapi.client.init({
'apiKey': 'omitted for security',
clientId: 'omitted for security',
'scope': 'https://www.googleapis.com/auth/drive',
'discoveryDocs': ['https://www.googleapis.com/discovery/v1/apis/drive/v3/rest']
}).then(_ => {
gapi.auth2.getAuthInstance().grantOfflineAccess().then(resp => {
if(resp.code){
gapi.client.request({
path: 'https://www.googleapis.com/oauth2/v4/token',
method: 'post',
params: {code: resp.code},
body: {
code: resp.code,
client_id: opts.clientId,
client_secret: 'omitted for security',
grant_type: 'authorization_code',
redirect_uri: 'omitted for security',
access_type: 'offline'
},
}).then((onfulfill, onreject, context) => {
console.log('fulfilled', onfulfill);
console.log('rejected: ', onreject);
console.log('context', context);
}).catch(err => console.error(err.body));
}
});
});
});
What I'm trying to do in the .then() is to call the token endpoint to exchange the code in the response for a refresh and access token to store in my back end and the user's local storage.
I get this error response from both versions of the code. (better, more reliable code is provided here.)
{ "error": "redirect_uri_mismatch", "error_description": "Bad
Request" }
I also have a backend setup stashed as a last resort that accepts the code from gapi.auth2.getAuthInstance().grantOfflineAccess() calls the token endpoint, and returns the access_token and refresh_token to the client.
This code is similar, but not quite. instead of using the google api library, I used fetch, and it works fine. (Fetch and XHR on the front end have the same issues as the gapi.client.request function....)
const gConfig = require('./basic.json');
const scopes = ['https://www.googleapis.com/auth/drive'];
const { client_id, client_secret, redirect_uris } = gConfig.web;
const authClient = new google.auth.OAuth2(client_id, client_secret, redirect_uris[0]);
app.post('/', (req, res) => {
const { code } = req.body;
console.log('Received Code From Request: ', code);
let data = { code , client_id, client_secret,redirect_uri: redirect_uris[0], grant_type: 'refresh_token'};
let encodedParams = Object.keys(data).map(k => encodeURIComponent(k) + '=' + encodeURIComponent(data[k])).join('&');
fetch(
`https://www.googleapis.com/oauth2/v4/token?code=${code}`,
{ method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, body: encodedParams }
).then((res) => {
console.log('called the api with fetch');
console.dir(res.json());
});
authClient.getToken(code, (err, token) => {
if (err) {
console.error(err);
res.status(500).json(err);
}
// console.dir(token);
console.log('TOKEN: =>', token);
res.json(token);
});
});
Is there anyone that's done this on the front end successfully?
You can't get a refresh token in a browser. Your example code would only work on a server. To do oauth at the client you should request "token" instead of "code".