Adding product to cart through QR code?

Highlighted
Tourist
8 0 0

I have a client that would like to add a product to the cart by scanning a QR code.

Is this possible? How can I achieve this? I have a QR code scanner script and I know I should reference cartPanel script and it's method .AddToCart, but how can I reference product and variant?

All of this should be done in Unity and using Shopify Unity SDK

 

if (cameraManager.TryGetLatestImage(out XRCameraImage image))
{
// 'image' is an acquired resource that must be diposed when we are done.
using (image)
{
// - Convert the image to RGBA. This takes considerable time, so there are also asynchronous
// options.
//
// - It's /much/ faster to convert to a single channel format, e.g., TextureFormat.R8.

var conversionParams = new XRCameraImageConversionParams(image, TextureFormat.RGBA32, CameraImageTransformation.MirrorY);

// Get the size (number of bytes) of the buffer required to hold the RGBA pixel data.
var dataSize = image.GetConvertedDataSize(conversionParams);
var bytesPerPixel = 4; // because we chose an RGBA format.

// Since the 'BarcodeReader' code accepts a managed
// array, that's what I've used here. It would be more efficient
// to use a NativeArray if the BarcodeReader can use that.
var pixels = new Color32[dataSize / bytesPerPixel];
fixed (void* ptr = pixels)
{
image.Convert(conversionParams, new IntPtr(ptr), dataSize);
}

IBarcodeReader barcodeReader = new BarcodeReader();
// The 'pixels' array now contains the image data.
var result = barcodeReader.Decode(pixels, image.width, image.height);
if (result != null)
{
if (result.Text.Contains("productID"))
{
//Add product to cart
cartPanel.AddToCart(productID);
}
}
}
}

 

Any help is kindly appreciated!

0 Likes
Highlighted
Shopify Partner
530 38 109

While I am not familiar with the Shopify Unity SDK, I utilized the Shopify POS App SDK for Edit Cart functionality. Details are here --> https://shopify.dev/tools/pos-app-sdk/methods#add-line-item. While there are a host of different packages for doing this (e.g. - Shopify App Bridge SDK, Shopify Embedded App SDK, etc.) if the Shopify POS SDK is still active I found it pretty straightforward to work with.

Below is a simple JavaScript example function for doing this. Figure if the QR code resolves to a middleware URL and the variantId is supplied as an URL parameter it should work.

function addToCart(variantId) {
    ShopifyPOS.fetchCart({
    success: function(cart) {
    cart.addLineItem({
                variant_id: variantId
		quantity: 1
                }, {
                success: function(cart) {
		    ShopifyPOS.flashNotice("Successfully added to cart");
		    ShopifyPOS.Modal.close();
                    },
                error: function(errors) {
		    ShopifyPOS.flashError("Failed to add to cart. Error: " + errors[0].message);
		    ShopifyPOS.Modal.close();
                }
            })
    }});
}

 

0 Likes
Highlighted
Shopify Partner
40 3 15

To add on to what Greg was saying. It sounds to me like the area of your flow that needs to be looked at is the QR code. Not 100% sure how you/they are generating it but it would need to have a reference to the variant ID in the code itself. Once you have that accomplished the method Greg provided (or something similar) should work properly.

0 Likes
Highlighted
Shopify Partner
530 38 109

...although when I looked up what the Unity SDK involves, my method was a more POS front-end function. Whereas what the OP was looking for appears to involve an online e-com client. But regardless, the QR code would likely need to include the variant ID in order to properly work!

1 Like
Highlighted
Tourist
8 0 0

Hi Greg,

Thank you for the reply, I have a question, if my product doesn't have variants, where can I look up what my product ID is? And how could I do that in C#?

0 Likes
Highlighted
Shopify Partner
530 38 109

I guess "look up what my product ID is" could be an open-ended question. It depends on the framework you are using, since if it's a Shopify-related one it should expose that somewhere.

One angle I can think of is if you know the product title. And the title is unique, only assigned to a single product. You could issue a GraphQL API request like this example below. the id is the GraphQL representation of the product ID. And the legacyResourceId is the REST API representation of it. Really used everywhere else for the most part, other than the GraphQL API.

If you are looking to consume the GraphQL API using C#, here's an article that speaks to building a client to make it a bit easier --> https://code-maze.com/consume-graphql-api-with-asp-net-core/

Hope this helps a little at least! 

{
  products(first:1, query: "title:14K White Gold Diamond Bangle") {
    edges {
      node {
        id
        legacyResourceId
        title
        tags
      }
    }
  }
}

 

