Internal server error create subscription sandbox

Hello,

Application id: sq0idp-BxXyeNBSWtIaRXnujal9QQ
Environment: sandbox

I am getting internal server errors when trying to test creating subscriptions with subscriptions api createSubscription. I saw similar topics to this, but none of those solutions resolve my issue. Thank you for your help

Using nodejs my test code essentially is like this:

const subscriptionResult = await subscriptionsApi.createSubscription({
  idempotencyKey: crypto.randomBytes(12).toString('hex'),
  locationId: 'LQYAKTAMA4MDG',
  customerId: 'CM0280KCRRYP4DY2ZKK429WTNW',
  cardId: 'ccof:customer-card-id-ok',
  planVariationId: 'RMFGYCPYCUVZQ7J7RBYZZUL7',
  phases: [
    {
      ordinal: BigInt(0), 
      orderTemplateId: 'BOBQaSL44VYKkHjwiutrt0EKtP6YY'
    }
  ]
})

where the

  • location is the default sand box test account location
  • the customer is created with customer api createCustomer
  • the cardId is a test card on file from here
  • planVariationId is from a monthly cadence subscription plan created in the test account’s dashboard
  • the orderTemplateId is from a draft order for a product with one line item created for the test customer using orders api

: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:

https://developer.squareup.com/docs/app-marketplace/requirements/subscriptions-api

Additional Documentation

Test in the Sandbox
Square Sandbox
Square Node.js SDK Quickstart

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.

The error you’re encountering might be due to the phases field in your request. The phases field is not required when creating a subscription with the createSubscription endpoint. When you provide a planVariationId, the subscription plan’s phases are automatically used.

Try removing the phases field from your request and see if that resolves the issue. If the problem persists, please provide the exact error message you’re receiving for further assistance.

This answer was reviewed by @Bryan-Square.

Hello,

I have tried doing as you suggested, but I am still getting an Internal Server Error.

I first create a subscription plan variation as follows:

await catalogApi.upsertCatalogObject({
  idempotencyKey: crypto.randomBytes(12).toString('hex'),
  object: {
    id: '#temp',
    type: 'SUBSCRIPTION_PLAN',
    subscriptionPlanData: {
      name: 'Phased Monthly Subscription Plan With Variations',
      subscriptionPlanVariations: [
        {
          id: '#temp2',
          type: 'SUBSCRIPTION_PLAN_VARIATION',
          subscriptionPlanVariationData: {
            subscriptionPlanId: '#temp',
            name: 'Phased Monthly Subscription Main Variation',
            phases: [
              {
                ordinal: BigInt(0), 
                cadence: 'MONTHLY',
                pricing: {
                  type: 'STATIC',
                  priceMoney: {
                    amount: 1000n,
                    currency: 'USD'
                  }
                }
              }
            ]
          }
        }
      ]
    }
  }
})

The resulting subscription plan variation id is “T3CMYUTFIC5F4ZAEWBL5DX2U”. Then I use this id to create a subscription for a test customer using a test card Id. This time I removed the phases from the request as you suggested.

const subscriptionResult = await subscriptionsApi.createSubscription({
  idempotencyKey: crypto.randomBytes(12).toString('hex'),
  locationId: 'LQYAKTAMA4MDG',
  customerId: 'CM0280KCRRYP4DY2ZKK429WTNW',
  cardId: 'ccof:customer-card-id-ok',
  planVariationId: 'T3CMYUTFIC5F4ZAEWBL5DX2U'
})

The result is the error below (full output)

ApiError: Response status code was not ok: 500.
    {
  request: {
    method: 'POST',
    url: 'https://connect.squareupsandbox.com/v2/subscriptions',
    headers: {
      'Content-Type': 'application/json',
      authorization: '***',
      'user-agent': 'Square-TypeScript-SDK/39.1.1 (2024-12-18) node/20.17.0 (linux) ',
      'Square-Version': '2024-12-18'
    },
    body: {
      type: 'text',
      content: '{"idempotency_key":"59216198ff789749d2433569","location_id":"LQYAKTAMA4MDG","plan_variation_id":"T3CMYUTFIC5F4ZAEWBL5DX2U","customer_id":"CM0280KCRRYP4DY2ZKK429WTNW","card_id":"ccof:customer-card-id-ok"}'
    }
  },
  statusCode: 500,
  headers: {
    date: 'Fri, 27 Dec 2024 11:13:43 GMT',
    'content-type': 'application/json',
    'content-length': '164',
    connection: 'keep-alive',
    'cf-ray': '8f88e2008806d51e-CDG',
    'cf-cache-status': 'DYNAMIC',
    'strict-transport-security': 'max-age=631152000; includeSubDomains; preload',
    'frame-options': 'DENY',
    'square-version': '2024-12-18',
    'squareup--connect--v2--common--versionmetadata-bin': 'CgoyMDI0LTEyLTE4',
    'x-content-type-options': 'nosniff',
    'x-envoy-decorator-operation': '/v2/subscriptions/**',
    'x-frame-options': 'DENY',
    'x-sq-dc': 'aws',
    'x-sq-region': 'us-west-2',
    'x-xss-protection': '1; mode=block',
    'set-cookie': '__cf_bm=VJpa6z8XgJp_Q_SPVeNn.g_4jBGjJA1wjWPBjXkvy2s-1735298023-1.0.1.1-uMBavNzXQTJe04KnqY2tGniXbDX7AG9atuaGv_DMsIOgauRtZjhlZbVCN_oYzDZQ0M48WYs7lXw13Shm5Ezf.Q; path=/; expires=Fri, 27-Dec-24 11:43:43 GMT; domain=.squareupsandbox.com; HttpOnly; Secure; SameSite=None',
    vary: 'Accept-Encoding',
    server: 'cloudflare'
  },
  body: '{"errors": [{"code": "INTERNAL_SERVER_ERROR","detail": "An internal error has occurred, and the API was unable to service your request.","category": "API_ERROR"}]}\n',
  result: [Object: null prototype] {
    errors: [
      [Object: null prototype] {
        code: 'INTERNAL_SERVER_ERROR',
        detail: 'An internal error has occurred, and the API was unable to service your request.',
        category: 'API_ERROR'
      }
    ]
  },
  errors: [
    [Object: null prototype] {
      code: 'INTERNAL_SERVER_ERROR',
      detail: 'An internal error has occurred, and the API was unable to service your request.',
      category: 'API_ERROR'
    }
  ]
}

