Table of Contents
Environment dependence
Notes
code
Home Backend Development PHP Tutorial A PHP file handles Alipay computer website payment

A PHP file handles Alipay computer website payment

Apr 09, 2018 am 10:15 AM
php pay computer

The content of this article is about using a PHP file to complete Alipay computer website payment. Friends in need can refer to it

Many PHP Alipay payment access tutorials on the Internet are quite complicated. , and requires the configuration and introduction of many files. I have sorted it out and given a single file version. I hope it can bring some help and reference to everyone who wants to access Alipay payment.

One PHP file to handle the Alipay series: https://github.com/dedemao/alipay

One PHP file to handle the WeChat payment series: https://github.com/dedemao/weixinPay

Environment dependence

PHP5.0 or above, and the CURL service and SSL service need to be enabled.

Notes

1. The configuration information at the beginning of the file must be complete
2. The merchant’s private key must be filled in with the private key corresponding to the signature algorithm type. How to generate the key reference:
2.1 https://docs.open.alipay.com/291/105971
2.2 https://docs.open.alipay.com/200/105310

code

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

<?phpheader(&#39;Content-type:text/html; Charset=utf-8&#39;);$appid = &#39;xxxxx&#39;;  //https://open.alipay.com 账户中心->密钥管理->开放平台密钥,填写添加了电脑网站支付的应用的APPID$returnUrl = &#39;http://www.xxx.com/alipay/return.php&#39;;     //付款成功后的同步回调地址$notifyUrl = &#39;http://www.xxx.com/alipay/notify.php&#39;;     //付款成功后的异步回调地址$outTradeNo = uniqid();     //你自己的商品订单号$payAmount = 0.01;          //付款金额,单位:元$orderName = &#39;支付测试&#39;;    //订单标题$signType = &#39;RSA2&#39;;       //签名算法类型,支持RSA2和RSA,推荐使用RSA2//商户私钥,填写对应签名算法类型的私钥,如何生成密钥参考:https://docs.open.alipay.com/291/105971和https://docs.open.alipay.com/200/105310$saPrivateKey=&#39;MIIEpAIBAAKCAQEA1MV+OY6MvGfXPM0MkpjT+FdzGmPOvVmX2wF3gjwQpe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DyPtDZvP/ImPnFs+pNbFryD0HfmrEKquhIvyzXoGQknnsgbV5iy3KCTJaII9FxzINAKzZei7+0a+jqUd1kN3Gogp50Sze2ltAoGARaM5Xpaa8RZ6dGocfI9Nn4/Ch5fdZPFvHkdjMoPV+LKiNKtw/Tz+KiclAlasDsfZT+RaY9AJe3NvuHTzoX807swIVR1Xr3EpLaCed+0XrN3AjB34dZAskU87WZw+cjdtMjFzGOoFBSyGJi+OP/WMOp6jo/YBbwoX88tCJROzsgECgYAT8pHHIyPt5Y/5pDb8EDvD3XNES1fBkfZffSoAodsrkeoKgrsKl+9M3rcGX+S9dscyoH0ur3BFTMHtIOOhC5qytt+BhMHIP5mAs4di4u/joQCWQbUyrUggVK5it+6BFgAT+jeB7zTAUtgGpTVFq3kLbV0NZ+XQyEHVlnoJnHYpQg==&#39;;$aliPay = new AlipayService($appid,$returnUrl,$notifyUrl,$saPrivateKey);$sHtml = $aliPay->doPay($payAmount,$outTradeNo,$orderName,$returnUrl,$notifyUrl);echo $sHtml;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 = &#39;utf8&#39;;        $this->rsaPrivateKey=$saPrivateKey;

    }    /**

     * 发起订单

     * @param float $totalFee 收款总费用 单位元

     * @param string $outTradeNo 唯一的订单号

     * @param string $orderName 订单名称

     * @param string $notifyUrl 支付结果通知url 不要有问号

     * @param string $timestamp 订单发起时间

     * @return array

     */

    public function doPay($totalFee, $outTradeNo, $orderName, $returnUrl,$notifyUrl)

    {

        //请求参数

        $requestConfigs = array(            &#39;out_trade_no&#39;=>$outTradeNo,            &#39;product_code&#39;=>&#39;FAST_INSTANT_TRADE_PAY&#39;,            &#39;total_amount&#39;=>$totalFee, //单位 元

            &#39;subject&#39;=>$orderName//订单标题

        );        $commonConfigs = array(            //公共参数

            &#39;app_id&#39; => $this->appId,            &#39;method&#39; => &#39;alipay.trade.page.pay&#39;,             //接口名称

            &#39;format&#39; => &#39;JSON&#39;,            &#39;return_url&#39; => $returnUrl,            &#39;charset&#39;=>$this->charset,            &#39;sign_type&#39;=>&#39;RSA2&#39;,            &#39;timestamp&#39;=>date(&#39;Y-m-d H:i:s&#39;),            &#39;version&#39;=>&#39;1.0&#39;,            &#39;notify_url&#39; => $notifyUrl,            &#39;biz_content&#39;=>json_encode($requestConfigs),

        );        $commonConfigs["sign"] = $this->generateSign($commonConfigs, $commonConfigs[&#39;sign_type&#39;]);        return $this->buildRequestForm($commonConfigs);

    }    /**

     * 建立请求,以表单HTML形式构造(默认)

     * @param $para_temp 请求参数数组

     * @return 提交表单HTML文本

     */

    protected function buildRequestForm($para_temp) {

 

        $sHtml = "<form id=&#39;alipaysubmit&#39; name=&#39;alipaysubmit&#39; action=&#39;https://openapi.alipay.com/gateway.do?charset=".$this->charset."&#39; method=&#39;POST&#39;>";        while (list ($key, $val) = each ($para_temp)) {            if (false === $this->checkEmpty($val)) {                $val = str_replace("&#39;","&apos;",$val);                $sHtml.= "<input type=&#39;hidden&#39; name=&#39;".$key."&#39; value=&#39;".$val."&#39;/>";

            }

        }        //submit按钮控件请不要含有name属性

        $sHtml = $sHtml."<input type=&#39;submit&#39; value=&#39;ok&#39; style=&#39;display:none;&#39;&#39;></form>";        $sHtml = $sHtml."<script>document.forms[&#39;alipaysubmit&#39;].submit();</script>";        return $sHtml;

    }    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-----\n" .

            wordwrap($priKey, 64, "\n", true) .            "\n-----END RSA PRIVATE KEY-----";

 

        ($res) or die(&#39;您使用的私钥格式错误,请检查RSA私钥配置&#39;);        if ("RSA2" == $signType) {

            openssl_sign($data, $sign, $res, version_compare(PHP_VERSION,&#39;5.4.0&#39;, &#39;<&#39;) ? SHA256 : OPENSSL_ALGO_SHA256); //OPENSSL_ALGO_SHA256是php5.4.8以上版本才支持

        } else {

            openssl_sign($data, $sign, $res);

        }        $sign = base64_encode($sign);        return $sign;

    }    /**

     * 校验$value是否非空

     *  if not set ,return true;

     *    if is null , return true;

     **/

    protected function checkEmpty($value) {

        if (!isset($value))            return true;        if ($value === null)            return true;        if (trim($value) === "")            return true;        return false;

    }    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);                if ($i == 0) {                    $stringToBeSigned .= "$k" . "=" . "$v";

                } else {                    $stringToBeSigned .= "&" . "$k" . "=" . "$v";

                }                $i++;

            }

        }        unset ($k, $v);        return $stringToBeSigned;

    }    /**

     * 转换字符集编码

     * @param $data

     * @param $targetCharset

     * @return string

     */

    function characet($data, $targetCharset) {

        if (!empty($data)) {            $fileType = $this->charset;            if (strcasecmp($fileType, $targetCharset) != 0) {                $data = mb_convert_encoding($data, $targetCharset, $fileType);                //$data = iconv($fileType, $targetCharset.&#39;//IGNORE&#39;, $data);

            }

        }        return $data;

    }

}

