You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在React JS中获取script标签内的PagSeguro.encryptCard函数

问题原因及解决方案

错误原因

  • 调用时机错误:动态插入的script标签是异步加载的,你在appendChild后立刻调用PagSeguro.encryptCard时,远程脚本还未完成下载和执行,全局还没有挂载PagSeguro对象。
  • 取值路径错误:PagSeguro是第三方脚本加载完成后挂载到window全局对象上的属性,不是你创建的script元素的属性,script.PagSeguro的写法本身不成立。

你遇到的报错中文翻译为:类型错误:无法读取未定义的属性(读取'encryptCard')

修复方案

把加密逻辑放到script的onload回调中执行,保证脚本加载完成后再调用相关方法,修改后的完整代码如下:

import React, {useEffect} from 'react'

function Pay(){   
  useEffect(() => {
    const container = document.getElementById("mydiv"); 

    // 封装卡加密逻辑
    const handleEncryptCard = () => {
      // 确保全局存在PagSeguro再调用
      if (!window.PagSeguro) return
      const card = window.PagSeguro.encryptCard({
        publicKey: "MINHA_CHAVE_PUBLICA",
        holder: "Nome Sobrenome",
        number: "4242424242424242",
        expMonth: "12",
        expYear: "2030",
        securityCode: "123"
      });
      const encrypted = card.encryptedCard;
      console.log('加密结果', encrypted)
    }

    // 避免重复加载脚本
    if (window.PagSeguro) {
      handleEncryptCard()
      return
    }

    const script = document.createElement('script');
    script.src = 'https://assets.pagseguro.com.br/checkout-sdk-js/rc/dist/browser/pagseguro.min.js';
    script.async = true;
    // 脚本加载完成后执行加密逻辑
    script.onload = handleEncryptCard
    container.appendChild(script); 
       
    // 组件卸载时清理插入的脚本
    return () => {
      container.removeChild(script)
    }
  }, []);

  return (
    <div id="mydiv">
      <h1>Payment</h1>
    </div>
  );
}
export default Pay

额外说明

如果你的项目使用TypeScript,需要添加全局类型声明避免类型报错,可在项目的.d.ts类型定义文件中添加如下内容:

declare global {
  interface Window {
    PagSeguro: {
      encryptCard: (params: {
        publicKey: string;
        holder: string;
        number: string;
        expMonth: string;
        expYear: string;
        securityCode: string;
      }) => { encryptedCard: string }
    }
  }
}

内容的提问来源于stack exchange,提问作者YMELO

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 06:15:03