Payment working in staging but in production

Hi Team,

Payment is not working in production environment but it is working good in staging/sandbox environment.

Application Flow: we created 4 plans and allowing our application user to select among the plan and then we are taking the cards details and processing payment.

below code flow on the same.

async createCustomerPaymentSubscription(cardNonce, selectedPlan, agentId, amount) {
    try {
      const idempotency_key = crypto.randomBytes(22).toString("hex");
      const customerRes = await axios.post(
        `${process.env.SQUARE_URL}/v2/customers`,
        {
          email_address: process.env.SQUARE_EMAIL
        },
        this.headers
      );
      const customerId: string = customerRes?.data?.customer?.id;
      const squareClient = new Client({
        environment: Environment.Production, // Change to square.Environment.Production for testing  for prod Production square.Environment.Production
        accessToken: process.env.SQUARE_ACCESS_TOKEN
      });
      // get selected plan
      const plan = await this.getListSubscriptionPlan();
      const activePlan = plan?.find((item) => item?.subscription_plan_data?.name === selectedPlan && item?.present_at_all_locations);
      
      console.log('activePlanactivePlan', activePlan);
      console.log('Subscription Plan', JSON.stringify(activePlan?.subscription_plan_data?.subscription_plan_variations?.[0]?.subscription_plan_variation_data?.phases?.[0]?.pricing?.price_money?.amount));
      
      // Create a customer card to charge
      const cardResult: any = await squareClient.customersApi.createCustomerCard(customerId, {
        cardNonce: cardNonce
      });

      console.log('cardResultcardResult',cardResult);
      const cardId = cardResult?.result?.card?.id;
      console.log('cardIdcardIdcardId',cardId);
      
      // get exiting subscription
      const existSubscription = await this.paymentSubscriptionService.getSubscription(agentId);
      let currDate: any = new Date();
      currDate = moment(currDate, "YYYY-MM-DD").format("YYYY-MM-DD");
      const existPlanCanceledDate = moment(existSubscription.canceledDate, "YYYY-MM-DD").format("YYYY-MM-DD");
      let subscriptionStartDate = moment().format("YYYY-MM-DD");
      let count = 0;

      if (activePlan?.subscription_plan_data?.subscription_plan_variations?.[0]?.subscription_plan_variation_data?.phases?.[0]?.pricing?.price_money?.amount <= existSubscription?.price && existPlanCanceledDate > currDate) {
        count = Math.abs(moment(currDate, "YYYY-MM-DD").startOf("day").diff(moment(existPlanCanceledDate, "YYYY-MM-DD").startOf("day"), "days")) + 1;
      }
      if (count > 0) {
        subscriptionStartDate = moment(subscriptionStartDate).add(count, "days").format("YYYY-MM-DD");
      }
      const subscription: any = {
        idempotencyKey: idempotency_key,
        locationId: process.env.LOCATION_ID,
        customerId: customerId,
        planId: activePlan?.id ?? "planId",
        cardId: cardId,
        startDate: subscriptionStartDate,
        timezone: "America/Los_Angeles",
        source: {
          name: "Navihome"
        }
      };

      //cancel exist Subscription
      if (existSubscription?.subscriptionId && !existSubscription?.subscriptionId.includes("free")) {
        const { result } = await squareClient.subscriptionsApi.cancelSubscription(existSubscription.subscriptionId);
      }

      // Create the subscription
      const { result }: any = await squareClient.subscriptionsApi.createSubscription(subscription);
      const subscriptionData = {
        agentId: agentId,
        subscriptionId: result?.subscription?.id,
        planId: result?.subscription?.planId,
        status: count > 0 ? "PENDING" : result?.subscription?.status,
        startDate: result?.subscription?.startDate,
        canceledDate: moment(result?.subscription?.startDate).add(30, "days").format("YYYY-MM-DD"),
        price: activePlan?.subscription_plan_data?.subscription_plan_variations?.[0]?.subscription_plan_variation_data?.phases?.[0]?.pricing?.price_money?.amount,
        planName: activePlan?.subscription_plan_data?.name,
        activePlan: count > 0 ? existSubscription?.planName : activePlan?.subscription_plan_data?.name
      };
      await this.paymentSubscriptionService.insertSubsciption(subscriptionData);
      return JSON.parse(JSON.stringify(result.subscription, (key, value) => (typeof value === "bigint" ? value.toString() : value)));
    } catch (error) {
      console.log("ERROR--", error);
      return {
        error: true,
        message: "Payment Failed",
        category: 'AUTHENTICATION_ERROR',
        code: 'UNAUTHORIZED',
        detail: 'This request could not be authorized.'
      }
    }
  }

