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

使用YouCanPay PHP SDK生成支付令牌遇类找不到及表单异常问题

问题描述

使用YouCanPay支付网关PHP SDK时遇到两个核心问题:

  1. 令牌生成步骤中,PHP无法找到YouCanPay类实例,无法调用静态方法YouCanPay::setIsSandboxMode(true);,当前已使用命名空间use YouCan\Pay\YouCanPay;,怀疑是文件夹结构或命名空间配置问题(附项目文件夹结构截图)
  2. 调用createToken()方法时,支付表单无法显示;不调用该方法时,点击支付按钮会提示请求存在无效字段,请验证输入后重试,但所有参数均已完整填写

相关代码

HTML表单

<div id="error-container"></div>
<div id="payment-card"></div>
<button id="pay">Pay</button>

PHP代码

use YouCan\Pay\YouCanPay;

class ExamplePayment
{
    /**
     * Return a token to make payment for an order, this token is required to make payment with JS script.
     *
     * @return string
     */
    public function createToken()
    {
        // Enable sandbox mode, otherwise delete this line.
        YouCanPay::setIsSandboxMode(true);

        // Create a YouCan Pay instance
        $youCanPay = YouCanPay::instance()->useKeys('pri_sandbox_56cfe571-f671-42a6-a231-d58ec', 'pub_sandbox_a62be70f-d585-4e88-9c5b-563f2');

        // Create the order token
        $token = $youCanPay->token->create(
            "order-id",
            "2000",
            "USD",
            "175.107.236.174",
            "https://smmpanelauto.com/orders-status/success",
            "https://smmpanelauto.com/orders-status/error"
        );

        echo $token->getId();
    }
}

JS代码

<script type="text/javascript">
    // Create a YouCan Pay instance.
    const ycPay = new YCPay('pub_sandbox_a62be70f-d585-4e88-9c5b-563f2', {
        formContainer: '#payment-card',
        locale: 'en',
        isSandbox: true,
        errorContainer: '#error-container',
        // token: 'token_x6gf0_....'
    });

    // render the form
    ycPay.renderCreditCardForm();
    
    // start the payment on button click
    var el = document.getElementById('pay');
    if(el){
        <?php   
             $a = new ExamplePayment; 
            ?>
        el.addEventListener('click', function(){
              // execute the payment
              ycPay.pay("<?php $a->createToken(); ?>") //using token
                .then(successCallback)
                .catch(errorCallback);
            });
    }
    function successCallback(response) {
      console.log(rsponse);
    }
    
    function errorCallback(response) {
        console.log(rsponse);
    }
</script>

解决方案

一、解决YouCanPay类找不到的问题

  1. 确认依赖安装与自动加载
    • 必须通过Composer安装SDK,执行composer require youcan/payment-php-sdk重新安装,避免手动下载文件导致的命名空间映射错误
    • 确保项目PHP文件开头已引入Composer自动加载文件:
      require __DIR__ . '/vendor/autoload.php';
      
  2. 验证文件结构与命名空间
    • 检查vendor/youcan/payment-php-sdk/src/YouCan/Pay/目录下是否存在YouCanPay.php文件
    • 打开YouCanPay.php,确认文件顶部的命名空间为namespace YouCan\Pay;,必须与文件路径严格匹配(遵循PSR-4规范)

二、解决表单不显示及支付字段无效问题

  1. 修复令牌生成的输出逻辑
    • 当前createToken()直接echo令牌ID,会破坏HTML渲染流程导致表单不显示,修改为返回令牌而非输出:
      public function createToken()
      {
          // ... 原有代码保持不变 ...
          return $token->getId(); // 替换echo为return
      }
      
    • 在JS中调用时,通过echo输出返回值:
      ycPay.pay("<?php echo $a->createToken(); ?>")
      
  2. 改用异步方式获取令牌
    • 页面加载时实例化ExamplePayment并生成令牌会阻塞渲染,建议点击按钮时通过AJAX异步获取令牌:
      el.addEventListener('click', function(){
          fetch('get-token.php') // 新建独立文件处理令牌生成
              .then(response => response.text())
              .then(token => {
                  ycPay.pay(token)
                      .then(successCallback)
                      .catch(errorCallback);
              })
              .catch(err => console.error('获取令牌失败:', err));
      });
      
    • get-token.php示例代码:
      require __DIR__ . '/vendor/autoload.php';
      use YouCan\Pay\YouCanPay;
      
      class ExamplePayment { /* 保留原有createToken方法 */ }
      
      $a = new ExamplePayment;
      echo $a->createToken();
      
  3. 校验支付参数合法性
    • amount参数必须是整数类型,将代码中的"2000"改为2000
    • order-id需保证唯一性,避免重复提交同一订单ID
    • 客户IP建议动态获取,替换固定IP为$_SERVER['REMOTE_ADDR'],确保是当前访问用户的真实IP

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 02:10:35