hypercharge/hypercharge-php

Hypercharge PHP 库 / SDK

1.25.6 2015-12-14 10:41 UTC

This package is not auto-updated.

Last update: 2024-09-28 15:40:19 UTC


README

Hypercharge支付网关的PHP SDK。

Latest Stable Version Build Status

在OSX/Linux上测试了PHP > 5.3

hypercharge-API-doc版本2.24(2014/09/16)匹配

安装

不要手动下载Hypercharge PHP SDK文件。PHP包管理器 composer 会处理这些。

假设 MY_PROJECT/ 是你的项目根目录。

执行以下三个步骤

  1. 下载composer.pharMY_PROJECT/composer.phar

  2. 使用你的文本编辑器创建一个 MY_PROJECT/composer.json 包含以下内容

{
  "require": {
    "php": ">=5.3",
    "hypercharge/hypercharge-php": "*"
  }
}

这将告诉composer安装最新的Hypercharge PHP SDK版本。

  1. 在shell(DOS控制台或终端)中转到 MY_PROJECT/ 并运行以下命令
$ php composer.phar install

这将下载并安装Hypercharge PHP SDK及其依赖项到 MY_PROJECT/vendor/

显示已安装的内容

$ php composer.phar show --installed
hypercharge/hypercharge-php    1.25.5 Hypercharge PHP Library / SDK
hypercharge/hypercharge-schema 1.25.2 Hypercharge API JSON Schema
hypercharge/json-schema-php    1.3.3  A library to validate a json schema.

nice.

注意:稍后,当将你的项目部署到服务器时,也要上传完整的 MY_PROJECT/vendor/ 目录。 MY_PROJECT/vendor/ 包含已安装的包和自动加载文件。

配置

要开始,将以下其中一个片段添加到你的全局配置文件中。

沙箱(用于测试)

Hypercharge支持创建测试账户并发送你登录名和密码。用于开发和测试。不会进行真实货币的转账。

// config.php
require_once dirname(__DIR__).'/vendor/autoload.php';
Hypercharge\Config::set(
   'YOUR-MERCHANT-TEST-LOGIN'
  ,'YOUR-MERCHANT-TEST-PASSWORD'
  ,Hypercharge\Config::ENV_SANDBOX
);

实时

当你的Hypercharge注册完成时,我们的支持团队将发送你的实时登录名和密码。这里可以进行真实货币交易!

// config.php
require_once dirname(__DIR__).'/vendor/autoload.php';
Hypercharge\Config::set(
   'YOUR-MERCHANT-LOGIN'
  ,'YOUR-MERCHANT-PASSWORD'
  ,Hypercharge\Config::ENV_LIVE
);

如果你的项目中没有 MY_PROJECT/vendor/autoload.php,请按照安装说明进行操作。

信用卡销售交易

向hypercharge渠道提交77.00美元作为信用卡销售。

注意:你必须遵守PCI标准才能处理信用卡数据。很可能会发生你并不符合PCI标准的情况,在这种情况下,你将使用我们的Web支付表单或我们的移动支付

require_once 'config.php';

// see field 'currency'
$channelToken = 'YOUR-USD-CHANNEL-TOKEN';

$sale = Hypercharge\Transaction::sale($channelToken, array(
  'currency'          => 'USD'
  ,'amount'           => 7700 // in cents, must be int
  ,'transaction_id'   => 'YOUR-GENERATED-UNIQUE-ID' // TODO your order-id here
  ,'usage'            => 'Appears in the customers bank statement'
  ,'card_holder'      => 'Max Mustermann'
  ,'expiration_month' => '07'
  ,'expiration_year'  => '2018'
  ,'card_number'      => '4200000000000000'
  ,'cvv'              => '123'
  ,'customer_email'   => 'max@mustermann.de'
  ,'customer_phone'   => '+403012345678'

  // TODO: dummy for cli run only. remove!
  ,'remote_ip'        => '127.0.0.1'
  // TODO: uncomment
  //,'remote_ip'        => $_SERVER['REMOTE_ADDR']

  ,"billing_address" => array(
      "first_name" =>"Max",
      "last_name"  =>"Mustermann",
      "address1"   =>"Muster Str. 12",
      "zip_code"   =>"10178",
      "city"       =>"Berlin",
      "country"    =>"DE"
  )
));

