Integrate Alipay Online Payments in PHP with Yansongda Pay

This guide walks you through the complete process of setting up Alipay online payment integration in a PHP project, covering certificate generation, configuration files, Composer installation, payment request code, and handling both synchronous and asynchronous callbacks.

Open Source Tech Hub
Open Source Tech Hub
Open Source Tech Hub
Integrate Alipay Online Payments in PHP with Yansongda Pay

Overview

This guide shows how to integrate Alipay's online payment interface into a PHP application using the yansongda/pay library.

Certificate Setup

Access Alipay Open Platform

Log in to https://open.alipay.com/develop/manage and create a new application.

Generate CSR and Certificates

Download Alipay's key tool, generate a CSR file, and upload the CSR in the Alipay console. The app_secret_cert field must contain the private‑key file content (e.g., the text of “应用私钥RSA2048-敏感数据,请妥善保管.txt”).

Installation

composer require yansongda/pay ^3.0.0
All examples use Alipay’s sandbox environment; switch the mode setting for production.

Configuration File

Create config/payment.php with the following content, replacing placeholder values with your actual certificates and keys:

<?php
return [
    'alipay' => [
        'default' => [
            // Required – Alipay‑assigned app_id
            'app_id' => '20160909004708941',
            // Required – Application private key (string or path)
            'app_secret_cert' => 'MIIEpAIBAAKCxxxxxxxxxxxxxxP4r3m4OUmD/+XDgCg==',
            // Required – Path to application public certificate
            'app_public_cert_path' => base_path().'/payment/appCertPublicKey_2016090900470841.crt',
            // Required – Path to Alipay public certificate
            'alipay_public_cert_path' => base_path().'/payment/alipayCertPublicKey_RSA2.crt',
            // Required – Path to Alipay root certificate
            'alipay_root_cert_path' => base_path().'/payment/alipayRootCert.crt',
            // Optional – Synchronous callback URL
            'return_url' => 'https://example.com/payment/alipay-return',
            // Optional – Asynchronous callback URL
            'notify_url' => 'https://example.com/payment/alipay-notify',
            // Optional – Service provider ID (used in SERVICE mode)
            'service_provider_id' => '',
            // Optional – Mode (NORMAL, SANDBOX, SERVICE)
            'mode' => \Yansongda\Pay\Pay::MODE_SANDBOX,
        ],
    ],
    'logger' => [
        'enable' => false,
        'file' => runtime_path().'/logs/alipay.log',
        'level' => 'debug', // use 'info' in production
        'type' => 'single', // or 'daily'
        'max_file' => 30,
    ],
    'http' => [
        'timeout' => 5.0,
        'connect_timeout' => 5.0,
        // Additional Guzzle options are supported
    ],
    '_force' => true,
];
The certificate files should be placed under the project’s payment directory.
├── payment
│   ├── alipayCertPublicKey_RSA2.crt
│   ├── alipayRootCert.crt
│   └── appCertPublicKey_2016090900470841.crt

Usage

Initialization

Load the configuration and initialize the Pay client:

// Retrieve configuration
$config = Config::get('payment');
Pay::config($config);
Keep 'mode' => \Yansongda\Pay\Pay::MODE_SANDBOX for sandbox testing.

Web (Desktop) Payment

Build an order array and invoke the web payment method. Official documentation URL: https://opendocs.alipay.com/open/270/105898?pathHash=b3b2b667

use support\Request;
use Webman\Config;
use Yansongda\Pay\Pay;

/**
 * @param Request $request
 * @return string
 */
public function payment(Request $request)
{
    $config = Config::get('payment');
    Pay::config($config);
    $order = [
        'out_trade_no' => time(),
        'total_amount' => '8888.88',
        'subject' => 'webman payment',
        '_method' => 'get', // redirect using GET
    ];
    return Pay::alipay()->web($order)->getBody()->getContents();
}

Asynchronous Callback

use support\Request;
use Webman\Config;
use Yansongda\Pay\Pay;
use support\Response;

/**
 * Alipay asynchronous notification handler
 */
public function alipayNotify(Request $request): Response
{
    $config = Config::get('payment');
    Pay::config($config);
    $result = Pay::alipay()->callback($request->post());
    // TODO: verify trade_status, out_trade_no, total_amount, seller_id, app_id, etc.
    return new Response(200, [], 'success');
}
Do not return Pay::alipay()->success() directly; use a framework response object instead.

Synchronous Callback

use support\Request;
use Yansongda\Pay\Pay;
use support\Log;

/**
 * Alipay synchronous notification handler
 */
public function alipayReturn(Request $request)
{
    Log::info('Alipay sync notify'.json_encode($request->get()));
    return 'success';
}

Logging

Payment‑related logs are written to runtime/logs/pay.log (or the path configured in the logger section).

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

PHPComposerPayment IntegrationAlipayYansongda Pay
Open Source Tech Hub
Written by

Open Source Tech Hub

Sharing cutting-edge internet technologies and practical AI resources.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.