in Production setup, i am not able to create a customer card line.

kindly request your help to solve this case.

:wave: I’m Square Dev AI, here to help answer your question!
Based on the information you’ve provided, the following documentation will help answer your question:

Additional Documentation

Customers API Workflows
Deploy the Server
Create a Shared Card on File and Make a Payment

If this documentation helped you find a solution, please check the box indicating that this reply solves the problem.
Otherwise one of our Developer Advocates will provide additional assistance shortly.

Hi Team,

we are getting the invalid request error when we are trying to createSubscription()

async createCustomerPaymentSubscription(cardNonce, selectedPlan, agentId, amount) {
    try {
      const idempotency_key = crypto.randomBytes(22).toString("hex");
      const customerRes = await axios.post(
        `${process.env.SQUARE_URL}/v2/customers`,
        {
          email_address: process.env.SQUARE_EMAIL
        },
        this.headers
      );
      const customerId: string = customerRes?.data?.customer?.id;
      const squareClient = new Client({
        environment: Environment.Production, // Change to square.Environment.Production for testing  for prod Production square.Environment.Production
        accessToken: process.env.SQUARE_ACCESS_TOKEN
      });
      // get selected plan
      const plan = await this.getListSubscriptionPlan();
      const activePlan = plan?.find((item) => item?.subscription_plan_data?.name === selectedPlan && item?.present_at_all_locations);
      
      console.log('activePlanactivePlan', activePlan);
      console.log('active', activePlan?.subscription_plan_data?.subscription_plan_variations);
      console.log('Subscription Plan', JSON.stringify(activePlan?.subscription_plan_data?.subscription_plan_variations?.[0]?.subscription_plan_variation_data?.phases?.[0]?.pricing?.price_money?.amount));
      
      // Create a customer card to charge
      const cardResult: any = await squareClient.customersApi.createCustomerCard(customerId, {
        cardNonce: cardNonce
      });

      console.log('cardResultcardResult',cardResult);
      const cardId = cardResult?.result?.card?.id;
      console.log('cardIdcardIdcardId',cardId);
      
      // get exiting subscription
      const existSubscription = await this.paymentSubscriptionService.getSubscription(agentId);
      let currDate: any = new Date();
      currDate = moment(currDate, "YYYY-MM-DD").format("YYYY-MM-DD");
      const existPlanCanceledDate = moment(existSubscription.canceledDate, "YYYY-MM-DD").format("YYYY-MM-DD");
      let subscriptionStartDate = moment().format("YYYY-MM-DD");
      let count = 0;

      if (activePlan?.subscription_plan_data?.subscription_plan_variations?.[0]?.subscription_plan_variation_data?.phases?.[0]?.pricing?.price_money?.amount <= existSubscription?.price && existPlanCanceledDate > currDate) {
        count = Math.abs(moment(currDate, "YYYY-MM-DD").startOf("day").diff(moment(existPlanCanceledDate, "YYYY-MM-DD").startOf("day"), "days")) + 1;
      }
      if (count > 0) {
        subscriptionStartDate = moment(subscriptionStartDate).add(count, "days").format("YYYY-MM-DD");
      }
      const subscription: any = {
        idempotencyKey: idempotency_key,
        locationId: process.env.LOCATION_ID,
        customerId: customerId,
        planId: activePlan?.id ?? "planId",
        cardId: cardId,
        startDate: subscriptionStartDate,
        timezone: "America/Los_Angeles",
        source: {
          name: "Navihome"
        }
      };

      //cancel exist Subscription
      if (existSubscription?.subscriptionId && !existSubscription?.subscriptionId.includes("free")) {
        const { result } = await squareClient.subscriptionsApi.cancelSubscription(existSubscription.subscriptionId);
      }

      // Create the subscription
      const { result }: any = await squareClient.subscriptionsApi.createSubscription(subscription);
      const subscriptionData = {
        agentId: agentId,
        subscriptionId: result?.subscription?.id,
        planId: result?.subscription?.planId,
        status: count > 0 ? "PENDING" : result?.subscription?.status,
        startDate: result?.subscription?.startDate,
        canceledDate: moment(result?.subscription?.startDate).add(30, "days").format("YYYY-MM-DD"),
        price: activePlan?.subscription_plan_data?.subscription_plan_variations?.[0]?.subscription_plan_variation_data?.phases?.[0]?.pricing?.price_money?.amount,
        planName: activePlan?.subscription_plan_data?.name,
        activePlan: count > 0 ? existSubscription?.planName : activePlan?.subscription_plan_data?.name
      };
      await this.paymentSubscriptionService.insertSubsciption(subscriptionData);
      return JSON.parse(JSON.stringify(result.subscription, (key, value) => (typeof value === "bigint" ? value.toString() : value)));
    } catch (error) {
      console.log("ERROR--", error);
      return {
        error: true,
        message: "Payment Failed",
        category: 'AUTHENTICATION_ERROR',
        code: 'UNAUTHORIZED',
        detail: 'This request could not be authorized.'
      }
    }
  }

