Edits history of script submission #23734 for ' Send Draft Order Invoice (shopify)'

  • bunnative
    One script reply has been approved by the moderators
    Ap­pro­ved
    //native
    
    /**
     * Send Draft Order Invoice
     * Email the draft order's invoice (a checkout link) to the customer. Leave to empty to use the draft order's email; subject and custom_message override the store's invoice template.
     */
    export async function main(
      auth: RT.Shopify,
      draft_order_id: string,
      to: string | undefined,
      subject: string | undefined,
      custom_message: string | undefined,
      bcc: string[] | undefined
    ) {
      const id = draft_order_id.startsWith("gid://")
        ? draft_order_id
        : `gid://shopify/DraftOrder/${draft_order_id}`
      const response = await fetch(
        `https://${auth.store_name}.myshopify.com/admin/api/2026-10/graphql.json`,
        {
          method: "POST",
          headers: {
            "X-Shopify-Access-Token": auth.token,
            "Content-Type": "application/json",
            Accept: "application/json",
          },
          body: JSON.stringify({
            query: `mutation ($id: ID!, $email: EmailInput) { draftOrderInvoiceSend(id: $id, email: $email) { draftOrder { id name status email invoiceUrl invoiceSentAt } userErrors { field message } } }`,
            variables: {
              id,
              email: {
                to: to || undefined,
                subject: subject || undefined,
                customMessage: custom_message || undefined,
                bcc: bcc?.length ? bcc : undefined,
              },
            },
          }),
        }
      )
    
      if (!response.ok) {
        throw new Error(`${response.status} ${await response.text()}`)
      }
    
      const { data, errors } = await response.json()
      if (errors) {
        throw new Error(JSON.stringify(errors))
      }
    
      if (data.draftOrderInvoiceSend.userErrors.length) {
        throw new Error(JSON.stringify(data.draftOrderInvoiceSend.userErrors))
      }
    
      return data.draftOrderInvoiceSend
    }
    

    Submitted by hugo989 3 hours ago