You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

基于Shopify API实现加购与结账:PHP+React Native技术求助

Hey there! Let's walk through how to implement add-to-cart and checkout for your React Native + PHP setup without the hassle of OAuth/partner apps—since you don't need the storefront or app store listing, we can keep things straightforward using Shopify's Storefront API (this is designed for customer-facing interactions, no admin-level auth required).

First: Get Your Storefront Access Token

This is the key to making API calls without OAuth. Here's how to generate it in your Shopify admin:

  • Go to Settings > Apps and sales channels
  • Click Develop apps > Create an app (name it whatever you want)
  • Go to Configure Storefront API
  • Check the permissions you need (for unauthenticated customers, these are critical):
    • unauthenticated_write_checkouts
    • unauthenticated_read_product_listings
    • unauthenticated_write_carts
  • Save, then click Install app > Generate token
  • Copy this token—keep it safe, and never expose it in your React Native code (we'll use it only in your PHP backend)

Step 1: PHP Backend for Add-to-Cart

Your React Native app shouldn't call Shopify directly (risk of token exposure, cross-domain issues), so your PHP backend will act as a middleman. We'll use the Storefront API's cartCreate mutation to create a cart and add items in one go (or cartLinesAdd if you're adding to an existing cart).

Here's a simple PHP example using Guzzle (install it first with composer require guzzlehttp/guzzle):

<?php
require 'vendor/autoload.php';

use GuzzleHttp\Client;

// Replace with your store details
$storeDomain = "your-shop-name.myshopify.com";
$storefrontToken = "your-storefront-access-token";

$client = new Client([
    'base_uri' => "https://{$storeDomain}/api/2024-07/graphql.json",
    'headers' => [
        'Content-Type' => 'application/json',
        'X-Shopify-Storefront-Access-Token' => $storefrontToken,
    ],
]);

// Get data from React Native request
$input = json_decode(file_get_contents('php://input'), true);
$variantId = $input['variant_id']; // Must be in Shopify's GID format: gid://shopify/ProductVariant/123456789
$quantity = $input['quantity'] ?? 1;

// Mutation to create a cart and add the item
$mutation = <<<'GQL'
mutation CreateCart($variantId: ID!, $quantity: Int!) {
  cartCreate(input: {lines: [{quantity: $quantity, merchandiseId: $variantId}]}) {
    cart {
      id
      checkoutUrl // This is the link to Shopify's hosted checkout page
    }
    userErrors {
      message
      field
    }
  }
}
GQL;

try {
    $response = $client->post('', [
        'json' => [
            'query' => $mutation,
            'variables' => ['variantId' => $variantId, 'quantity' => $quantity]
        ]
    ]);

    echo $response->getBody();
} catch (Exception $e) {
    echo json_encode(['error' => $e->getMessage()]);
}
?>

Step 2: React Native Frontend Integration

Call your PHP backend to trigger the add-to-cart, then use Shopify's hosted checkout page to handle payment (this is way easier than building your own checkout—Shopify handles taxes, shipping, payment gateways, and security for you).

Here's a React Native example using axios and Linking:

import axios from 'axios';
import { Linking, Alert } from 'react-native';

const addToCartAndCheckout = async (variantId, quantity) => {
  try {
    const response = await axios.post(
      'https://your-php-backend-url.com/add-to-cart.php',
      { variant_id: variantId, quantity }
    );

    const { cart, userErrors } = response.data.data.cartCreate;
    
    if (userErrors.length > 0) {
      Alert.alert('Error', userErrors[0].message);
      return;
    }

    // Open Shopify's checkout page in the device's browser
    await Linking.openURL(cart.checkoutUrl);
  } catch (error) {
    console.error('Add to cart failed:', error);
    Alert.alert('Error', 'Failed to add item to cart');
  }
};

// Usage example (replace with your product variant ID)
addToCartAndCheckout('gid://shopify/ProductVariant/123456789', 2);

Step 3: Handle Checkout Completion (Optional but Useful)

Once a user finishes checkout, you'll want to know about it to update your app's data or send notifications. Use Shopify Webhooks for this:

  • In your Shopify admin, go to Settings > Notifications > Webhooks
  • Click Create webhook
  • For Event, select Checkout > Checkout completed
  • For URL, enter your PHP backend endpoint (e.g., https://your-php-backend.com/webhook-checkout-completed.php)
  • Select JSON as the format, then save
  • Copy the Webhook API secret—you'll need this to verify the request is legitimate

Here's a PHP example to receive and validate the webhook:

<?php
$webhookSecret = 'your-webhook-secret';
$requestBody = file_get_contents('php://input');
$hmacHeader = $_SERVER['HTTP_X_SHOPIFY_HMAC_SHA256'];

// Validate the webhook is from Shopify
$calculatedHmac = base64_encode(hash_hmac('sha256', $requestBody, $webhookSecret, true));
if (!hash_equals($hmacHeader, $calculatedHmac)) {
    http_response_code(403);
    exit('Invalid request');
}

// Process the checkout data
$checkoutData = json_decode($requestBody, true);
// Example: Save order details to your database, send a push notification to the user
error_log('Checkout completed: ' . $checkoutData['order_id']);

http_response_code(200);
echo 'Success';
?>

Key Notes to Remember

  • Never expose your Storefront Token in React Native: Always use your PHP backend as a proxy.
  • Product Variant IDs: Make sure you're using the full GID format (e.g., gid://shopify/ProductVariant/123456789). You can get these via the Storefront API's products query if you need to fetch product data in your app.
  • Shopify Hosted Checkout: This is the recommended approach—building your own checkout would require handling payment processing, tax calculations, and shipping rules, which is extremely complex.

内容的提问来源于stack exchange,提问作者Sardar Usama

火山引擎 最新活动