async createSubscriptionPlan() {
    try {
      const idempotency_key = crypto.randomBytes(22).toString("hex");
      // create Plan
      const newPlan = {
        idempotency_key: idempotency_key,
        object: {
          type: "SUBSCRIPTION_PLAN",
          id: "#basicPlan",
          subscription_plan_data: {
            name: "Navihome Basic Plan",
            phases: [
              {
                cadence: "MONTHLY",
                recurring_price_money: {
                  amount: 2999,
                  currency: "USD"
                }
              }
            ]
          }
        }
      };

      await axios
        .post(`${process.env.SQUARE_URL}/v2/catalog/object`, newPlan, this.headers)
        .then((respo) => {
          console.log("respo---", respo);
          return respo;
        })
        .catch((error) => {
          console.log("error---", error);
          return error;
        });
    } catch (err) {
      console.log(err);
      return err;
    }
  }

error snap:

we have changed to SQUARE API VERSION to latest: 2024-01-18

Hi @kymberli :wave: ,

Welcome to the forums :tada:

Regarding your original post, about how the card form is not loading when you switched over to production API credentials, here is some troubleshooting suggestions:

    1. Check API Credentials: Ensure that the API credentials (such as the application ID, location ID, and access token) used in the production environment are correctly configured.
    1. Check if there is any error logs. See this is in TypeScript, which I take it means you are using Web Payments SDK. Check the console logs, check the network tab, see if there is an error explaining why the form might not have loaded.

Regarding the createSubscription() error:
I would like to get your application id to take a look at your API Logs. This will give me more context on where you are at in the Subscription creation process.
If you have not already, you should checkout the Subscription Plans and Variations doc. In newer Square API version after around July of 2023, each subscription plan also needs a subscription plan variation.

Seems like you have some code to implement variations, but I cannot tell at which point in the series of API calls you have gotten that error.

Do you have any example ids (like a subscription plan id) I can look at as an example, for when I take a look at the API calls in the API Logs?

Hi Lance,

As requested kindly find the application id

Application Name: Navihome
Application ID: sq0idp-HR_b0xXg8Q6vl4Pl7gwOJg

for checking the API Logs.

we have deployed our application in 2 ec2 instance; one for staging and one for production.
payments and subscription were successful through staging but on production.

we tried changing the latest square API version on production but still issue persists.

