


A painstaking work: Application of Alipay's mobile website payment interface, a painstaking work_PHP tutorial
Jul 12, 2016 am 08:54 AMA painstaking work: the application of Alipay’s mobile website payment interface, a painstaking work
Since I was working on the Mobile Portl interface last year, I needed to use Alipay’s Payment, so Mobile Website Payment Interface has become the first choice.
1. First download the interface package
<span>支付寶商家服務(wù)中心鏈接</span>:<span>https://b.alipay.com/login.htm?goto=https://b.alipay.com:443/newIndex.htm</span>
Mobile website payment product introduction: https://b.alipay.com/order/productDetail.htm?productId=2013080604609688
Demo download link: https://doc.open.alipay.com/doc2/detail.htm?treeId=54&articleId=104511&docType=1 (Please click on the keyword demo to download )
Unzip the downloaded file and you can see the folder structure as shown below:
I use RSA signature method, PHP-UTF-8 folder
Documentation description of 2.readme.txt
The files in red font are the most important files and are required!
│<br />├lib┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈類文件夾<br />│ │<br />│ ├<span>alipay_core.function.php</span> ┈┈┈┈┈┈支付寶接口公用函數(shù)文件<br />│ │<br />│ ├<span>alipay_notify.class.php</span>┈┈┈┈┈┈┈支付寶通知處理類文件<br />│ │<br />│ ├<span>alipay_submit.class.php</span>┈┈┈┈┈┈┈支付寶各接口請求提交類文件<br />│ │<br />│ └<span>alipay_rsa.function.php</span>┈┈┈┈┈┈┈支付寶接口RSA函數(shù)文件<br />│<br />├log.txt┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈日志文件<br />│<br />├<span>alipay.config.php</span>┈┈┈┈┈┈┈┈┈┈┈┈基礎(chǔ)配置類文件<br />│<br />├<span>alipayapi.php</span>┈┈┈┈┈┈┈┈┈┈┈┈┈┈支付寶接口入口文件<br />│<br />├<span>notify_url.php</span> ┈┈┈┈┈┈┈┈┈┈┈┈┈服務(wù)器異步通知頁面文件<br />│<br />├<span>return_url.php</span> ┈┈┈┈┈┈┈┈┈┈┈┈┈頁面跳轉(zhuǎn)同步通知文件<br />│<br />├key┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈私鑰公鑰文件夾(用法見下方※注意※)<br />│ │<br />│ ├<span>rsa_private_key.pem</span>┈┈┈┈┈┈┈┈┈商戶的私鑰文件<br />│ │<br />│ └<span>alipay_public_key.pem</span>┈┈┈┈┈┈┈┈支付寶的公鑰文件<br />│<br />├openssl┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈缺省dll文件(用法見下方※注意※)<br />│ │<br />│ ├libeay32.dll<br />│ │<br />│ ├ssleay32.dll<br />│ │<br />│ └php_openssl.dll<br />│<br />├<span>cacert.pem</span> ┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈用于CURL中校驗(yàn)SSL的CA證書文件<br />│<br />└<span>readme.txt</span> ┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈使用說明文本<br /><br /><br /><span><span><strong>3.</strong> 把必需的文件整合到框架里(我當(dāng)時(shí)用的是thinkPHP框架)</span><br /> ?。?)在<img src="/static/imghw/default1.png" data-src="http://www.bkjia.com/uploads/allimg/160415/1643115256-2.png" class="lazy" alt="" /> 里新建一個(gè)文件夾叫<span>AliMobilePay</span>,</span><span><br /> <img src="/static/imghw/default1.png" data-src="http://www.bkjia.com/uploads/allimg/160415/16431124L-3.png" class="lazy" alt="" /><br /> 把上圖里的4個(gè)文件拷貝到AliMobilePay文件夾里,<br /></span>
Rename the above files,
alipay_core.function.php is renamed to: Corefunction.php
Alipay_notify.class.php is renamed to: Notify.php
alipay_rsa.function.php is renamed to: Rsafunction.php
Alipay_submit.class.php is renamed to: Submit.php
Open Notify.php and remove the code,
require_once("alipay_core.function.php");
require_once("alipay_rsa.function.php");
Similarly remove the include files in the other three files.
<span> ?。?)在根目錄下建立一個(gè)文件夾key<br /> 在key文件夾里放入</span><span>商戶的私鑰文件、支付寶的公鑰文件、CA證書文件</span>
How to generate RSA key: https://cshall.alipay.com/enterprise/help_detail.htm?help_id=474010&keyword=????????? &sToken=s-5d0c889ac47741fd8094b26d4862696b&from= search&flag=0 (The rsa_private_key.pem described in this article is the merchant’s private key file)
◆Merchant’s private key
1. There is no need to perform pkcs8 encoding on the newly generated (original) private key
? ? 1. No need to perform pkcs8 encoding on the newly generated (original] private key --", "-----END RSA PRIVATE KEY-----"
In short, just maintain the content of the private key just generated with the openssl tool .
◆Alipay public key
1. The two words "-----BEGIN PUBLIC KEY-----" and "-----END PUBLIC KEY-----" must be retained.
In short, the Alipay public key only needs to remain as it is in the demo .
(3) alipay_config.php configuration file
Integrate the alipay_config.php configuration file into the thinkPHP framework configuration file
<?<span>php </span><span>/*</span><span>* * Created by PhpStorm. * User: zhangxiaoliu * Date: 16/4/15 * Time: 上午10:39 </span><span>*/</span> <span>//</span><span>支付寶商家服務(wù)中心鏈接:https://b.alipay.com/login.htm?goto=https://b.alipay.com:443/newIndex.htm</span> <span>return</span> <span>array</span><span>( </span>'ALIMOBILEPAY_CONFIG'=><span>array</span><span>( </span><span>//</span><span>合作身份者id,以2088開頭的16位純數(shù)字, (合作身份者id的查看鏈接:https://b.alipay.com/order/pidAndKey.htm)</span> 'partner' => '2088XXXXXXXXXXXX', <span>//</span><span>收款支付寶賬號(hào),與partner的值一樣</span> 'seller_id' => '2088XXXXXXXXXXXX', <span>//</span><span>商戶的私鑰(后綴是.pem)文件相對路徑</span> 'private_key_path'=> NEW_PORTAL_DOMAIN.'key/rsa_private_key.pem', <span>//</span><span>支付寶公鑰(后綴是.pem)文件相對路徑</span> 'ali_public_key_path'=> NEW_PORTAL_DOMAIN.'key/alipay_public_key.pem', <span>//</span><span>簽名方式 不需修改</span> 'sign_type' => <span>strtoupper</span>('RSA'), <span>//</span><span>字符編碼格式 目前支持 gbk 或 utf-8</span> 'input_charset'=> 'utf-8', <span>//</span><span>ca證書路徑地址,用于curl中ssl校驗(yàn)</span> 'cacert' => NEW_PORTAL_DOMAIN.'key/cacert.pem', <span>//</span><span>訪問模式,根據(jù)自己的服務(wù)器是否支持ssl訪問,若支持請選擇https;若不支持請選擇http</span> 'transport' => 'http', <span>//</span><span>這里是異步通知頁面url,提交到項(xiàng)目的Payment控制器的notifyurl方法; //需http://格式的完整路徑,不能加?id=123這類自定義參數(shù)</span> 'notify_url'=> NEW_PORTAL_DOMAIN.'portal.php/AliMobilePay/notify_url.php', <span>//</span><span>這里是頁面跳轉(zhuǎn)通知url,提交到項(xiàng)目的Payment控制器的returnurl方法; //需http://格式的完整路徑,不能加?id=123這類自定義參數(shù)</span> 'return_url'=> NEW_PORTAL_DOMAIN.'portal.php/AliMobilePay/return_url.php', <span>//</span><span>支付成功跳轉(zhuǎn)到的頁面</span> 'successpage'=>NEW_PORTAL_DOMAIN.'portal.php/Success/index', <span>//</span><span>支付失敗跳轉(zhuǎn)到的頁面</span> 'errorpage'=>NEW_PORTAL_DOMAIN.'portal.php/Error/index', <span>//</span><span>商品展示地址</span> 'product_url'=>NEW_PORTAL_DOMAIN.'portal.php/Product/index',<span> ) );</span>
(4) Alipay Help Center
https://cshall.alipay.com/enterprise/index.htm
4. Call Alipay interface
(1) Create a new AliMobilePay controller
<?php namespace Portal\Controller; use Common\Component\FilterComponent; use Portal\Service\LogPaycallbacksService; use Portal\Service\GuozhanOrderService; use Portal\Model\Pengwifi\Guozhan\OrderModel; use Portal\Service\TokenService; use Portal\Service\UserService; use Portal\Service\SetMotoRadiusService; use Common\Model\Radius\RadcheckModel; /* * 購買上網(wǎng)卡的手機(jī)頁面支付寶接口 */ class AliMobilePayController extends CommonController{ protected $_order_model=null; protected $_order_service=null; protected $_token_service = null; protected $_Set_MotoRadius_service=null; protected $_RadcheckModel=null; protected $_log_pay_callbacks = null; protected function afterInit() { parent::afterInit(); vendor('AliMobilePay.Corefunction'); vendor('AliMobilePay.Rsafunction'); vendor('AliMobilePay.Notify'); vendor('AliMobilePay.Submit'); $this->_order_model= new OrderModel(); $this->_order_service= new GuozhanOrderService(); $this->_log_pay_callbacks = new LogPaycallbacksService(); $this->_service = new UserService(); $this->_token_service = new TokenService(); $this->_RadcheckModel = new RadcheckModel(); $this->_Set_MotoRadius_service = new SetMotoRadiusService(); } /** * 執(zhí)行新增訂單 */ protected function _post(){ if(isset($this->params['name']) && ($this->params['name']=="notify_url")){ $this->notify_url('notify_url'); die; } $this->insert_order(); } protected function _get(){ /* *根據(jù)配置文件里的路由規(guī)則: *':'.$var_controller.'/[:name]/[:action]'=> ':1/_index?', //匹配控制器后緊跟字符串,表示name * 例如:http://portal_v2.com/portal.php/Payment/Return.html * $notify_url會(huì)返回Return */ $notify_url = isset($this->params['name']) ? FilterComponent::getString($this->params['name']) : 'Unknown'; switch($notify_url){ case 'return_url': $this->return_url($notify_url); break; default: $this->_log_pay_callbacks->update(array('request_from'=>'Unknown'), false); exit('Wrong request url'); } } //服務(wù)器異步通知頁面方法 private function notify_url($notify_url){ $alipay_config = C('ALIMOBILEPAY_CONFIG'); //計(jì)算得出通知驗(yàn)證結(jié)果 $alipayNotify = new \AlipayNotify($alipay_config); $verify_result = $alipayNotify->verifyNotify(); if($verify_result) {//驗(yàn)證成功 //商戶訂單號(hào) $order_sn = $this->params['out_trade_no']; //支付寶交易號(hào) //$trade_no = $this->params['trade_no']; //交易狀態(tài) $trade_status = $this->params['trade_status']; $this->_log_pay_callbacks->update(array('request_from'=>$notify_url, 'order_sn'=>$order_sn, 'response_status'=>$trade_status), false); if (in_array($trade_status,array('TRADE_SUCCESS','TRADE_FINISHED'))) { //判斷該筆訂單是否在商戶網(wǎng)站中已經(jīng)做過處理 //如果沒有做過處理,根據(jù)訂單號(hào)(out_trade_no)在商戶網(wǎng)站的訂單系統(tǒng)中查到該筆訂單的詳細(xì),并執(zhí)行商戶的業(yè)務(wù)程序 //如果有做過處理,不執(zhí)行商戶的業(yè)務(wù)程序 if(!$this->checkorderstatus($order_sn)){ $result=$this->orderhandle($order_sn); if($result==true){ echo "success"; }else{ echo "fail"; } } }else{ echo "fail"; } }else { //驗(yàn)證失敗 echo "fail"; } } //頁面跳轉(zhuǎn)同步通知 private function return_url($notify_url){ $alipay_config=C('ALIMOBILEPAY_CONFIG'); //計(jì)算得出通知驗(yàn)證結(jié)果 $alipayNotify = new \AlipayNotify($alipay_config); $verify_result = $alipayNotify->verifyReturn(); if($verify_result) {//驗(yàn)證成功 //商戶訂單號(hào) $order_sn = $this->params['out_trade_no']; //支付寶交易號(hào) //$trade_no = $this->params['trade_no']; //交易狀態(tài) $trade_status = $this->params['trade_status']; $this->_log_pay_callbacks->update(array('request_from'=>$notify_url, 'order_sn'=>$order_sn, 'response_status'=>$trade_status), false); if (in_array($trade_status,array('TRADE_SUCCESS','TRADE_FINISHED'))) { //判斷該筆訂單是否在商戶網(wǎng)站中已經(jīng)做過處理 //如果沒有做過處理,根據(jù)訂單號(hào)(out_trade_no)在商戶網(wǎng)站的訂單系統(tǒng)中查到該筆訂單的詳細(xì),并執(zhí)行商戶的業(yè)務(wù)程序 //如果有做過處理,不執(zhí)行商戶的業(yè)務(wù)程序 if(!$this->checkorderstatus($order_sn)){ $result=$this->orderhandle($order_sn); //——請根據(jù)您的業(yè)務(wù)邏輯來編寫程序(以上代碼僅作參考)—— if($result==true){ header("Location:".C('ALIMOBILEPAY_CONFIG.successpage'));//跳轉(zhuǎn)到配置項(xiàng)中配置的支付成功頁面; }else{ header("Location:".C('ALIMOBILEPAY_CONFIG.errorpage'));//跳轉(zhuǎn)到配置項(xiàng)中配置的支付失敗頁面; } } }else { header("Location:".C('ALIMOBILEPAY_CONFIG.errorpage'));//跳轉(zhuǎn)到配置項(xiàng)中配置的支付失敗頁面; } }else { //支付寶頁面“返回商戶”按鈕的鏈接,商品頁面 header("Location:".C('ALIMOBILEPAY_CONFIG.product_url')); } } //在線交易訂單支付處理函數(shù) //函數(shù)功能:根據(jù)支付接口傳回的數(shù)據(jù)判斷該訂單是否已經(jīng)支付成功; //返回值:如果訂單已經(jīng)成功支付,返回true,否則返回false; private function checkorderstatus($order_sn){ $status=$this->_order_model->where("order_sn='$order_sn'")->getField('order_status'); if($status == OrderModel::ORDER_STATUS_PAYED){ return true; }else{ return false; } } //處理訂單函數(shù) //更新訂單狀態(tài),寫入訂單支付后返回的數(shù)據(jù) private function orderhandle($order_sn){ try{ //開啟事務(wù) $this->_order_model->startTrans(); $data['order_status']=OrderModel::ORDER_STATUS_PAYED; $affected_row=$this->_order_model->where("order_sn='$order_sn'")->save($data); $find=$this->_order_model->where("order_sn='$order_sn'")->field('location_id,goods_id,mobile,goods_number')->find(); //根據(jù)goods_id查找card_name對應(yīng)的上網(wǎng)時(shí)長 $goods_model=M('goods'); $card_model=M('card'); $card_name=$goods_model->where("id={$find['goods_id']}")->getField('card_name'); $duration=$card_model->where("location_id={$find['location_id']} and card_name='$card_name'")->order('id desc')->getField('duration'); $incre_time=($find['goods_number']) * $duration; $user_model=M('user'); $mobile=$find['mobile']; $user_info=$user_model->where("user_name='{$mobile}'")->field('id,end_time')->find(); $affected_row2=$user_model->where("user_name='{$mobile}'")->setInc('usable_time',$incre_time); //如果end_time 大于當(dāng)前的時(shí)間戳就累計(jì),否則就更新:使用當(dāng)前時(shí)間戳 加上 $incre_time if($user_info['end_time'] >= time()){ $user_model->where("user_name='{$mobile}'")->setInc('end_time',$incre_time); }else{ $update_data['end_time']=time()+$incre_time; $user_model->where("user_name='{$mobile}'")->save($update_data); } if(empty($affected_row)){ $this->_log_pay_callbacks->setException(L('ERROR_FAILED_UPDATE_ORDER'), $this->_log_pay_callbacks->getException('code')); throw new \Exception(); } if(empty($affected_row2)){ $this->_log_pay_callbacks->setException(L('ERROR_FAILED_UPDATE_USABLETIME'), $this->_log_pay_callbacks->getException('code')); throw new \Exception(); } //提交更新 if($affected_row && $affected_row2) { $this->_order_model->commit(); return true; } }catch(\Exception $e){ $this->_order_model->rollback(); return false; } } private function insert_order(){ $gw_id = isset($this->params['gw_id']) ? FilterComponent::get($this->params['gw_id']) : ''; if (empty($gw_id)) { exit('400_EMPTY_GWID'); } $router=M('router'); $location_id=$router->where("gw_id='$gw_id'")->getField('supplier_location_id'); $goods_number = isset($this->params['goods_number']) ? FilterComponent::get($this->params['goods_number'],'int') : ''; if (empty($goods_number)) { exit('400_EMPTY_GOODSNUMBER'); } $mobile = isset($this->params['mobile']) ? FilterComponent::get($this->params['mobile']) : ''; if (!preg_match('/^1[0-9]{10}$/',$mobile)) { exit('400_ERROR_MOBILE'); } $user=M('user'); //查詢充值號(hào)碼是否存在 $user_name=$user->where("user_name='$mobile'")->getField('user_name'); if(!$user_name){ exit('400_EMPTY_USERNAME'); } $goods_id = isset($this->params['goods_id']) ? FilterComponent::get($this->params['goods_id'],'int') : ''; if (empty($goods_id)) { exit('400_EMPTY_GOODSID'); } $goods=M('goods'); $unit_price=$goods->where("id=$goods_id")->getField('unit_price'); $this->params['WIDtotal_fee']=$unit_price * $goods_number; $data['location_id']=$location_id; $data['mobile']=$mobile; $data['goods_id']=$goods_id; $data['goods_type']=1;//1代表充值卡 $data['goods_number']=$goods_number; $data['total_price']=$this->params['WIDtotal_fee']; $data['pay_type']=OrderModel::PAY_TYPE_ALIPAY;//支付寶 //執(zhí)行添加操作 $insert_id=$this->_order_service->update($data,false); // var_dump($this->_order_service->getError()); // var_dump($this->_order_service->model->getError()); // var_dump($this->_order_service->model->getlastsql());die; if($insert_id){ $this->params['WIDout_trade_no']=$this->_order_model->where("id=$insert_id")->getField('order_sn'); /**************************請求參數(shù)**************************/ //支付類型 $payment_type = "1"; //必填,不能修改 //商戶訂單號(hào) $out_trade_no = $this->params['WIDout_trade_no']; //商戶網(wǎng)站訂單系統(tǒng)中唯一訂單號(hào),必填 $this->params['WIDsubject']='pengwifi_card'; //訂單名稱 $subject = $this->params['WIDsubject']; //必填 //付款金額 $total_fee = $this->params['WIDtotal_fee']; //必填 //$this->params['WIDshow_url']=trim(C('ALIMOBILEPAY_CONFIG.product_url')); $this->params['WIDshow_url']=$_SERVER['HTTP_REFERER']; //商品展示地址 $show_url = $this->params['WIDshow_url']; //必填,需以http://開頭的完整路徑,例如:http://www.商戶網(wǎng)址.com/myorder.html //訂單描述 $body = $this->params['WIDbody']; //選填 //超時(shí)時(shí)間 $it_b_pay = $this->params['WIDit_b_pay']; //選填 //錢包token $extern_token = $this->params['WIDextern_token']; //選填 /************************************************************/ //構(gòu)造要請求的參數(shù)數(shù)組,無需改動(dòng) $parameter = array( "service" => "alipay.wap.create.direct.pay.by.user", "partner" => trim(C('ALIMOBILEPAY_CONFIG.partner')), "seller_id" => trim(C('ALIMOBILEPAY_CONFIG.seller_id')), "payment_type" => $payment_type, "notify_url" => trim(C('ALIMOBILEPAY_CONFIG.notify_url')), "return_url" => trim(C('ALIMOBILEPAY_CONFIG.return_url')), "out_trade_no" => $out_trade_no, "subject" => $subject, "total_fee" => $total_fee, "show_url" => $show_url, "body" => $body, "it_b_pay" => $it_b_pay, "extern_token" => $extern_token, "_input_charset" => trim(strtolower(C('input_charset'))) ); $alipay_config=C('ALIMOBILEPAY_CONFIG'); //建立請求 $alipaySubmit = new \AlipaySubmit($alipay_config); //建立請求,以表單HTML形式構(gòu)造(默認(rèn)),經(jīng)測試post方法不行 $html_text = $alipaySubmit->buildRequestForm($parameter,"get", "確認(rèn)"); echo $html_text; }else{ echo 'fail'; } } }
<br /><br /><br /><br /><br /><br /><br />

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

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
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

The stablecoin trading process includes the steps of registering an exchange, completing certification, buying or selling. First, choose a trusted exchange such as Binance, OKX, etc., and then complete KYC identity authentication, and then buy stablecoins through fiat currency recharge or OTC transactions. You can also transfer the stablecoins to the fund account and sell them through P2P transactions and withdraw them to the bank card or Alipay. When operating, you need to pay attention to choosing a regulated platform, confirm transaction security and handling fees.

Bitcoin does not have an official app, and users mainly trade and manage them through third-party exchanges or account apps. 1. Binance has comprehensive functions and is suitable for all kinds of traders; 2. OKX provides integrated trading and Web3 accounts; 3. Huobi (HTX) is stable and reliable in the Asian market; 4. Gate.io is known for its rich currency; 5. KuCoin has diverse currencies and active communities; 6. Bybit is known for its derivatives trading. When downloading, you should visit the official website, scan the QR code, complete the installation according to the system, and set up security measures such as two-factor verification to ensure the security of the account.

Maybe there are many children's shoes that don't know the answers of Ant New Village Classroom today July 17th. Is the cotton paper used in the ancient books of intangible cultural heritage made of cotton? Let the editor answer this question below. Let's take a look with me!

To build a PHP content payment platform, it is necessary to build a user management, content management, payment and permission control system. First, establish a user authentication system and use JWT to achieve lightweight authentication; second, design the backend management interface and database fields to manage paid content; third, integrate Alipay or WeChat payment and ensure process security; fourth, control user access rights through session or cookies. Choosing the Laravel framework can improve development efficiency, use watermarks and user management to prevent content theft, optimize performance requires coordinated improvement of code, database, cache and server configuration, and clear policies must be formulated and malicious behaviors must be prevented.

Maybe there are many children's shoes who want to know the answers to Ant New Village on July 17, 2025. Let's bring you answers in this regard. Come and have a look.

Choose a payment platform based on user portrait. WeChat Pay is suitable for users in the WeChat ecosystem, and Alipay is suitable for mature consumer groups and PC-side large-scale payments; 2. Registering a merchant account to obtain AppID, MCHID, API keys and other qualifications is the prerequisite; 3. Using the official PHPSDK integrated interface can simplify development and improve security; 4. The PHP backend generates orders and initiates prepayment requests, and the front end calls for payment based on the returned data; 5. Asynchronous callbacks are the final basis for successful payment, and signatures, IP whitelists, SSL encryption transmission must be verified and idempotence must be realized to prevent repeated processing; 6. Timeout orders are closed through timed tasks, refunds must be called to the API and handled multiple states, reconciliation needs to be regularly compared with the platform flow and system orders to ensure the consistency of funds, and the entire flow

I believe some children's shoes want to know about Ant New Village's answer today. The editor below will bring you the answer. Let's take a look with me!

I believe some users do not understand what the main characteristics of Huang Ronghou are. Ant Manor’s answer on July 27 is the latest. Let’s solve this problem for you below. Let’s take a look!
