GCashまたはMaya Payment InterfaceとPHP/Pythonの連携

GCash および Maya 支払いインターフェースとの連携ガイド

GCash決済インターフェースのドッキング

PHPの実装

<?php
// GCash API の設定
$gcash_api_key = 'YOUR_GCASH_API_KEY';
$gcash_secret = 'YOUR_GCASH_SECRET';
$gcash_base_url = 'https://api.gcash.com';

// 支払リクエストを作成する
function createGcashPayment($amount, $reference_id, $callback_url) {.
global $gcash_api_key、$gcash_secret、$gcash_base_url;

$endpoint = '/payments/v1/payments';
$imestamp = time();

// リクエストデータを構築する
$data = [
'amount' => number_format($amount, 2)、
'currency' => 'PHP'、
'payment_method' => ['type' => 'GCASH']、
'reference_id' => $reference_id、
'redirect_urls' => [
'success' => "$callback_url?status=success"、
'failure' => "$callback_url?status=failure"、
'cancel' => "$callback_url?status=cancel"
]
];

// 署名を生成する
$signature_data = "POSTn{$endpoint}n{$imestamp}n" . json_encode($data);
$signature = hash_hmac('sha256', base64_encode($signature_data), base64_encode($gcash_secret));

// HTTP リクエストヘッダ
$headers = [
「Content-Type: application/json」。
「Authorization: Bearer {$gcash_api_key}」、「Authorisation: Bearer {$gcash_api_key}」。
「X-GCash-Timestamp: {$imestamp}"、
「X-GCash-Signature: {$signature}"
];

// cURLリクエスト
を試す。
return makeApiRequest("{$gcash_base_url}{$endpoint}", json_encode($data), true);
} catch (例外) {.
throw new Exception("Failed to create GCASH payment");
}
}

function makeApiRequest(string url string data bool isPost): array|false {.
/* 実装はこちら */
}

Pythonの実装

輸入リクエスト
インポートhashlib
インポート hmac
インポート base64
インポート時間
インポート json

クラス GcashPayment.

def __init__(self api_key secret).
self.api_key api key self.secret secret self.base url https://api.gcash.com

def create_payment(self amount reference id callback url)::
エンドポイント /payments/v1/payments タイムスタンプ int(time.time())