Kindly do the needful.

The error message that you got means that the subscription that your trying to create doesn’t have a subscription_plan_variation. You’ll need to add a variation to the subscription as documented here. :slightly_smiling_face:

@Lance-Square

Have you gone through the API logs of our application?

Hi @Bryan-Square,

We are able to do create customer card and subscription plan and make payments in sandbox environment but on production environment it get stopped while creating customer card module and not proceeding to subscription plan creation.

I request you to check the Developer API Logs of Sandbox and Production for more reference.

We wanted to know whether it is happening due to new changes in subscription plan creation (i.e compulsory one item assignment). Do we need to recreate new subscription plan including item. if so we are not selling any items like dress or so. we are giving application features as service and asking customer to subscribe to use the application feature like Netflix subscription or gym subscription.

Another point, for testing the square production payment, can we use Indian credit card having international payment enabled or is it there any way to test production payment like sandbox.

@kymberli, I took a look at the logs and see that your using CreateCustomerCard instead of CreateCard with the Cards API. We recommend that you use CreateCard since that is the supported endpoint for creating a card on file.

While you may not be selling a physical item the item you are selling is the subscription. You’ll want to create an item in the Catalog for the subscription and create the subscription with the item as documented in our Subscription Plans and Variations.

Also I see that you used a sandbox test value to test in production. Please note that only valid cards will only work for production. :slightly_smiling_face:

1 Like

Hi @Bryan-Square ,

As suggested, we have implemented the changes but still we are not able to complete the subscription process.

I checked the API Production logs in developer dashboard. square version mentioned as 2022-12-16 but we are using 2023-12-13 square version in our header during API call. why it is showing as 2022-12-16, can you help us to debug.

kindly check these five transactions.

If your passing in the version in the header of the request it will override the set version in the application. If it’s not picking up the version that your passing in that means that theres something wrong with the way your passing in the Square-Version. Do you have a sample request that your seeing this with? :slightly_smiling_face:

Hi @Bryan-Square ,

As requested, Please refer to “getListSubscriptionPlan()” in below square.service.ts complete code where we called list catalog api

Here we used process.env.SQUARE_API_VERSION over code and find the .env setup code as below

.env

# PRODUCTION SQUARE PAYMENT GATEWAY
 SQUARE_URL=https://connect.squareup.com
 SQUARE_APPLI_ID=sq0idp-HR_b0xXg8Q6vl4Pl7gwOJg
 SQUARE_ACCESS_TOKEN=Exxxxxxxxxxxxxxxxxxxxxxx
 SQUARE_API_VERSION=2023-12-13
 LOCATION_ID=L016J6TZKPE5A

square.service.ts

import { Injectable } from "@nestjs/common";
import axios from "axios";
import * as crypto from "crypto";
import * as moment from "moment";
import { Client, Environment } from "square";
import { PaymentSubscriptionService } from "src/payment-subscription/payment-subscription.service";

export interface IPublishInput {
  /**
   * Recipent Name
   */
  cardholder_name;
  /**
   * Card Last 4 digit
   */
  last_4;
  /**
   * Card Expiry Month
   */
  exp_month;
  /**
   * Card Expiry Year
   */
  exp_year;
  /**
   * Payment Amount
   */
  amount;
  /**
   * Agent Id
   */
  agentId;
  /**
   * Buyer Id
   */
  buyerId;
  /**
   * Subscription Type
   */
  subscription_type;
}

@Injectable()
export class SquareService {
  constructor(private readonly paymentSubscriptionService: PaymentSubscriptionService) { }
  headers = {
    headers: {
      "Square-Version": process.env.SQUARE_API_VERSION,
      Authorization: `Bearer ${process.env.SQUARE_ACCESS_TOKEN}`,
      "Content-Type": "application/json"
    }
  };

