LoginSignup
5
8

More than 3 years have passed since last update.

[PHP]PAY.JPで決済する

Last updated at Posted at 2019-01-10

意外と参考になるとこがなかったんで書く。

ドキュメント
API リファレンス
テストカード
ライブラリ

WordPress使ってるので適宜かえてもらえば

controller.php

get_template_part('lib/payjp-php/init');
\Payjp\Payjp::setApiKey( SECRET_KEY );

$customer_id;//pay.jpにおける顧客ID

try {
  if ( empty($customer_id) ) {//初回
    $customer = \Payjp\Customer::create([//顧客登録
      'card' => $form['payjp-token'],
      'description' => 'メモなど'
    ]);
  }

  $charge = \Payjp\Charge::create([//課金処理
    'customer' => $customer_id,
    'amount'=> $form['amount'],
    'description' => '注文IDなど',
    'currency' => 'jpy'
  ]);

  if ( isset($charge['error']) ) {
    $this->errors[] = $charge['error']['message'];
  )

} catch (\Payjp\Error\Card $e) {
  $body = $e->getJsonBody();
  $this->errors[] = "ステータス: {$e->getHttpStatus()}";
  $this->errors[] = "タイプ: {$err['type']}";
  $this->errors[] = "コード: {$err['code']}";
  $this->errors[] = $err['message'];

} catch (\Payjp\Error\InvalidRequest $e) {
  $this->errors[] = $e->getMessage();

} catch (\Payjp\Error\Authentication $e) {
  $this->errors[] = $e->getMessage();

} catch (\Payjp\Error\ApiConnection $e) {
  $this->errors[] = $e->getMessage();

} catch (\Payjp\Error\Base $e) {
  $this->errors[] = $e->getMessage();

} catch (Exception $e) {
  $this->errors[] = $e->getMessage();

} finally {
  if ( !empty($this->errors) ) {
  )
}

//DBでいろいろやる
view.php
<?php
$customer_id;//pay.jpにおける顧客ID
?>
<form method="post">

<input type="hidden" name="amount" value="<?php esc_attr_e($amount);?>">

<?php if ( empty($customer_id) )://初回?>
<script type="text/javascript"
      src="https://checkout.pay.jp/"
      class="payjp-button"
      data-key="<?php echo PUBLIC_KEY;?>"
      data-partial="true">
</script>
<?php else://2回目以降?>
登録済みのカードで支払う
<?php endif;?>

<button class="button">注文を確定する</button>

</form>

<script>
(function ($) {
  $('form').on('submit', function() {
    $(this).find('button').attr('disabled', 'disabled');
  });
}(jQuery));
</script>

ちなみにカートは
seikan/Cart が使いやすかった

5
8
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
8