data amount f{float(amount):.2f} currency PHP payment method type GCASH reference id reference id redirect urls success f{call backurl status success失敗 f{call backurl status failure キャンセル f call backurl status キャンセル

signature data POSTn end point ୧ str(timestamp)୨ +json.dumps(data)
署名 hmac.new(base64.b64encode(self.secret.encode()) base64.b6encode(signatur_data.encode()) hashlib.sha256).hexdigest()

ヘッダー Content-Type application/json Authorization Bearer {self.api key X-GCash-Timestamp str(タイムスタンプ) X-GCash-Signatur signature

response requests.post(f"{self.base url}{end point}" jso=data headers=headers)
response.raise_for_status()
return response.json()

マヤ・ペイメント・インターフェイス・ドッキング

PHPの実装


public function createCheckout(float amount string requestReferenceNumber array redirectUrls try payload [ totalAmount [ value 金額 通貨 PHPitems [[ name 商品名 quantity | price value (amoun/100)*100 code item001 description Sample item]] requestReferenceNumberrequestReferenceNumber redirectUrl redirectUrls ] ] です。

response this->makeRequest('/checkout/v1/checkouts payload); if (!isset(response['checkoutId'])) throw new Exception('Failed to creatチェックアウトの作成に失敗しました')。

return [ checkoutUrl response['redirectUrl'] checkoutId response['checkoutId'] ]; catch (Exception e) error log(e->getMessage()); return false.}

private function makeRequest(string path array data string method POST') curl curl_init(this->api Url path); curl_setopt_array(curl CURLOPT_RETURNTRANSFER true CURLOPT_CUSTOMREQUEST method CURLOPT_POSTFIELDS json encode(data)); headers ['Content-Type application/jsonAuthorization Basic .base6 encode(this->checOutKey )]; curl setopt(curl CURLOPT HTTPHEADER headers);

result cur_exec(curl); errno cur_errno(curl); error cur_error(curl); if errno throw new Exception(Curl error error error).

httpCode cur_getinfo(cu CURLINFO HTTP CODE if httpCode >=400 parse result ?json decode(result true :[]; message parsed['message??parsed[0]['メッセージ]??Unknown Maya API erro'; throw new Exception(Maya API Error message httpCod finally cu_close(cu );

return son decode(result tru ); } ```.

Pythonの実装 ``python import reques import bas664 import jsor from typing impo Dict Any Optional class May Payment def __init__(sel checout_k y your_may .チェックアウト_k y your_may _check utkey se ret ey your maya s cret k y a i_u l https:/ pg sand ox pay ay . om).

elfのch ck ut ke check t k y elfのsec et ke secre _keのelf a i u l ap _ur def cre te_ch ckou sel am unt floa req est ref r nc numbe tr redi ectU ls Di t[str st ] D ct[str An ].

ペイロード総額 金額 現価 PH イット数 名 称 金額 ラウンド(Amo t *10 )/100 co de ite O01 descr pt on Sam le tem ReuestRefere Ce um er requ(単位:百万円)単位:百万円(単位:百万円)

応答する self._ma_req est /chk ut v1/chc outs paylo d)

応答がない場合、または応答がない場合、response.get( chec ou d ): raise Except on(Fai ed o cre te Ma ya ch c out )

[etc.etc.etc.etc.etc.etc.etc.etc.etc.etc.etc.etc.etc.etc.

ef _mak eque t(se pa th str da a Di t ny met od st POS ) > Op iona Dic any].

このような場合、{s If.a i_r }{ athheade s ont nt Typ appli ation/jso Auth riz tion asic b4encod ((f sel .checou key ).en ode() hex ist())] を使用します。

を使用する。

spons raise fo sta us()

返り値 sponse.jso () excep Exce tion as xceptio print(f May API er or exep ion return No ne ```.

主な検討事項

1 サンドボックス環境:どちらの決済サービスもサンドボックス環境を提供しているため、開発者はまず統合テスト用のテストAPIキーを使用する必要がある。

2 Webhook処理:非同期通知を処理し、トランザクションステータスを検証するために、サーバーエンドポイントを設定する必要がある。

3 セキュリティ対策:
- すべてのAPIコールはHTTPSで行われるべきである。
- APIキーのような機密データをコードにハードコードすべきではない。
- IPホワイトリスト(サポートされている場合)は、サーバーIPへのアクセスのみを許可するように設定する必要があります。

4 コンプライアンス要件
- PCI DSSに準拠したクレジットカードデータの処理(該当する場合)
- GDPRまたはその他の現地プライバシー規制への対応

5 エラー処理:ネットワークの問題や一時的な障害に対応するための再試行メカニズムを実装する。

決済インターフェース・ドッキングの徹底的な実装とベストプラクティス

Webhook処理の実装(PHPの例)

<?php
// GCash/Maya Webhook プロセッサ
クラスのPaymentWebhookHandler {。
private $apiSecret.

public function __construct(string $apiSecret) {
$this->apiSecret = $apiSecret;
}

パブリック関数 handleGcashWebhook(): void {
// 署名を検証する
$signature = $_SERVER['HTTP_X_GCASH_SIGNATURE'] ?? '';
$payload = file_get_contents('php://input');

if (!$this->verifyGcashSignature($signature, $payload)) { {.
http_response_code(401)。
退場する;
}

// ウェブフック・イベントを処理する
を試す。
return match ($eventType) {.
'payment.success' => new SuccessPaymentEvent($data)、
'payment.failed' => new FailedPaymentEvent($data)、
default => throw new UnexpectedValueException("Unsupported event type: {$eventType}")、
};

// TODO: オーダー・ステータスの更新とその他のビジネス・ロジック

http_response_code(200)。

Pythonの非同期Webhook処理

from fastapi import FastAPI, Request, HTTPException 
インポート hmac
インポートhashlib

app = FastAPI()

MAYA_WEBHOOK_SECRET = "your_webhook_secret"

app.post("/maya/webhooks")
async def handle_maya_webhook(request: Request).
# ベリファイ署名
signature_header = request.headers.get("X-Maya-Signature")

よくある問題の解決策

  1. 証明書検証の失敗::

    # PHP cURL SSL設定(開発環境では一時的に認証を無効にすることができます。)
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

    # PythonがSSLのセットアップを要求する
    requests.post(url, verify='/path/to/cert.pem')

  2. デバッグのヒント::

    • GCashサンドボックスのテストカード番号:4111111111111111
  3. パフォーマンス最適化::

  4. セキュリティ強化の提言

  5. トランザクション・ステータスの同期

10

決済インターフェース・ドッキングの徹底的な実装とベストプラクティス(続き)

5.取引状況の同期メカニズム

アクティブクエリのPHP実装

function getGcashPaymentStatus(string $paymentId): array {.
$endpoint = "/payments/v1/payments/{$paymentId}";
$imestamp = time();

// シグネチャを生成する(先に定義したシグネチャ・メソッドを使用する)
$signature = generateGcashSignature('GET', $endpoint, $imestamp);

を試す。
return makeApiRequest(
"{$gcash_base_url}{$endpoint}",
ヌルである、
false, // GETリクエスト
[
「Authorization: Bearer {$gcash_api_key}」、「Authorisation: Bearer {$gcash_api_key}」。
「X-GCash-Timestamp: {$imestamp}"、
「X-GCash-Signature: {$signature}"
]
);
} catch (例外) {.
throw new Exception("Failed to fetch payment status");
}
}

Pythonの非同期状態チェック

async def check_maya_payment_status(session, checkout_id).
url = f"{self.base_url}/checkout/v1/checkouts/{checkout_id}"

6.エラー処理とリトライ機構

PHP Exponential Backoff Retry の例

function makePaymentWithRetry(callable $paymentFn, int maxRetries) { retryCount while (true) { try return paymentFn(); catchPaymentException e if retryCount >= maxRetries throw e; } }.

sleep(min(pow(2 retryCount rand(1000)/1000)); retryCount++; } } }.

// 使い方。
makePaymentWithRetry(fn createGcashPayment(...));

Pythonデコレータの実装

from functools import wraps 

def retriable(max_retries=3 backoff_factor=1)::
def デコレータ(func) @wraps(func)
async def wrapper(*args kwargs last_error None for attempt in range(max_retrieve sleep_time backoff_factor * (2 attempt await asyncio.sleep(sleep_time)

try return await func(*args kwargs except PaymentError as e last_error e raise last_error からの Retr yExhaustedError return wrapper return デコレーター

リトライ可能(最大リトライ数)
async def process_paymen().
パス ``



7.

8.

9.

10