  async createPayment(cardholder_name, nonce, amount, agentId, buyerId, subscription_type) {
    try {
      const idempotency_key = crypto.randomBytes(22).toString("hex");
      const customerRes = await axios.post(
        `${process.env.SQUARE_URL}/v2/customers`,
        {
          email_address: process.env.SQUARE_EMAIL
        },
        this.headers
      );

      let paymentRes: any;
      if (customerRes?.data) {
        /* Make Payments  */
        paymentRes = await axios.post(
          `${process.env.SQUARE_URL}/v2/payments`,
          {
            idempotency_key: idempotency_key,
            amount_money: {
              amount: parseInt(amount),
              currency: "USD"
            },
            source_id: nonce,
            autocomplete: true
          },
          this.headers
        );

        if (paymentRes?.data) {
          const cardData = {
            card_id: paymentRes?.data?.payment?.id,
            card_brand: paymentRes?.data?.payment?.card_details?.card?.card_brand,
            last_4: paymentRes?.data?.payment?.card_details?.card?.last_4,
            exp_month: paymentRes?.data?.payment?.card_details?.card?.exp_month,
            exp_year: paymentRes?.data?.payment?.card_details?.card?.exp_year,
            cardholder_name: cardholder_name,
            customer_id: "",
            merchant_id: "",
            bin: paymentRes?.data?.payment?.card_details?.card?.bin,
            card_type: paymentRes?.data?.payment?.card_details?.card?.card_type,
            agentId: agentId ? agentId : 0,
            buyerId: buyerId ? buyerId : 0,
            created_at: new Date()
          };
          /* Insert Card */
          await axios.post(`${process.env.API_URL}/card`, cardData);

          /* Payment history Data */
          const paymentsData = {
            payment_id: paymentRes?.data?.payment?.id,
            amount: paymentRes?.data?.payment?.amount_money?.amount,
            currency: paymentRes?.data?.payment?.amount_money?.currency,
            status: paymentRes?.data?.payment?.status,
            delay_duration: paymentRes?.data?.payment?.delay_duration,
            source_type: paymentRes?.data?.payment?.source_type,
            card_bin: paymentRes?.data?.payment?.card_details?.card?.bin,
            order_id: paymentRes?.data?.payment?.order_id,
            customer_id: paymentRes?.data?.payment?.receipt_number,
            receipt_url: paymentRes?.data?.payment?.receipt_url,
            version_token: paymentRes?.data?.payment?.version_token,
            application_id: paymentRes?.data?.payment?.application_details?.application_id,
            subscription_type: subscription_type,
            agentId: agentId ? agentId : 0,
            buyerId: buyerId ? buyerId : 0,
            created_at: new Date()
          };
          /* Insert payements history */
          await axios.post(`${process.env.API_URL}/payments`, paymentsData);
          return paymentRes?.data;
        }
      }
    } catch (error) {
      console.log("ERROR--", error);
    }
  }

  async updateCustomerPaymentService(cardholder_name, nonce, amount, agentId, buyerId, subscription_type) {
    try {
      const idempotency_key = crypto.randomBytes(22).toString("hex");
      const customerRes = await axios.post(
        `${process.env.SQUARE_URL}/v2/customers`,
        {
          email_address: process.env.SQUARE_EMAIL
        },
        this.headers
      );

      if (customerRes?.data) {
        /* Make Payments  */
        await axios
          .post(
            `${process.env.SQUARE_URL}/v2/payments`,
            {
              idempotency_key: idempotency_key,
              amount_money: {
                amount: parseInt(amount),
                currency: "USD"
              },
              source_id: "cnon:CBASEDacZZ-_R8qD5eLtl1LjCx0",
              location_id: process.env.LOCATION_ID,
              autocomplete: true
            },
            this.headers
          )
          .then((respo) => {
            console.log("respo---", respo);
          })
          .catch((error) => {
            console.log("Nonce error---", JSON.stringify(error));
          });
        return;
      }
    } catch (error) {
      console.log("ERROR--", error);
    }
  }

  async createCustomerPaymentSubscription(cardNonce, selectedPlan, agentId, amount) {
    try {
      const idempotency_key = crypto.randomBytes(22).toString("hex");
      const customerRes = await axios.post(
        `${process.env.SQUARE_URL}/v2/customers`,
        {
          email_address: process.env.SQUARE_EMAIL
        },
        this.headers
      );

      const customerId: string = customerRes?.data?.customer?.id;
      const squareClient = new Client({
        environment: Environment.Production, // Change to square.Environment.Production for testing  for prod Production square.Environment.Production
        accessToken: process.env.SQUARE_ACCESS_TOKEN,
        squareVersion: process.env.SQUARE_API_VERSION
      });
      // get selected plan
      const plan = await this.getListSubscriptionPlan();
      // console.log('planplan', plan);  
      const activePlan = plan?.find((item) => ((item?.subscription_plan_data?.name === selectedPlan) && item?.present_at_all_locations));
      console.log('Subscription Plan', JSON.stringify(
        activePlan?.subscription_plan_data?.subscription_plan_variations?.[0]?.subscription_plan_variation_data?.phases?.[0]?.pricing?.price_money?.amount));
      // console.log('Plan name', JSON.stringify(activePlan));

      const createCardData = {
        idempotencyKey:idempotency_key,
        sourceId: cardNonce,
        card:{
          customerId: customerId
        }
      }
      
      // Create a customer card to charge
      const cardResult: any = await squareClient.cardsApi.createCard(createCardData);
      // console.log('cardResult--', cardResult);

      const cardId = cardResult?.result?.card?.id;
      // get exiting subscription
      const existSubscription = await this.paymentSubscriptionService.getSubscription(agentId);
      let currDate: any = new Date();
      currDate = moment(currDate, "YYYY-MM-DD").format("YYYY-MM-DD");
      const existPlanCanceledDate = moment(existSubscription.canceledDate, "YYYY-MM-DD").format("YYYY-MM-DD");
      let subscriptionStartDate = moment().format("YYYY-MM-DD");
      let count = 0;

      if (activePlan?.subscription_plan_data?.subscription_plan_variations?.[0]?.subscription_plan_variation_data?.phases?.[0]?.pricing?.price_money?.amount <= existSubscription?.price && existPlanCanceledDate > currDate) {
        count = Math.abs(moment(currDate, "YYYY-MM-DD").startOf("day").diff(moment(existPlanCanceledDate, "YYYY-MM-DD").startOf("day"), "days")) + 1;
      }
      if (count > 0) {
        subscriptionStartDate = moment(subscriptionStartDate).add(count, "days").format("YYYY-MM-DD");
      }
      const subscription: any = {
        idempotencyKey: idempotency_key,
        locationId: process.env.LOCATION_ID,
        customerId: customerId,
        planVariationId: activePlan?.subscription_plan_data?.subscription_plan_variations?.[0]?.id ?? "planId",
        cardId: cardId,
        startDate: subscriptionStartDate,
        timezone: "America/Los_Angeles",
        source: {
          name: "Navihome"
        }
      };
      //cancel exist Subscription
      if (existSubscription?.subscriptionId && !existSubscription?.subscriptionId.includes("free")) {
        const { result } = await squareClient.subscriptionsApi.cancelSubscription(existSubscription.subscriptionId);
      }

      // Create the subscription
      const { result }: any = await squareClient.subscriptionsApi.createSubscription(subscription);
      // console.log('resultresult', result);
      const subscriptionData = {
        agentId: agentId,
        subscriptionId: result?.subscription?.id,
        planId: result?.subscription?.planId,
        status: count > 0 ? "PENDING" : result?.subscription?.status,
        startDate: result?.subscription?.startDate,
        canceledDate: moment(result?.subscription?.startDate).add(30, "days").format("YYYY-MM-DD"),
        price: activePlan?.subscription_plan_data?.subscription_plan_variations?.[0]?.subscription_plan_variation_data?.phases?.[0]?.pricing?.price_money?.amount,
        planName: activePlan?.subscription_plan_data?.name,
        activePlan: count > 0 ? existSubscription?.planName : activePlan?.subscription_plan_data?.name
      };
      await this.paymentSubscriptionService.insertSubsciption(subscriptionData);
      return JSON.parse(JSON.stringify(result.subscription, (key, value) => (typeof value === "bigint" ? value.toString() : value)));
    } catch (error) {
      console.log("ERROR--", error?.errors?.[0]);
      return {
        error: true,
        message: "Payment Failed",
        category: error?.errors?.[0]?.category,
        code: error?.errors?.[0]?.code,
        detail: error?.errors?.[0]?.detail  //'This request could not be authorized.'
      }
    }
  }

