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

Angular中如何渲染iyzico返回的checkoutFormContent支付表单?

解决iyzico支付表单嵌入问题

问题分析

你当前的代码存在三个核心问题:

  1. 未将获取到的checkoutFormContent插入到指定的iyzipay-checkout-form容器中
  2. 错误使用forEach处理云函数返回值(httpsCallable返回的是包含data属性的对象,而非可遍历数组)
  3. Angular默认会过滤innerHTML中的脚本,直接插入无法自动执行

解决方案步骤

1. 导入必要依赖

在组件文件顶部引入Angular的DOM安全和视图操作工具:

import { DomSanitizer, SafeHtml } from '@angular/platform-browser';
import { ElementRef, ViewChild, ChangeDetectorRef } from '@angular/core';

2. 组件内定义变量与视图引用

在组件类中添加以下内容:

// 绑定支付表单容器的视图引用
@ViewChild('iyzipayCheckoutForm') iyzipayCheckoutForm!: ElementRef;
// 存储经过安全处理的支付表单HTML
sc!: SafeHtml;

constructor(
  private fnc: AngularFireFunctions,
  private sanitizer: DomSanitizer,
  private cdf: ChangeDetectorRef
) {}

3. 修正支付方法逻辑

修改pay2方法,正确获取并处理支付表单内容:

async pay2() {
  // 调用云函数获取支付表单内容
  const resp = await this.fnc.httpsCallable('test')({
    email: "blabla@gmail.com",
    name: "bla",
    surname: "alb"
  });
  
  // 从返回结果中提取checkoutFormContent(根据实际返回结构调整,此处假设在resp.data中)
  const checkoutContent = resp.data.checkoutFormContent;
  
  // 标记内容为安全HTML,避免Angular过滤脚本
  this.sc = this.sanitizer.bypassSecurityTrustHtml(checkoutContent);
  
  // 触发变更检测,确保HTML渲染
  this.cdf.detectChanges();
  
  // 手动执行容器内的脚本
  this.executeScriptsInElement(this.iyzipayCheckoutForm.nativeElement);
}

4. 添加脚本执行辅助方法

在组件类中添加方法,手动提取并执行插入的脚本:

private executeScriptsInElement(element: HTMLElement) {
  const scripts = element.querySelectorAll('script');
  scripts.forEach(script => {
    const newScript = document.createElement('script');
    
    // 复制原脚本的属性与内容
    if (script.type) newScript.type = script.type;
    if (script.src) newScript.src = script.src;
    if (script.textContent) newScript.textContent = script.textContent;
    
    // 插入到页面头部执行脚本
    document.head.appendChild(newScript);
    
    // 执行完成后移除临时脚本
    setTimeout(() => document.head.removeChild(newScript), 0);
  });
}

5. 修改HTML模板

更新模板,使用[innerHTML]绑定安全HTML,并添加视图引用:

<div class="row">
  <button (click)="pay2()" class="btn btn-dark">Accept Payment</button>
</div>
<div #iyzipayCheckoutForm id="iyzipay-checkout-form" class="responsive" [innerHTML]="sc"></div>

关键说明

  • Angular的安全机制会默认过滤innerHTML中的脚本,因此必须用DomSanitizer.bypassSecurityTrustHtml标记内容为安全
  • 直接插入的脚本不会自动执行,需要手动提取并创建新的<script>标签插入到页面中触发执行
  • 云函数返回值的结构需根据实际情况调整,确保正确获取checkoutFormContent

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 07:39:23