if($sale->isApproved()) {
  // cc transaction successfull
} else {
  //
}

要查看本地验证错误,请将 Hypercharge\Transaction::sale 调用包裹在 try catch 中。

require_once 'config.php';

$channelToken = 'YOUR-USD-CHANNEL-TOKEN';
try {
  $sale = Hypercharge\Transaction::sale($channelToken, array(
    'currency'          => 'USD'
    ,'amount'           => 7700 // in cents, must be int
    ,'transaction_id'   => 'YOUR-GENERATED-UNIQUE-ID' // TODO your order-id here
    ,'usage'            => 'Appears in the customers bank statement'
    ,'card_holder'      => 'Max Mustermann'
    ,'expiration_month' => '07'
    ,'expiration_year'  => '2018'
    ,'card_number'      => '4200000000000000'
    ,'cvv'              => '123'
    ,'customer_email'   => 'max@mustermann.de'
    ,'customer_phone'   => '+403012345678'
    ,'remote_ip'        => $_SERVER['REMOTE_ADDR']
    ,"billing_address" => array(
        "first_name" =>"Max",
        "last_name"  =>"Mustermann",
        "address1"   =>"Muster Str. 12",
        "zip_code"   =>"10178",
        "city"       =>"Berlin",
        "country"    =>"DE"
    )
  ));

  if($sale->isApproved()) {
    echo "cc transaction successfull\n";
    print_r($sale);
  } else {
    echo "cc transaction FAILED\n";
    print_r($sale);
  }
} catch(Hypercharge\Errors\ValidationError $e) {
  echo "local validation errors\n";
  print_r( $e->errors );

} catch(Exception $e) {
  echo "severe error\n";
  print_r($e);
}

Web支付表单(WPF)会话

以下示例更复杂。

  • 创建一个WPF会话。
  • 将客户浏览器重定向到提供的WPF URL
  • 客户提交WPF并被重定向到您提供的return_success_url。与此同时,hypercharge通过调用 notification_url 通知您的后端,提供支付状态。
require_once 'config.php';

try {
  // create the WPF payment session
  $payment = Hypercharge\Payment::wpf(array(
    'currency' => 'EUR'
    ,'amount' => 1000 // in cents
    ,'transaction_id' => 'YOUR-GENERATED-UNIQUE-ID' // TODO replace with your e.g. order id
    ,'description' => 'Appears as intro text in the WPF form'
    ,'usage' => 'Appears in the customers bank statement'

    // TODO: set your PaymentNotification handler url here
    ,'notification_url' => 'https://your-server.com/hypercharge-wpf-notifications.php'

    // TODO: set your return pages for the user here. These are the pages he is shown after leaving the WPF
    ,'return_success_url' => 'http://your-server.com/payment-return-page.php?status=success'
    ,'return_failure_url' => 'http://your-server.com/payment-return-page.php?status=failure'
    ,'return_cancel_url'  => 'http://your-server.com/payment-return-page.php?status=cancel'

    ,'billing_address' => array(
        'first_name' =>'Max',
        'last_name'  =>'Mustermann',
        'address1'   =>'Muster Str. 12',
        'zip_code'   =>'10178',
        'city'       =>'Berlin',
        'country'    =>'DE'
    )
  ));

  if($payment->shouldRedirect()) {
    // ok, WPF session created.

    // TODO: pseudocode, comment or replace with your own business logic!
    store_hypercharge_payment_unique_id_to_your_order( $payment->unique_id );

    // redirect user to WPF
    header('Location: '. $payment->getRedirectUrl());

  // handle errors...
  } elseif($payment->isPersistentInHypercharge()) {
    // payment has been created in hypercharge but something went wrong.

    // TODO: pseudocode, comment or replace with your own business logic!
    store_hypercharge_payment_unique_id_to_your_order( $payment->unique_id );

    // 1.) check $payment->error (a subclass of Hypercharge\Errors\Error)
    //     and show error message to customer
    // 2.) manually login to hypercharge merchant backend.
    //     Go to "Payments", search by unique_id and analize the log messages.

  } else {
    // TODO handle error
    // authentication error? check $login, $password
    // inputdata error? check your php code for missing or misspelled fields.

  }

} catch(Hypercharge\Errors\ValidationError $e) {
  // no payment created in hypercharge because of local pre-validation errors

  // show validation errors to customer
  // $e->errors is an Array of Hash, format: [ { "property": String , "message" : String }, ... ]

} catch(Exception $e) {
  // severe error
  // log $e
  // display apologies to customer
}