  async createSubscriptionPlan() {
    try {
      const idempotency_key = crypto.randomBytes(22).toString("hex");
      // create Plan
      const newPlan = {
        idempotency_key: idempotency_key,
        object: {
          type: "SUBSCRIPTION_PLAN",
          id: "#basicPlan",
          subscription_plan_data: {
            name: "Navihome Basic Plan",
            phases: [
              {
                cadence: "MONTHLY",
                recurring_price_money: {
                  amount: 2999,
                  currency: "USD"
                }
              }
            ]
          }
        }
      };

      await axios
        .post(`${process.env.SQUARE_URL}/v2/catalog/object`, newPlan, this.headers)
        .then((respo) => {
          console.log("respo---", respo);
          return respo;
        })
        .catch((error) => {
          console.log("error---", error);
          return error;
        });
    } catch (err) {
      console.log(err);
      return err;
    }
  }

  async getListSubscriptionPlan() {
    try {
      let planResult = [];
      await axios
        .get(`${process.env.SQUARE_URL}/v2/catalog/list`, this.headers)
        .then((respo) => {
          planResult = respo.data.objects;
        })
        .catch((error) => {
          console.log("error---", error);
          return error;
        });
      // const squareClient = new Client({
      //   environment: Environment.Production, // Change to square.Environment.Production for testing  for prod Production
      //   accessToken: process.env.SQUARE_ACCESS_TOKEN,
      //   squareVersion: process.env.SQUARE_API_VERSION
      // });
      // const planResult: any = await squareClient.catalogApi.listCatalog();
      // return JSON.parse(
      //   JSON.stringify(
      //     planResult.result.objects,
      //     (key, value) => (typeof value === "bigint" ? value.toString() : value) // return everything else unchanged
      //   )
      // );
      return planResult.filter(obj => obj.subscription_plan_data);
    } catch (err) {
      console.log(err);
      return err;
    }
  }

  async pauseSubscriptionPlan(agentId: number) {
    try {
      const squareClient = new Client({
        environment: Environment.Production, // Change to square.Environment.Production for testing  for prod Production
        accessToken: process.env.SQUARE_ACCESS_TOKEN,
        squareVersion: process.env.SQUARE_API_VERSION
      });
      const existSubscription = await this.paymentSubscriptionService.getSubscription(agentId);
      const body = {
        pauseEffectiveDate: moment().format("YYYY-MM-DD"),
        pauseReason: "User want to pause account . Might be he can enable after some time."
      };
      if (existSubscription?.subscriptionId) {
        const { result } = await squareClient.subscriptionsApi.pauseSubscription(existSubscription.subscriptionId, body);
        return JSON.parse(
          JSON.stringify(
            result.subscription,
            (key, value) => (typeof value === "bigint" ? value.toString() : value) // return everything else unchanged
          )
        );
      }
    } catch (err) {
      console.log(err);
      return err;
    }
  }

  async deleteSubscriptionPlan(agentId: number) {
    try {
      const squareClient = new Client({
        environment: Environment.Production, // Change to square.Environment.Production for testing  for prod Production
        accessToken: process.env.SQUARE_ACCESS_TOKEN,
        squareVersion: process.env.SQUARE_API_VERSION
      });
      const existSubscription = await this.paymentSubscriptionService.getSubscription(agentId);
      const { result } = await squareClient.subscriptionsApi.cancelSubscription(existSubscription.subscriptionId);
      if (result?.actions?.[0]?.id) {
        const response = await squareClient.subscriptionsApi.deleteSubscriptionAction(existSubscription.subscriptionId, result?.actions?.[0]?.id);
        return response;
      }
    } catch (err) {
      console.log(err);
      return err;
    }
  }

  async resumeSubscriptionPlan(agentId: number) {
    try {
      const squareClient = new Client({
        environment: Environment.Production, // Change to square.Environment.Production for testing  for prod Production
        accessToken: process.env.SQUARE_ACCESS_TOKEN,
        squareVersion: process.env.SQUARE_API_VERSION
      });
      const existSubscription = await this.paymentSubscriptionService.getSubscription(agentId);
      const body = {
        resumeEffectiveDate: moment().format("YYYY-MM-DD")
      };
      if (existSubscription?.subscriptionId) {
        const response = await squareClient.subscriptionsApi.resumeSubscription(existSubscription.subscriptionId, body);
        return response;
      }
    } catch (err) {
      console.log(err);
      return err;
    }
  }

  async activatepaidToFreePlan(agentId: any, selectedPlan: any) {
    const deleleResponse = await this.deleteSubscriptionPlan(agentId);
    // get selected plan
    const plan = await this.getListSubscriptionPlan();
    const activePlan = plan.find((item) => item?.subscription_plan_data?.name === selectedPlan && item.present_at_all_locations);
    const existSubscription = await this.paymentSubscriptionService.getSubscription(agentId);
    const date = moment().format("YYYY-MM-DD");
    const subscriptionData = {
      agentId: agentId,
      subscriptionId: `free-${"2324344-rerdf-43434"}-sub-${moment().format("YYYY-MM-DD")}-id`,
      planId: `free-${"223232-fdsfdsf-33443"}-plan-${moment().format("YYYY-MM-DD")}-id`,
      status: "ACTIVE",
      startDate: new Date(),
      canceledDate: date,
      price: 0,
      planName: "Navihome Free Plan",
      activePlan: activePlan?.subscription_plan_data?.subscription_plan_variations?.[0]?.subscription_plan_variation_data?.phases?.[0]?.pricing?.price_money?.amount > existSubscription?.price ? existSubscription?.planName : activePlan?.subscription_plan_data?.name ?? "Navihome Free Plan"
    };

    const response = await this.paymentSubscriptionService.insertSubsciption(subscriptionData);
    return response
  }
}

Is this the same .env your using for all your other API calls because they have the correct version. :slightly_smiling_face:

Yes. Same .env file for entire backend

Hi @Bryan-Square,

Have you found any gaps in our implementation?
we are stuck in going live due to this, can we connect over teams or gmeet if possible.

Kindly do the needful

I’m not seeing anything wrong with what you provided. If you search your entire application for 2022-06-16 do you get any results? :slightly_smiling_face:

Hi @Bryan-Square,

I have checked our entire application code for this date (2022-06-16) but no results.

Is it possible to schedule a meeting with our developer team? we can show and explain the complete flow of square api used in our application. you can correct us if anything is wrong over there.

if you are ok, please share the email id where i can send the developers email address for scheduling the meeting

Hi Bryan,

Thanks for all your help, but we’re still a little stuck. Apologies that I’m technically out on PTO this week, but this is important and I’d love to schedule a call with our developers so you can see and hopefully help us clear why our code seems to be stuck with the outdated version.

What day/times work for you? Most days before 11am ET works well with our developer team.

Thanks so much,
Kymberli

Hi Kymberli,

I’m happy to jump on a call however I’m on the west coast. Have any of your developers spun up a new project that uses the SDK to calls our API and confirm that the correct version is being set? There are only two ways the version is configured which is in the application itself or if the version is explicitly set in the header.

Also have you tried removing the header from the .env since you have the API version set in the application? :slightly_smiling_face:

Thanks Bryan. I have forwarded on the message and will see if there’s any update next week. If not, can we try to schedule a time that works for your schedule (I know it’s a little rough given the time zone difference), but maybe first thing in the morning (9am PT) for you?

Thanks,
Kymberli