How to add selling plan in graphql checkout shopify - react-native

I'm new to use Shopify graphql APIs. I create checkout using the below code. My Checkout working fine.
Now I want to add a product with a subscription plan.
I'm getting all plan data and id of the subscription plan added on product data. On the Shopify backend, we use the rechargepayments.com app that is installed in over admin. This is supported by JQuery and an over website subscription working fine.
const query = `
mutation {
checkoutCreate(input: {
lineItems: [{ variantId: "${item.variantId}", quantity: 1, customAttributes: {key: "Shipping Styles", value: "Mixed"} }]
}) {
checkout {
id
webUrl
lineItems(first: 5) {
edges {
node {
title
quantity
}
}
}
}
}
}`
axios({
url: `https://mystore.myshopify.com/api/2021-07/graphql.json`,
method: 'POST',
body: query,
onSuccess: (data) => {
onSuccess({ value: 'Checkout item added' })
},
onFailure: (err) => {
console.log('updateCheckout err ', err);
onFailure({ value: 'fail' })
},
});
Please help me how can I add a selling plan or a subscription using graphql from the mobile application.

Related

Amplify AppSync subscription on update of a single record

My request table is:
type RequestService
#model
#auth(
rules: [
{ allow: groups, groups: ["Consumers"], operations: [read, create, update] }
{ allow: groups, groups: ["Providers"], operations: [read, update] }
]
) {
id: ID!
consumerID: ID!
providerID: ID
request_detail: String
}
I have a subscription on the updateRequestService mutation:
type Subscription {
onUpdateRequestServiceByID(id: ID!): RequestService
#aws_subscribe(mutations: ["updateRequestService"])
}
I have a page that lists all the records for the RequestService, upon clicking on one record, it opens a details page for the single record.
On the details page, I've called the subscription to listen to any updates done on the RequestService.
const [request, setRequest] = React.useState(route.params.requestID)
React.useEffect(() => {
(async () => {
const abortController = new AbortController();
const subscribe = await API.graphql(graphqlOperation(onUpdateRequestServiceByID, { id: request.id })).subscribe(
{
next: (data) => {
console.log("data", data.value.data.onUpdateRequestServiceByID);
setRequest(data.value.data.onUpdateRequestServiceByID);
},
error: (err) => console.log("err", err),
}
);
return () => {
subscribe.unsubscribe();
abortController.abort();
};
})();
}, []);
Unfortunately, I don't get any console.log's back, I get no response. I've also tried this on the AppSync Queries interface, but doesn't listen to updates on a record.
Any assistance on why I'm not getting the response?

Shopify API returns 400 bad request when creating new custom collection

I'm trying to create a custom collection following the document. I'm getting a 400 about the request being malformed.
My code:
require('dotenv').config()
const { Shopify } = require('#shopify/shopify-api')
const client = new Shopify.Clients.Rest(
process.env.SHOPIFY_STORE,
process.env.SHOPIFY_API_SECRET_KEY
);
(async () => {
try {
const data = await client.post({
path: 'custom_collections',
body: { 'custom_collection': { 'title': 'Nike' } },
type: 'application/json',
})
} catch(err) {
console.error(JSON.stringify(err))
}
})()
And the error response from Shopify is:
{"code":400,"statusText":"Bad Request"}
Any ideas what I'm doing wrong here? My tokens are correct because I can use the same token to view collections using the https URL https://API_KEY:SECRET#SHOPIFY_STORE/admin/api/2021-07/collections.json

Infinity loop in paypal multi seller

