Single‑File PHP Implementation for Alipay and WeChat Payments

This article provides a concise, single‑file PHP solution for integrating Alipay and WeChat payments, detailing required environment settings, configuration parameters, essential code snippets, and usage instructions to simplify the payment integration process for developers.

php Courses
php Courses
php Courses
Single‑File PHP Implementation for Alipay and WeChat Payments

Many online tutorials for PHP Alipay integration are complex and require multiple files; this guide consolidates the process into a single PHP file, offering a lightweight alternative for developers who need to add Alipay or WeChat payment functionality.

Environment dependencies : PHP 5.0+ with CURL and SSL extensions enabled; for WeChat browser compatibility, include ap.js and pay.htm from Alipay's official demo.

Key configuration parameters (replace with your own values):

$appid = 'xxxxx'; // App ID from Alipay Open Platform
$returnUrl = 'http://www.xxx.com/alipay/return.php'; // Synchronous callback URL
$notifyUrl = 'http://www.xxx.com/alipay/notify.php'; // Asynchronous callback URL
$outTradeNo = uniqid(); // Your order number
$payAmount = 0.01; // Amount in yuan
$orderName = '支付测试'; // Order title
$signType = 'RSA2'; // Signature algorithm (RSA2 recommended)

The private key for your merchant account must correspond to the chosen signature algorithm; generate it according to Alipay documentation ( https://docs.open.alipay.com/291/105971 and https://docs.open.alipay.com/200/105310).

Core PHP class (single‑file implementation):

<?php
header('Content-type:text/html; Charset=utf-8');
class AlipayService {
    protected $appId;
    protected $returnUrl;
    protected $notifyUrl;
    protected $charset;
    protected $rsaPrivateKey;
    public function __construct($appid, $returnUrl, $notifyUrl, $saPrivateKey) {
        $this->appId = $appid;
        $this->returnUrl = $returnUrl;
        $this->notifyUrl = $notifyUrl;
        $this->charset = 'utf8';
        $this->rsaPrivateKey = $saPrivateKey;
    }
    /**
     * Initiate payment order
     */
    public function doPay($totalFee, $outTradeNo, $orderName, $returnUrl, $notifyUrl) {
        $requestConfigs = array(
            'out_trade_no' => $outTradeNo,
            'product_code' => 'QUICK_WAP_WAY',
            'total_amount' => $totalFee,
            'subject' => $orderName,
        );
        $commonConfigs = array(
            'app_id' => $this->appId,
            'method' => 'alipay.trade.wap.pay',
            'format' => 'JSON',
            'return_url' => $returnUrl,
            'charset' => $this->charset,
            'sign_type' => 'RSA2',
            'timestamp' => date('Y-m-d H:i:s'),
            'version' => '1.0',
            'notify_url' => $notifyUrl,
            'biz_content' => json_encode($requestConfigs),
        );
        $commonConfigs['sign'] = $this->generateSign($commonConfigs, $commonConfigs['sign_type']);
        return $commonConfigs;
    }
    public function generateSign($params, $signType = "RSA") {
        return $this->sign($this->getSignContent($params), $signType);
    }
    protected function sign($data, $signType = "RSA") {
        $priKey = $this->rsaPrivateKey;
        $res = "-----BEGIN RSA PRIVATE KEY-----
" .
               wordwrap($priKey, 64, "
", true) .
               "
-----END RSA PRIVATE KEY-----";
        if ("RSA2" == $signType) {
            openssl_sign($data, $sign, $res, version_compare(PHP_VERSION,'5.4.0','<') ? SHA256 : OPENSSL_ALGO_SHA256);
        } else {
            openssl_sign($data, $sign, $res);
        }
        return base64_encode($sign);
    }
    public function getSignContent($params) {
        ksort($params);
        $stringToBeSigned = '';
        $i = 0;
        foreach ($params as $k => $v) {
            if (false === $this->checkEmpty($v) && "@" != substr($v,0,1)) {
                $v = $this->characet($v, $this->charset);
                $stringToBeSigned .= ($i == 0 ? '' : '&') . "$k=$v";
                $i++;
            }
        }
        return $stringToBeSigned;
    }
    protected function checkEmpty($value) {
        if (!isset($value) || $value === null || trim($value) === "") return true;
        return false;
    }
    protected function characet($data, $targetCharset) {
        if (!empty($data)) {
            $fileType = $this->charset;
            if (strcasecmp($fileType, $targetCharset) != 0) {
                $data = mb_convert_encoding($data, $targetCharset, $fileType);
            }
        }
        return $data;
    }
}
function isWeixin() {
    return strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger') !== false;
}
$aliPay = new AlipayService($appid,$returnUrl,$notifyUrl,$saPrivateKey);
$payConfigs = $aliPay->doPay($payAmount,$outTradeNo,$orderName,$returnUrl,$notifyUrl);
$queryStr = http_build_query($payConfigs);
if (isWeixin()):
    ?>
    <script type="text/javascript" src="ap.js"></script>
    <script>
        var gotoUrl = 'https://openapi.alipay.com/gateway.do?<?=$queryStr?>';
        _AP.pay(gotoUrl);
    </script>
    <?php
else:
    header("Location:https://openapi.alipay.com/gateway.do?{$queryStr}");
endif;
?>

Notes :

Complete the configuration section at the top of the file with your own credentials.

Ensure the merchant private key matches the selected signature algorithm (RSA or RSA2).

When accessed from the WeChat browser, the script loads ap.js to invoke the Alipay SDK; otherwise it redirects directly.

By following these steps, developers can quickly integrate Alipay (and optionally WeChat) payment capabilities into a PHP website using only one file.

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.

IntegrationpaymentAlipay
php Courses
Written by

php Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

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.