默认情况下,WPF以英语显示('en')。如果您想使用德语WPF,只需将重定向行更改为

    header('Location: '. $payment->getRedirectUrl('de'));

WPF支付通知

使用支付通知,Hypercharge会通知您的服务器有关支付状态的变化,例如,当支付成功(状态 approved)或以某种方式失败时。支付通知是在后台进行的服务器到服务器的请求。既不涉及网页浏览器,也不涉及用户交互。

hypercharge                 your-server.com/hypercharge-wpf-notifications.php
    |   -> http POST request: notification ->   |
    |                                           |     -> store notification status to your DB
    |                                           |     -> e.g. trigger shipping (sucess) or send failure email to user (NOT success)
    |   <- http response: ack              <-   |

您将PHP脚本放置在您指定的URL下,作为 notification_url(例如,“Web支付表单(WPF)会话”示例中的“https://your-server.com/hypercharge-wpf-notifications.php”)

一个示例

require_once 'config.php';

// $notification is an instance of Hypercharge\PaymentNotification
$notification = Hypercharge\Payment::notification($_POST);
if($notification->isVerified()) {
  $payment = $notification->getPayment();
  if($notification->isApproved()) {

    ////////////////////////////////////////
    // payment successfull
    // implement your business logic here
    ////////////////////////////////////////

  } else {

    ////////////////////////////////////////
    // payment NOT successfull
    // check $payment->status
    // implement your business logic here
    ////////////////////////////////////////

  }

  // http response.
  // Tell hypercharge the notification has been successfully processed
  // and ensure output ends here
  die( $notification->ack() );

} else {
  // signature invalid or message does not come from hypercharge.
  // check your configuration or notificatoin request origin
}

请参阅PaymentNotification类的定义,了解如何使用$notification$payment

以下是一个带有符号业务逻辑的伪代码示例

require_once 'config.php';

$notification = Hypercharge\Payment::notification($_POST);
if($notification->isVerified()) {
  $payment = $notification->getPayment();
  if($notification->isApproved()) {

    ////////////////////////////////////////
    // payment successfull
    // implement your business logic here

    // example as pseudocode, replace with your own code...

    // store notification status to your database
    // Notice: to be 100% racecondition proof update status to 'payment_approved' has to be done atomically
    $updatedRows = update_order(array(
      'set'   => array('status'=> 'payment_approved'),
      'where' => array('status'=> 'waiting_for_payment_approval'
                      ,'hypercharge_unique_id' => $payment->unique_id
      )
    ));

    if($updatedRows == 1) {
      // ok, start shipping
      $order = find_order_where(array('status' => 'payment_approved'
                                      ,'hypercharge_unique_id' => $payment->unique_id
      ));
      $order->ship_goods_to_customer();

    } else {
      // hypercharge notification already received! ignore duplicate notification.
    }
    //
    // END of your business logic
    ////////////////////////////////////////

  } else {

    ////////////////////////////////////////
    // payment NOT successfull
    // check $payment->status and handle it

    // ...

    // END of your business logic here
    ////////////////////////////////////////

  }

  // Tell hypercharge the notification has been successfully processed
  // and ensure output ends here
  die( $notification->ack() );

} else {
  // signature invalid or message does not come from hypercharge.
  // check your configuration or notificatoin request origin
}

创建移动支付会话

移动支付与WPF支付相当相似。会话创建的数据略有不同。通知代码与WPF通知类似。

your_server -> POST XML -> hypercharge

require_once 'config.php';

try {
  // create the mobile payment session
  $payment = Hypercharge\Payment::mobile(array(
    'currency' => 'EUR'
    ,'amount' => 1000 // in cents
    ,'transaction_id' => 'YOUR-GENERATED-UNIQUE-ID'
    ,'usage' => 'Appears in the customers bank statement'
    ,'notification_url' => 'https://your-server.com/hypercharge-wpf-notifications.php'
  ));

  if($payment->shouldContinueInMobileApp()) {
    // ok, mobile payment session created.

    save_payment_unique_id_to_order($payment->unique_id);

    // tell your mobile device where to
    // a) submit credit card xml data to (submit_url)
    // b) cancel the payment if user presses 'cancel' in your mobile app (cancel_url)
    // see example below.
    die(json_encode($payment));

  } else {

    // TODO handle error
    // vaildation
    // authentication error -> check $login, $password
    // inputdata error -> check your php code for missing
    // or misspelled fields in $paymentData

  }
} catch(Hypercharge\Errors\Error $e) {
  // no payment created in hypercharge because of local pre-validation errors

  // check your php code
  // display apologies to customer "Sorry, no payment possible at the moment."
}

从移动设备提交移动支付

以下是一个示例,您的移动应用程序将XML发布到$payment->submit_url以处理支付。

<payment>
  <payment_method>credit_card</payment_method>
  <card_holder>Manfred Mann</card_holder>
  <card_number>4200000000000000</card_number>
  <cvv>123</cvv>
  <expiration_year>2015</expiration_year>
  <expiration_month>12</expiration_month>
</payment>

如果您担心通过互联网POST信用卡数据:该$payment->submit_url看起来可能像https://testpayment.hypercharge.net/mobile/submit/eabcb7a41044e764746b0c7e32c1e9d1,因此XML将加密传输。

测试

对hypercharge-php本身运行测试必须在MY_PROJECT之外进行。将hypercharge-php克隆到其自己的目录中

git clone https://github.com/hypercharge/hypercharge-php.git

进入目录

cd hypercharge-php

安装composer(此处为1.0.0-alpha7,您可以自由使用更新的版本)

curl -o composer.phar https://getcomposer.org.cn/download/1.0.0-alpha7/composer.phar

安装开发依赖项

php composer.phar update --dev

单元测试

运行单元测试

php test/all.php

您可能想知道输出意味着什么

File does not exist /home/hans/hypercharge-php/test/credentials.json. See README.md chapter 'Remote Tests' how to setup credentials for testing.

简单地阅读下一章。

远程测试

远程测试会对hypercharge沙盒(测试网关)进行HTTPS调用。

首先,您必须设置您的登录和渠道令牌

test/credentials.json.example复制到test/credentials.json。当hypercharge创建您的测试帐户时,您收到了凭据。将凭据添加到test/credentials.json。请参阅带有TODO标记的值。

运行远程测试

php test/remote.php

这将花费大约一分钟。

您可以使用环境变量

DEBUG=1 CREDENTIALS=development php test/remote.php
  • DEBUG=1详细输出。
  • CREDENTIALS=development切换到“开发”凭据。默认是sandbox

注意

  • test/credentials.json不应纳入您的代码存储库。例如,将其添加到.gitignore
  • 不要在您的实时凭据上运行远程测试。

保修

本软件按“现状”提供,不提供任何明确的或隐含的保证,包括但不限于适销性和特定目的适用性的隐含保证。