I'm currently programming a paypal multi seller checkout with the paypal api v2. In the checkout i always get stuck in a loop after clicking continue. It just says processing and stays like that. I also tried creating another Paypal App but same problem.How can i fix this? I used the following code to generate the order:
const axios = require('axios')
axios
.post('https://api-m.sandbox.paypal.com/v2/checkout/orders', {
"intent":"CAPTURE",
"application_context":{
"return_url":"C:\Users\Felix\Desktop\index.html",
"cancel_url":"C:\Users\Felix\Desktop\index.html"
},
"purchase_units":[
{
"reference_id":"test1",
"payee": {
"email_address": "sb-lgj1x6610750#business.example.com"
},
"amount":{
"currency_code":"EUR",
"value":"100.00"
},
"payment_instruction":{
"disbursement_mode":"INSTANT",
"platform_fees":[
{
"amount":{
"currency_code":"EUR",
"value":"2.00"
}
}
]
}
},
{
"reference_id":"test2",
"payee": {
"email_address": "sb-bong06236339#business.example.com"
},
"amount":{
"currency_code":"EUR",
"value":"7.00"
},
"payment_instruction":{
"disbursement_mode":"INSTANT",
"platform_fees":[
{
"amount":{
"currency_code":"EUR",
"value":"2.00"
}
}
]
}
}
]
},{
headers:{
'Content-Type': "application/json",
'Authorization': "Bearer A21AAJwo7sZjHVhLX3jHjR3HQzE-ojoUzbJUe--WXulQqOzEoV8sF0wNgCUqhOO3N3mDQl5pjnogxOBFmwywr3iXPpj9_VmGA",
'PayPal-Partner-Attribution-Id': 'FLAVORsb-7vgls6637891_MP'
}
})
.then(res => {
console.log(`statusCode: ${res.statusCode}`)
console.log(res.data)
})
.catch(error => {
console.error(error)
})
The return_url must be valid HTTP/S
The receiving (seller) account's email must be confirmed in the sandbox environment, https://www.sandbox.paypal.com/businessprofile/settings/email -- and if they do not have a balance in the transaction's currency (EUR in this example), they must accept a payment in their account's interface to open such a balance, or enable the payment receiving preference to automatically convert received payments to their account's primary balance (often USD, depending on country)

Can we get product by SKU using Shopify Storefront GraphQL API(NOT ADMIN)?

I am stuck on this for more than two days now. I couldn't able to find any resources on this. There are many solutions by using ADMIN API but I don't have Admin access. Problem I am trying to solve is: I have only access to Product's SKU. I need to fetch all other information(title, price, description, featuredImage etc...) from Shopify using Storefront API. Here's the function to get product:
function loadProducts(items) {
let products = [];
items.forEach((item) => {
const sku = item.id;
if (sku !== "undefined") {
/* TODO: Need to figure out this query*/
const query = `{
products(first: 1, query: "sku:<sku>") {
edges {
node {
title
id
description
}
}
}
}`;
const STOREFRONT_ACCESS_TOKEN = 'xxxxxxxxxxxxxxx';
const GRAPHQL_URL = 'https://<my-store>.myshopify.com/api/2021-01/graphql.json';
const GRAPHQL_BODY = {
'method': 'POST',
'headers': {
'X-Shopify-Storefront-Access-Token': STOREFRONT_ACCESS_TOKEN,
'Content-Type': 'application/json',
},
'body': JSON.stringify({ query })
}
products.push(getData(GRAPHQL_URL, GRAPHQL_BODY));
}
});
return Promise.all(products);
}
function getData(url, body) {
return new Promise((resolve, reject) => {
fetch(url, body)
.then(res => res.json())
.then(data => {
resolve(data);
})
.catch((error) => {
reject(error);
});
});
}
I'd really appreciate if you can redirect me to the right direction. PLEASE NOT: I am only suppose to use Storefront API, not the ADMIN API. Thank you!
You can't query the products by SKU using the StoreFront API.
The available query params for the StoreFront products are:
available_for_sale
created_at
product_type
tag
title
updated_at
variants.price
vendor
So you can't do this only with the StoreFront API since the SKU is not exposed (like the Admin API).
There is a workaround if you tag all of your products with their SKUs and you can search for that instead.

how to apple pay through stripe in VJs?