@Bryan-Square
Do you have any alternative here? I was not able to resolve the issue by following the AI generated message above, please see the code I tested and the error response. Thank you.

What API version are you using? :slightly_smiling_face:

@Bryan-Square
I’m using the square npm distribution 39.1.1 (sandbox environment). I did not set the api version explicitly so based on the response headers I believe it is square api version 2024-12-18

@Bryan-Square should I explicitly use a different version of the square api?

What are the steps you doing before you get this error? Like are you canceling to doing any other actions? :slightly_smiling_face:

@Bryan-Square
No, I’m not intentionally cancelling, and I can see the same logs for the requests and 500 responses on my square developer web console, so I do not believe this is the result of a cancellation or timeout on the client side. I’m doing this with a simple script, the entirety is as follows. I just compile the typescript and run with nodejs. I have also explicitly set the api version to the same as for my square application to be sure.

The output of executing this script is always the same 500 response I posted above. These are the api logs I see on the square developer web console.

request

content-length: 203
content-type: application/json
square-version: 2024-12-18
accept-encoding: gzip
accept: application/json
user-agent: Square-TypeScript-SDK/39.1.1 (2024-12-18) node/20.17.0 (linux)


    {
  "idempotency_key": "c6e79908d4f8e056b4c83c23",
  "location_id": "LQYAKTAMA4MDG",
  "plan_variation_id": "E7ZR2NYPMMMVWU6XB2STUGCL",
  "customer_id": "73PFZZ4JKQP55WBTW4REV111AR",
  "card_id": "ccof:customer-card-id-ok"
}

response

date: Thu, 09 Jan 2025 01:03:30 GMT
content-length: 164
content-type: application/json
square-version: 2024-12-18
strict-transport-security: max-age=31536000
x-frame-options: DENY


    {
  "errors": [
    {
      "code": "INTERNAL_SERVER_ERROR",
      "detail": "An internal error has occurred, and the API was unable to service your request.",
      "category": "API_ERROR"
    }
  ]
}

Are you able to check the server side logs to identify the source of this server side failure?

import * as Square from 'square'
import crypto from 'crypto'

const MAIN_LOCATION_ID = 'LQYAKTAMA4MDG' // main location for this application
const TEST_CUSTOMER_EMAIL = '[email protected]' // my company email for testing

const defaultClient = new Square.Client({
    squareVersion: '2024-12-18',
    environment: Square.Environment.Sandbox,
    accessToken: '***',
});

const { customersApi, catalogApi, subscriptionsApi } = defaultClient;

function bigIntReplacer(key: string, value: any): any {
  if (typeof value === "bigint") {
    return value.toString() + 'n';
  }
  return value;
}

const customer = await customersApi.createCustomer({
  emailAddress: TEST_CUSTOMER_EMAIL
})

const customerId = customer.result.customer.id

const catalogResult = await catalogApi.upsertCatalogObject({
  idempotencyKey: crypto.randomBytes(12).toString('hex'),
  object: {
    id: '#temp',
    type: 'SUBSCRIPTION_PLAN',
    subscriptionPlanData: {
      name: 'Phased Monthly Subscription Plan With Variations',
      subscriptionPlanVariations: [
        {
          id: '#temp2',
          type: 'SUBSCRIPTION_PLAN_VARIATION',
          subscriptionPlanVariationData: {
            subscriptionPlanId: '#temp',
            name: 'Phased Monthly Subscription Main Variation',
            phases: [
              {
                ordinal: BigInt(0), 
                cadence: 'MONTHLY',
                pricing: {
                  type: 'STATIC',
                  priceMoney: {
                    amount: 1000n,
                    currency: 'USD'
                  }
                }
              }
            ]
          }
        }
      ]
    }
  }
})

const planVariationId = catalogResult.result.catalogObject.subscriptionPlanData.subscriptionPlanVariations[0].id

const subscriptionResult = await subscriptionsApi.createSubscription({
  idempotencyKey: crypto.randomBytes(12).toString('hex'),
  locationId: MAIN_LOCATION_ID,
  customerId: customerId,
  cardId: 'ccof:customer-card-id-ok',
  planVariationId: planVariationId
})

console.log(JSON.stringify(subscriptionResult, bigIntReplacer, 2))

Hmm, taking a look but I did notice your amount has a n init.

:slightly_smiling_face:

(post deleted by author)

@Bryan-Square
the n is a javascript BigInt literal as required by the square javascript sdk. Without that I get typescript compilation errors.

Moreover, the result is a 500, not a client error, and not a transient issue like a 502 gateway timeout, please check the server side logs to enlighten me on the issue. Either there is a server failure, or there is a client error that is not being correctly reported with a 4xx status code. If the latter case please help me understand how I need to correct the request.