Copy after login

Related Recommended:

php to implement product addition to shopping cart function (1)_php example                

The above is the detailed content of A PHP file handles Alipay computer website payment. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

Explain the match expression (PHP 8 ) and how it differs from switch. Explain the match expression (PHP 8 ) and how it differs from switch. Apr 06, 2025 am 12:03 AM

In PHP8, match expressions are a new control structure that returns different results based on the value of the expression. 1) It is similar to a switch statement, but returns a value instead of an execution statement block. 2) The match expression is strictly compared (===), which improves security. 3) It avoids possible break omissions in switch statements and enhances the simplicity and readability of the code.

What is the reason why PS keeps showing loading? What is the reason why PS keeps showing loading? Apr 06, 2025 pm 06:39 PM

PS "Loading" problems are caused by resource access or processing problems: hard disk reading speed is slow or bad: Use CrystalDiskInfo to check the hard disk health and replace the problematic hard disk. Insufficient memory: Upgrade memory to meet PS's needs for high-resolution images and complex layer processing. Graphics card drivers are outdated or corrupted: Update the drivers to optimize communication between the PS and the graphics card. File paths are too long or file names have special characters: use short paths and avoid special characters. PS's own problem: Reinstall or repair the PS installer.

Does H5 page production require continuous maintenance? Does H5 page production require continuous maintenance? Apr 05, 2025 pm 11:27 PM

The H5 page needs to be maintained continuously, because of factors such as code vulnerabilities, browser compatibility, performance optimization, security updates and user experience improvements. Effective maintenance methods include establishing a complete testing system, using version control tools, regularly monitoring page performance, collecting user feedback and formulating maintenance plans.

How to speed up the loading speed of PS? How to speed up the loading speed of PS? Apr 06, 2025 pm 06:27 PM

Solving the problem of slow Photoshop startup requires a multi-pronged approach, including: upgrading hardware (memory, solid-state drive, CPU); uninstalling outdated or incompatible plug-ins; cleaning up system garbage and excessive background programs regularly; closing irrelevant programs with caution; avoiding opening a large number of files during startup.

What is Cross-Site Request Forgery (CSRF) and how do you implement CSRF protection in PHP? What is Cross-Site Request Forgery (CSRF) and how do you implement CSRF protection in PHP? Apr 07, 2025 am 12:02 AM

In PHP, you can effectively prevent CSRF attacks by using unpredictable tokens. Specific methods include: 1. Generate and embed CSRF tokens in the form; 2. Verify the validity of the token when processing the request.

Describe the purpose and usage of the ... (splat) operator in PHP function arguments and array unpacking. Describe the purpose and usage of the ... (splat) operator in PHP function arguments and array unpacking. Apr 06, 2025 am 12:07 AM

The... (splat) operator in PHP is used to unpack function parameters and arrays, improving code simplicity and efficiency. 1) Function parameter unpacking: Pass the array element as a parameter to the function. 2) Array unpacking: Unpack an array into another array or as a function parameter.

How can you prevent a class from being extended or a method from being overridden in PHP? (final keyword) How can you prevent a class from being extended or a method from being overridden in PHP? (final keyword) Apr 08, 2025 am 12:03 AM

In PHP, the final keyword is used to prevent classes from being inherited and methods being overwritten. 1) When marking the class as final, the class cannot be inherited. 2) When marking the method as final, the method cannot be rewritten by the subclass. Using final keywords ensures the stability and security of your code.

See all articles