I am trying to follow the guide here ( https://stripe.com/docs/stripe-js/elements/payment-request-button ) to setup Apple Pay for the web and Stripe. The initial steps such as verification of domain and all the pre-setup is done but I am having an issue following the steps for the payment.
The Apple Pay Button is showing up in my Safari browser. When the button is clicked, I fire an event called Paymentmethode() i am facing this error while checking live.Either you do not have a card saved to your Wallet or the current domain (pwafe.devco.pk) is not registered for Apple Pay. Visit https://dashboard.stripe.com/account/apple_pay to register this domain.
main.js:25. and button is hide I get lost after step 3 and not sure what to do. I am posting to my backend and on the backend, creating a payment intent and returning the client_secret
paymentMethod() {
// STEP 1 FROM GUIDE
var stripe = Stripe("pk_test_YxSI6F4QeV0XCofSgabilbTu00ChOmJWJ0", {
apiVersion: "2020-08-27",
stripeAccount: "CONNECTED_STRIPE_ACCOUNT_ID",
});
// STEP 2 FROM GUIDE
var paymentRequest = stripe.paymentRequest({
country: "US",
currency: "usd",
total: {
label: "Demo total",
amount: 1099,
},
requestPayerName: true,
requestPayerEmail: true,
});
// STEP 3 FROM GUIDE
var elements = stripe.elements();
var prButton = elements.create("paymentRequestButton", {
paymentRequest: paymentRequest,
});
// console.log("before api call", paymentRequest);
paymentRequest.canMakePayment().then(function (result) {
// console.log("after api called" + result);
if (result) {
prButton.mount("#payment-request-button");
} else {
//prButton.mount('#payment-request-button');
document.getElementById("payment-request-button").style.display =
"none";
}
});
// STEP 4 FROM GUIDE -- THIS RETURNS A CLIENT SECRET
let clientSecret;
axios
.post("https://pwa.devco.pk/api/Create_PaymentIntent", {})
.then((resp) => {
// Assign this previously defined variable
clientSecret = resp.client_secret;
});
paymentRequest.on("paymentmethod", function (ev) {
// Confirm the PaymentIntent without handling potential next actions (yet).
stripe
.confirmCardPayment(
clientSecret,
{
payment_method: ev.paymentMethod.id,
},
{
handleActions: false,
}
)
.then(function (confirmResult) {
if (confirmResult.error) {
// Report to the browser that the payment failed, prompting it to
// re-show the payment interface, or show an error message and close
// the payment interface.
ev.complete("fail");
} else {
// Report to the browser that the confirmation was successful, prompting
// it to close the browser payment method collection interface.
ev.complete("success");
// Check if the PaymentIntent requires any actions and if so let Stripe.js
// handle the flow. If using an API version older than "2019-02-11" instead
// instead check for: `paymentIntent.status === "requires_source_action"`.
if (confirmResult.paymentIntent.status === "requires_action") {
// Let Stripe.js handle the rest of the payment flow.
stripe.confirmCardPayment(clientSecret).then(function (result) {
if (result.error) {
let data = {
msg: "An error occurred. Please try again.",
};
this.handleShowFlashMsg(data);
// The payment failed -- ask your customer for a new payment method.
} else {
this.handleShowOrderConfirmModal();
// The payment has succeeded.
}
});
} else {
// The payment has succeeded.
}
}
});
});
var paymentRequest = stripe.paymentRequest({
country: "US",
currency: "usd",
total: {
label: "Demo total",
amount: 1099,
},
requestShipping: true,
// `shippingOptions` is optional at this point:
shippingOptions: [
// The first shipping option in this list appears as the default
// option in the browser payment interface.
{
id: "free-shipping",
label: "Free shipping",
detail: "Arrives in 5 to 7 days",
amount: 0,
},
],
});
paymentRequest.on("shippingaddresschange", function (ev) {
if (ev.shippingAddress.country !== "US") {
ev.updateWith({
status: "invalid_shipping_address",
});
} else {
// Perform server-side request to fetch shipping options
fetch("/calculateShipping", {
data: JSON.stringify({
shippingAddress: ev.shippingAddress,
}),
})
.then(function (response) {
return response.json();
})
.then(function (result) {
ev.updateWith({
status: "success",
shippingOptions: result.supportedShippingOptions,
});
});
}
});
var stripe = Stripe("pk_test_YxSI6F4QeV0XCofSgabilbTu00ChOmJWJ0", {
apiVersion: "2020-08-27",
stripeAccount: "CONNECTED_STRIPE_ACCOUNT_ID",
});
},
You should verify domain registration and add card into wallet.tha