1 Like
Highlighted
Shopify Partner
40 3 15

Also something of note, every product has at least one variant, even if itdit have multiple variants defined. So there is always a variant Id to work with.

0 Likes
Highlighted
Tourist
8 0 0

Hey Martin,

 

Thanks for noting that, I have a question, that I hope you can help me out, I solved the QR code adding by creating a custom script, however, when I scan one QR code that adds the first item, then open checkout, then go back and scan the QR code for the second item, it doesn't update the store, how can I fix that? Thanks.

 

    public BrowserOpener inAppBrowser;
    Cart cart;

    List<ProductVariant> firstProductVariants, secondProductVariants;
    ProductVariant firstProductFirstVariant, secondProductFirstVariant;

    List<ProductVariant> collectionVariants;
    ProductVariant collectionVariant;
    // Start is called before the first frame update
    void Start()
    {
        string accessToken = "***************************";
        string shopDomain = "***************************";

        ShopifyBuy.Init(accessToken, shopDomain);

        cart = ShopifyBuy.Client().Cart();

        ShopifyBuy.Client().products((products, error, after) => {
            if (error != null)
            {
                Debug.Log(error.Description);

                switch (error.Type)
                {
                    // An HTTP error is actually Unity's WWW.error
                    case ShopifyError.ErrorType.HTTP:
                        break;
                    // Although it's unlikely, an invalid GraphQL query might be sent.
                    // Report an issue to https://github.com/shopify/unity-buy-sdk/issues
                    case ShopifyError.ErrorType.GraphQL:
                        break;
                };
            }
            else
            {
                Debug.Log("Here is the first page of products:");

                // products is a List<Product>
                foreach (Product product in products)
                {
                    Debug.Log("Product Title: " + product.title());
                    Debug.Log("Product Description: " + product.descriptionHtml());
                    Debug.Log("--------");
                }
            }

            firstProductVariants = (List<ProductVariant>)products[0].variants();
            firstProductFirstVariant = firstProductVariants[0];


            secondProductVariants = (List<ProductVariant>)products[1].variants();
            secondProductFirstVariant = secondProductVariants[0];

        });
    }

    // Update is called once per frame
    void Update()
    {
        if (inAppBrowser.pageToOpen.Contains("second"))
        {
            AddSecondItem();
        }

        if (inAppBrowser.pageToOpen.Contains("first"))
        {
            AddFirstItem();
        }
    }

    public void AddFirstItem()
    {
        // The following example adds a line item using the first products first variant.
        // In this case, the cart will have 1 copy of the variant.
        cart.LineItems.AddOrUpdate(firstProductFirstVariant, 1);
    }

    public void AddSecondItem()
    {
        // The following example adds a line item using the second products first variant.
        // In this case, the cart will have 1 copy of the variant.
        cart.LineItems.AddOrUpdate(secondProductFirstVariant, 1);
    }

    //Checkout with inAppBrowser
    public void WebCheckOut()
    {
        cart.GetWebCheckoutLink(
               success: (link) => {
                   //inAppBrowser.pageToOpen = link;
                   //inAppBrowser.OnButtonClicked();
                   Application.OpenURL(link);

               },
               failure: (checkoutError) => {
                   Debug.Log(checkoutError.Description);
               }
           );
    }

 

 

0 Likes
Highlighted
Shopify Partner
530 38 109

The source code paste is helpful, as it gives a better idea about what you are working with. I assume this is just a small test project you are creating, right? While I don't have any practical hands-on with the Unity SDK, I do have a few C# production projects that I created using Visual Studio. 

In broad, general terms I would imagine that your QR code scanning action would trigger an event handler. And the event handler should be taking the scanned variant ID, cast it as a ProductVariant, and pass that ProductVariant along to a single add to cart method. With the variant ID as a method parameter. Like this for add to cart:

public void AddItemToCart(ProductVariant variantId)    {
        cart.LineItems.AddOrUpdate(variantId, 1);
    }

Like I said, I have zero knowledge of the Unity SDK. So I'm not sure if you can just cast a scanned QR code value to a ProductVariant type. Perhaps others with Unity SDK experience can speak to some of this. But I do know that your code should be simpler and not have duplicate methods for essentially the same add to cart function.

0 Likes
Highlighted
Tourist
8 0 0

Hi Greg,

Thanks for the reply, I will refactor my code later but currently my issue is that my cart is not updating whenever I add a product to it.

 

When I open the link through GetWebCheckoutLink. If I opened it before adding any products it will say that the cart is empty no matter what product I add

0 Likes