繁体   English   中英

如何在 Wordpress PHP 文件中隐藏外部 API 密钥?

[英]How can I hide an external API key in a Wordpress PHP file?

我花了几个小时试图研究和解决这个问题,但不幸的是仍在苦苦挣扎。

我在 Wordpress 中创建了一个自定义“课程”帖子类型,其中涉及使用嵌入式 Calendly 事件注册。 我正在使用 Calendly embed API 在发生事件注册时通知父 window 通知负载提供事件的URI ,然后我想使用 Calendly API 查找并返回事件的名称 我正在努力隐藏 header 中的 API 密钥:

    "Content-Type": "application/json",
    "Authorization": "Bearer MY_API_KEY"
  }

我试图在 wpconfig 中添加一行来定义密钥:

define( 'CALENDLY_KEY', '**key**' );

但我不知道如何在我的 function 中使用它而不通过“回声”暴露它。

任何建议将不胜感激。

下面的扩展代码:

<!-- Calendly widget script -->
<script type="text/javascript" src="https://assets.calendly.com/assets/external/widget.js" async></script>

<script>function isCalendlyEvent(e) {
  return e.data.event &&
         e.data.event.indexOf('calendly') === 0;
};
 
window.addEventListener(
  'message',
  function(e) {
    if (isCalendlyEvent(e)) {
        if (e.data.event == "calendly.event_scheduled") {
            console.log("event scheduled!");
            let event_uri = e.data.payload.event.uri;
            console.log(event_uri);

            fetch(event_uri, {
  "method": "GET",
  "headers": {
    "Content-Type": "application/json",
    "Authorization": "Bearer MY_API_KEY"
  }
})
.then(response => response.json())
  .then((json) => {
    console.log(json);
    let ordered_course = json.resource.name;
    console.log(ordered_course);

  })



        }
      console.log(e.data);
    }
  }
);</script>

您应该为您的 API 密钥使用 dotenv (.env) 文件。

您可以通过vlucas/phpdotenv package 和 Composer package 管理器在您的服务器上安装对 dotenv (.env) 的支持。

更简单的选择 - 如果您没有您所说的经验,则使用 WordPress 插件dontenv ,您将创建.env 文件并在其中写入 MY_API_KEY=123456,然后在您的代码中,您可以检索 this.env 密钥通过使用 getenv('MY_API_KEY');

This is for PHP but your code is JS, so you should install npm package manager then run npm i dontenv then in your code Bearer ${process.env.MY_API_KEY} .

此外,不应将 .env 文件上传到 GitHub。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM