search
HomeBackend DevelopmentPHP TutorialDetailed explanation of a simple example of developing UnionPay payment interface in PHP

This article mainly introduces the method of developing the PHP version of the UnionPay payment interface, and analyzes the specific process and related operating techniques of the PHP UnionPay payment interface development in the form of examples. Friends in need can refer to the

Payment interface Now there are third-party payment interfaces and bank payment interfaces. Here we will introduce the method of developing the PHP version of UnionPay payment interface.

When paying with UnionPay, you must first pay attention to two important parts:

The PHP operating environment is 5.4.18 or above

The extension openssl is enabled

The examples in the development manual are only for reference, because they are basically wrong. You can try to go to the official website for a demo. . . Note that now UnionPay is developing, there is no test key provided, it can only be developed in the official environment

The following is a payment class I wrote using ThinkPHP

/**
* 银联支付 v0.1
* @auther:Summer<dengwz7788@gmail.com>;
* @date:20151202
* **/
class NetPayAction extends BaseAction{
//在类初始化方法中,引入相关类库
public function _initialize() {
 header("Content-type:text/html;charset=utf-8");
 vendor(&#39;Netpay.util.common&#39;,"",".php"); //导入加密核心文件夹
 vendor(&#39;Netpay.util.SecssUtil&#39;,"",".class.php"); //导入加密核心文件夹
 vendor(&#39;Netpay.util.Settings_INI&#39;,"",".php"); //导入加密核心文件夹
 vendor(&#39;Netpay.util.Settings&#39;,"",".php"); //导入加密核心文件夹
 $this->securityPropFile= $_SERVER[&#39;DOCUMENT_ROOT&#39;] . "/ThinkPHP/Extend/Vendor/Netpay/config/security.properties"; //谁知道这是啥,反正他们要我加的
 $this->b2cPaySend = __APP__."/Index/NetPay/b2cPaySend";
 $this->b2cRefundSend = __APP__."/Index/NetPay/b2cRefundSend";
 $this->b2cQuerySend = __APP__."/Index/NetPay/b2cQuerySend";
 $this->;MerBgUrl = __APP__."/Index/NetPay/MerBgUrl";
 $this->MerPageUrl = __APP__."/Index/NetPay/MerPageUrl";
}
public function index()
{
 $paramArray=array (
   &#39;MerId&#39; => &#39;商户号&#39;,
   &#39;MerOrderNo&#39; => &#39;0000001944663232&#39;,
   &#39;OrderAmt&#39; => &#39;1&#39;,
   &#39;TranDate&#39; => &#39;20151219&#39;,
  &#39;TranTime&#39; =>&#39;171248&#39;,
  &#39;TranType&#39; => &#39;0001&#39;,
  &#39;BusiType&#39; =>&#39;0001&#39;,
  &#39;Version&#39; => &#39;20140728&#39;,
  &#39;CurryNo&#39; => &#39;CNY&#39;,
  &#39;AccessType&#39; =>; &#39;0&#39;,
  &#39;CommodityMsg&#39; => &#39;测试商品1号&#39;,
  &#39;MerPageUrl&#39; => $this->MerBgUrl,
  &#39;MerBgUrl&#39; =>$this->MerPageUrl,
  &#39;MerResv&#39; => &#39;MerResv&#39;,
 );
 if (count($paramArray) >0) {
  $dispatchUrl = $this->b2cPaySend;
  $transResvedJson = array();
  $cardInfoJson = array();
  $sendMap = array();
   foreach ($paramArray as $key => $value) {
   if (isEmpty($value)) {
    continue;
   }
   if (startWith($key, "trans_")) {
     $key = substr($key, strlen("trans_"));
        $transResvedJson[$key] = $value;
   } else
     if (startWith($key, "card_")) {
       $key = substr($key, strlen("card_"));
       $cardInfoJson[$key] = $value;
     } else {
       $sendMap[$key] = $value;
     }
  }
  $transResvedStr = null;
  $cardResvedStr = null;
  if (count($transResvedJson) >0) {
   $transResvedStr = json_encode($transResvedJson);
  }
  if (count($cardInfoJson) > 0) {
   $cardResvedStr = json_encode($cardInfoJson);
  }
 $secssUtil = new SecssUtil();
 if (! isEmpty($transResvedStr)) {
  $transResvedStr = $secssUtil->decryptData($transResvedStr);
  $sendMap["TranReserved"] = $transResvedStr;
  }
 if (! isEmpty($cardResvedStr)) {
   $cardResvedStr = $secssUtil->decryptData($cardResvedStr);
   $sendMap["card_"] = $cardResvedStr;
  }
  $securityPropFile = $this>securityPropFile;
  $secssUtil->init($securityPropFile);
  $secssUtil->sign($sendMap);
  $sendMap["Signature"] = $secssUtil->getSign();
  $_SESSION = $sendMap;
  header("Location:" . $dispatchUrl);
 }
}
public function b2cPaySend(){
  layout(false);
  $settings = new Settings_INI();
  $settings->oad($this->securityPropFile);
  $pay_url = "https://payment.chinapay.com/CTITS/service/rest/page/nref/000000000017/0/0/0/0/0";
  $html = "<form name=&#39;payment&#39; action=&#39;{$pay_url}&#39; method=&#39;POST&#39; target=&#39;_blank&#39;>;";
  $params = "TranReserved;MerId;MerOrderNo;OrderAmt;CurryNo;TranDate;SplitMethod;BusiType;MerPageUrl;MerBgUrl;SplitType;MerSplitMsg;PayTimeOut;MerResv;Version;BankInstNo;CommodityMsg;Signature;AccessType;AcqCode;OrderExpiryTime;TranType;RemoteAddr;Referred;TranTime;TimeStamp;CardTranData";
  foreach ($_SESSION as $k =>$v) {
   if (strstr($params, $k)) {
     $html .= "<input type=&#39;hidden&#39; name = &#39;" . $k . "&#39; value =&#39;" . $v . "&#39;/>";
   }
  }
    $html .= "<nput type=&#39;button&#39; type=&#39;hidden&#39; value=&#39;提交订单&#39; >";
    $html .= "<;/from>";
    $this->html = $html;
    $this->display();
}
public function pgReturn(){
 if ($_POST) {
   if (count($_POST) > 0) {
    $secssUtil = new SecssUtil();
    $securityPropFile = $this>securityPropFile;
    $secssUtil->init($securityPropFile);
    $text = array();
    foreach($_POST as $key=>$value){
      $text[$key] = urldecode($value);
    }
   if ($secssUtil->verify($text)) {
            //支付成功
     $_SESSION["VERIFY_KEY"] = "success";
   } else {
    //支付失败
     $_SESSION["VERIFY_KEY"] = "fail";
   }
  }
  }
 }
}

UnionPay payment should be relatively simple! !

Summary: The above is the entire content of this article, I hope it will be helpful to everyone's study.

Related recommendations:

phpRealize the refund function of WeChat payment

phpAlipay series of computer website payment

phpPerformance analysis ofphp-fpm slow execution log slow log usage

The above is the detailed content of Detailed explanation of a simple example of developing UnionPay payment interface in PHP. For more information, please follow other related articles on the PHP Chinese website!

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

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.

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use