admin管理员组

文章数量:1391736

I'm building a Chrome extension that calls the GoHighLevel (GHL) API to create and manage contacts. When I do the same request in Postman using my GHL API key as a bearer token, it works (status 200). But when my extension code runs, I get 401 Unauthorized.

What I'm Doing

Manifest.json (Manifest v3) has:

json
Copy
Edit
{
  "manifest_version": 3,
  "name": "GoHighLevel Messenger Extension",
  "version": "1.0",
  "permissions": [
    "storage",
    "activeTab",
    "scripting"
  ],
  "host_permissions": [
    "/*"
  ],
  "background": {
    "service_worker": "background.js"
  },
  "content_scripts": [
    {
      "matches": ["<all_urls>"],
      "js": ["content_script.js"]
    }
  ],
  "action": {
    "default_popup": "popup.html"
  }
}

I added "host_permissions" for /* to handle possible CORS or cross-origin issues.

popup.js snippet (where I fetch the GHL endpoint):

js
Copy
Edit
chrome.storage.local.get("ghl_api_key", async (res) => {
  if (!res.ghl_api_key) {
    alert("No GHL API key found. Please save one first.");
    return;
  }

  const apiKey = res.ghl_api_key;
  const url = ";; 
  // Note: 54HQKNLdRdp1puWWYfv7 is my location ID

  try {
    const resp = await fetch(url, {
      method: "POST",
      headers: {
        "Authorization": `Bearer ${apiKey}`,
        "Content-Type": "application/json"
      },
      body: JSON.stringify({
        firstName: "Test",
        email: "[email protected]",
        phone: "+15555555555"
      })
    });

    console.log("Fetch status:", resp.status); // Logs 401
    if (!resp.ok) {
      // e.g. "Error creating contact: 401"
      alert(`Error creating contact: ${resp.status}`);
    } else {
      const data = await resp.json();
      console.log("Success:", data);
    }
  } catch (err) {
    console.error("Fetch error:", err);
  }
});

Testing in Postman:

http
Copy
Edit
POST 
Authorization: Bearer <MY_SAME_API_KEY>
Content-Type: application/json

{
  "firstName": "Test",
  "email": "[email protected]",
  "phone": "+15555555555"
}

This returns 200 OK and creates a contact successfully.

But in the Chrome extension environment, the same token and body yield 401 Unauthorized.

What I’ve Tried

  • Verified the key is correct (no typos) and it works in Postman.
  • Added "host_permissions": ["/*"] in manifest.json.
  • Ensured I only set "Content-Type": "application/json" on POST calls (for GET calls, I omit it).
  • Confirmed my extension logs say 401 with no additional message.
  • Double-checked the location ID matches the one in Postman.
  • Generated a new API key in GHL, tested in Postman again (works), extension still 401.

Question: Why might my extension’s fetch call get a 401 from GoHighLevel, even though the same bearer token works in Postman? Am I missing any additional headers or steps in a Chrome extension context?

Any insight is appreciated — thanks in advance!

本文标签: