question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Square Connect API

See original GitHub issue
Have a request for a new sample?
================================
Great, we love hearing how we can improve our samples! Remove the template below and
provide an explanation of your sample request. Be as detailed as possible.
Note that it should cover a use case that isn't similar to our existing samples and
likely to be of broad use (i.e. not just a copy/paste solution to your specialized problem).

Hi!

First of all, thanks for the looooovely suite of function samples. This is a programmer’s dream! 🎉 🚀 ✨

I was wondering, do you think you could integrate the Square Connect API to your function samples? That could open up a whole slew of Point-Of-Sale applications w/ inventory and catalog management.

Let me know!

Have a wonderful day ✨

Cheers,

Philippe

Issue Analytics

  • State:open
  • Created 5 years ago
  • Comments:5

github_iconTop GitHub Comments

1reaction
danielpowell4commented, Sep 11, 2018

This is a preliminary sample for those who come next:

const functions = require("firebase-functions");
const crypto = require("crypto");
const axios = require("axios"); // be sure to add to package.json via npm install axios

exports.authorize = functions.https.onRequest((request, response) => {
  const squareAuthURL = "https://connect.squareup.com/oauth2/authorize?";
  const state = crypto.randomBytes(32).toString("hex");
  response.set("Set-Cookie", `__session=${state}; Secure`);

  response.redirect(
    squareAuthURL +
      `client_id=${functions.config().square.app_id}&` +
      `response_type=code&` +
      `scope=MERCHANT_PROFILE_READ ITEMS_READ ORDERS_READ PAYMENTS_READ&` +
      `session=false&` +
      `locale=en-US&` +
      `state=${state}`
  );
});

const getSessionCookie = cookie => {
  let name = "__session=";
  let decodedCookie = decodeURIComponent(cookie);
  let ca = decodedCookie.split(";");
  for (let c of ca) {
    while (c.charAt(0) === " ") {
      c = c.substring(1);
    }
    if (c.indexOf(name) === 0) {
      return c.substring(name.length, c.length);
    }
  }
  return "";
};

// TODO: Implement me as needed for use case!
const createOrUpdateFirebaseAccount = (userData, tokenData) => ({
  userData,
  tokenData
});

exports.callback = functions.https.onRequest((request, response) => {
  const tokenURL = "https://connect.squareup.com/oauth2/token";
  const redirectURI =
    "https://us-central1-YOUR_APP_NAME.cloudfunctions.net/callback";
  const cookieState = getSessionCookie(request.get("cookie"));

  const { code, state } = request.query;

  if (cookieState === state) {
    const { app_id, secret } = functions.config().square;
    let access_token, id, email, name;
    return axios
      .post(tokenURL, {
        client_id: app_id,
        client_secret: secret,
        code: decodeURIComponent(code),
        redirect_uri: redirectURI
      })
      .then(token => {
        ({ access_token } = token.data);
        return (
          axios
            .get("https://connect.squareup.com/v1/me", {
              headers: {
                Authorization: `Bearer ${access_token}`
              }
            })
            .then(user => {
              //  return createOrUpdateFirebaseAccount(user.data, token.data);
              return response.json({
                tokenData: token.data,
                userData: user.data
              });
            })
            // .then(firebaseToken => {
            //   return response.json({
            //     email: email,
            //     token: firebaseToken
            //   });
            // })
            .catch(error => {
              console.log(error);
              return response.send(error);
            })
        );
      });
  } else {
    console.log(`INVALID STATE: ${cookieState} === ${state}`);
    return response.send(`INVALID STATE: ${cookieState} === ${state}`);
  }
});

Be sure to set ENV configs as appropriate:

https://firebase.google.com/docs/functions/config-env

You will also need to set up the Oauth callback url inside of square

It is also best practice to encode the tokens rather than saving them directly.

This is best done via something like:

const encryptToken = accessToken => {
  const cipher = crypto.createCipher("aes192", ENCRYPT_KEY);

  let encrypted = cipher.update(accessToken, "utf8", "hex");
  encrypted += cipher.final("hex");
  return encrypted;
};

const decryptToken = accessToken => {
  const decipher = crypto.createDecipher("aes192", ENCRYPT_KEY);

  let decrypted = decipher.update(accessToken, "hex", "utf8");
  decrypted += decipher.final("utf8");
  return decrypted;
};

Beyond this be sure to checkout the pre-built postman test api suite, likely using a sandbox access_token credential in your environment

0reactions
Kliegercommented, May 22, 2020

@danielpowell4 could you share your full code, where is functions.config().square coming from?

https://firebase.google.com/docs/functions/config-env

Read more comments on GitHub >

github_iconTop Results From Across the Web

Square Developer Documentation
Find out how to build and publish apps to the Square App Marketplace. ... Make requests to the Square API to easily test...
Read more >
Square API Reference
Square APIs enable you to accept payments securely and integrate your app with Square's first party product ecosystem. Build full-featured business apps for ......
Read more >
Connect API Basics - Square Developer
The Connect v2 API suite supports online payments, order creation for itemized transactions, product catalog management, inventory management, ...
Read more >
Square Connect API Documentation
This page contains links to technical reference material for Square's APIs and SDKs for non-current versions. Current references are always accessible from ...
Read more >
Point of Sale SDK for iOS Reference - Square Developer
Initiating a Square Point of Sale transaction with the Point of Sale SDK ... Your Connect API Application ID, available from your application...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found