search
HomeBackend DevelopmentPHP Tutorial微信支付与支付宝支付整合 PHP实现

利用PHP的反射把两种支付接口统一起来。

使用前需要配置目录下的Config文件即WxpayConfig.php与AlipayConfig.php

使用支付宝支付
<?phpnamespace WatcherHangzhouPayment\Payment;$payRequestParams = array(    'returnUrl' => $this->generateUrl('pay_return', array('name' => 'alipay'), true),    'notifyUrl' => $this->generateUrl('pay_notify', array('name' => 'alipay'), true),    'showUrl' => $this->generateUrl('show_goods', array('id' => $goods['id']), true),);$paymentRequest = createPaymentRequest($order, $requestParams);function createPaymentRequest($order, $requestParams){    $requestParams = array_merge($requestParams, array(            'orderSn' => $order['sn'],            'title' => $order['title'],            'summary' => '',            'amount' => $order['amount'],    ));    return Payment::createRequest('alipay', $requestParams);}$htmlForm = $request->form();$inputHtml = '';foreach ($htmlForm['params'] as $key => $value) {    $inputHtml .= "<input type=\"hidden\" name=\"{$key}\" value=\"{$value}\">";}$html = <<<EOF<!DOCTYPE html><html><head>  <meta charset="utf-8">  <title>Jumping to alipay gateway...</title><body>  <form action="{$htmlForm['action']}"  method="{$htmlForm['method']}" name="form">    {$inputHtml}  </form>  <script>    document.all.form.submit();  </script></body></html>EOF;echo $html;die;

使用微信支付

微信支付依赖composer的把url转换为二维码text的Endroid\QrCode\QrCode库。

<?phpnamespace WatcherHangzhouPayment\Payment;<?phpnamespace WatcherHangzhouPayment\Payment;$payRequestParams = array(    'returnUrl' => $this->generateUrl('pay_return', array('name' => 'wxpay'), true),    'notifyUrl' => $this->generateUrl('pay_notify', array('name' => 'wxpay'), true),    'showUrl' => $this->generateUrl('show_goods', array('id' => $goods['id']), true),);$paymentRequest = createPaymentRequest($order, $requestParams);function createPaymentRequest($order, $requestParams){    $requestParams = array_merge($requestParams, array(            'orderSn' => $order['sn'],            'title' => $order['title'],            'summary' => '',            'amount' => $order['amount'],    ));    return Payment::createRequest('wxpay', $requestParams);}$returnXml = $paymentRequest->unifiedOrder();$returnArray = $paymentRequest->fromXml($returnXml);if ($returnArray['return_code'] == 'SUCCESS') {    $url = $returnArray['code_url'];    $html = <<<EOF<!DOCTYPE html><html><head>  <meta charset="utf-8">  <title>使用微信二维码支付</title><body>  <img  src="{{ path('generate_qrcode_image',{url:url}) }}"  alt="微信支付与支付宝支付整合 PHP实现" >          <div class="text-qrcode hidden-xs">            请使用微信扫一扫<br>扫描二维码支付          </div></body></html>EOF;    echo $html;    die;}

 回调数据处理  
if (支付宝) {    $response = Payment::createResponse('alipay', $_POST);} elseif (微信) {    $returnXml = $GLOBALS['HTTP_RAW_POST_DATA'];    $response = Payment::createResponse('wxpay', fromXml($returnXml));}$payData = $response->getPayData();if ($payData['status'] == "success") {    //干支付成功该干的事情}function fromXml($xml){    $array = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);    return $array;}

项目主页:http://www.open-open.com/lib/view/home/1441781914992

Statement
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
PHP Performance Tuning for High Traffic WebsitesPHP Performance Tuning for High Traffic WebsitesMay 14, 2025 am 12:13 AM

ThesecrettokeepingaPHP-poweredwebsiterunningsmoothlyunderheavyloadinvolvesseveralkeystrategies:1)ImplementopcodecachingwithOPcachetoreducescriptexecutiontime,2)UsedatabasequerycachingwithRedistolessendatabaseload,3)LeverageCDNslikeCloudflareforservin

Dependency Injection in PHP: Code Examples for BeginnersDependency Injection in PHP: Code Examples for BeginnersMay 14, 2025 am 12:08 AM

You should care about DependencyInjection(DI) because it makes your code clearer and easier to maintain. 1) DI makes it more modular by decoupling classes, 2) improves the convenience of testing and code flexibility, 3) Use DI containers to manage complex dependencies, but pay attention to performance impact and circular dependencies, 4) The best practice is to rely on abstract interfaces to achieve loose coupling.

PHP Performance: is it possible to optimize the application?PHP Performance: is it possible to optimize the application?May 14, 2025 am 12:04 AM

Yes,optimizingaPHPapplicationispossibleandessential.1)ImplementcachingusingAPCutoreducedatabaseload.2)Optimizedatabaseswithindexing,efficientqueries,andconnectionpooling.3)Enhancecodewithbuilt-infunctions,avoidingglobalvariables,andusingopcodecaching

PHP Performance Optimization: The Ultimate GuidePHP Performance Optimization: The Ultimate GuideMay 14, 2025 am 12:02 AM

ThekeystrategiestosignificantlyboostPHPapplicationperformanceare:1)UseopcodecachinglikeOPcachetoreduceexecutiontime,2)Optimizedatabaseinteractionswithpreparedstatementsandproperindexing,3)ConfigurewebserverslikeNginxwithPHP-FPMforbetterperformance,4)

PHP Dependency Injection Container: A Quick StartPHP Dependency Injection Container: A Quick StartMay 13, 2025 am 12:11 AM

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Dependency Injection vs. Service Locator in PHPDependency Injection vs. Service Locator in PHPMay 13, 2025 am 12:10 AM

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHP performance optimization strategies.PHP performance optimization strategies.May 13, 2025 am 12:06 AM

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHP Email Validation: Ensuring Emails Are Sent CorrectlyPHP Email Validation: Ensuring Emails Are Sent CorrectlyMay 13, 2025 am 12:06 AM

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl

See all articles

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)