


A painstaking work: Application of Alipay's mobile website payment interface, a painstaking work_PHP tutorial
A 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>支付宝商家服务中心链接</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> ┈┈┈┈┈┈支付宝接口公用函数文件<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函数文件<br />│<br />├log.txt┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈日志文件<br />│<br />├<span>alipay.config.php</span>┈┈┈┈┈┈┈┈┈┈┈┈基础配置类文件<br />│<br />├<span>alipayapi.php</span>┈┈┈┈┈┈┈┈┈┈┈┈┈┈支付宝接口入口文件<br />│<br />├<span>notify_url.php</span> ┈┈┈┈┈┈┈┈┈┈┈┈┈服务器异步通知页面文件<br />│<br />├<span>return_url.php</span> ┈┈┈┈┈┈┈┈┈┈┈┈┈页面跳转同步通知文件<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中校验SSL的CA证书文件<br />│<br />└<span>readme.txt</span> ┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈使用说明文本<br /><br /><br /><span><span><strong>3.</strong> 把必需的文件整合到框架里(我当时用的是thinkPHP框架)</span><br /> (1)在<img src="/static/imghw/default1.png" data-src="http://www.bkjia.com/uploads/allimg/160415/1643115256-2.png" class="lazy" alt="" /> 里新建一个文件夹叫<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个文件拷贝到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> (2)在根目录下建立一个文件夹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>支付宝商家服务中心链接: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位纯数字, (合作身份者id的查看链接:https://b.alipay.com/order/pidAndKey.htm)</span> 'partner' => '2088XXXXXXXXXXXX', <span>//</span><span>收款支付宝账号,与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校验</span> 'cacert' => NEW_PORTAL_DOMAIN.'key/cacert.pem', <span>//</span><span>访问模式,根据自己的服务器是否支持ssl访问,若支持请选择https;若不支持请选择http</span> 'transport' => 'http', <span>//</span><span>这里是异步通知页面url,提交到项目的Payment控制器的notifyurl方法; //需http://格式的完整路径,不能加?id=123这类自定义参数</span> 'notify_url'=> NEW_PORTAL_DOMAIN.'portal.php/AliMobilePay/notify_url.php', <span>//</span><span>这里是页面跳转通知url,提交到项目的Payment控制器的returnurl方法; //需http://格式的完整路径,不能加?id=123这类自定义参数</span> 'return_url'=> NEW_PORTAL_DOMAIN.'portal.php/AliMobilePay/return_url.php', <span>//</span><span>支付成功跳转到的页面</span> 'successpage'=>NEW_PORTAL_DOMAIN.'portal.php/Success/index', <span>//</span><span>支付失败跳转到的页面</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; /* * 购买上网卡的手机页面支付宝接口 */ 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(); } /** * 执行新增订单 */ 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(){ /* *根据配置文件里的路由规则: *':'.$var_controller.'/[:name]/[:action]'=> ':1/_index?', //匹配控制器后紧跟字符串,表示name * 例如:http://portal_v2.com/portal.php/Payment/Return.html * $notify_url会返回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'); } } //服务器异步通知页面方法 private function notify_url($notify_url){ $alipay_config = C('ALIMOBILEPAY_CONFIG'); //计算得出通知验证结果 $alipayNotify = new \AlipayNotify($alipay_config); $verify_result = $alipayNotify->verifyNotify(); if($verify_result) {//验证成功 //商户订单号 $order_sn = $this->params['out_trade_no']; //支付宝交易号 //$trade_no = $this->params['trade_no']; //交易状态 $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'))) { //判断该笔订单是否在商户网站中已经做过处理 //如果没有做过处理,根据订单号(out_trade_no)在商户网站的订单系统中查到该笔订单的详细,并执行商户的业务程序 //如果有做过处理,不执行商户的业务程序 if(!$this->checkorderstatus($order_sn)){ $result=$this->orderhandle($order_sn); if($result==true){ echo "success"; }else{ echo "fail"; } } }else{ echo "fail"; } }else { //验证失败 echo "fail"; } } //页面跳转同步通知 private function return_url($notify_url){ $alipay_config=C('ALIMOBILEPAY_CONFIG'); //计算得出通知验证结果 $alipayNotify = new \AlipayNotify($alipay_config); $verify_result = $alipayNotify->verifyReturn(); if($verify_result) {//验证成功 //商户订单号 $order_sn = $this->params['out_trade_no']; //支付宝交易号 //$trade_no = $this->params['trade_no']; //交易状态 $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'))) { //判断该笔订单是否在商户网站中已经做过处理 //如果没有做过处理,根据订单号(out_trade_no)在商户网站的订单系统中查到该笔订单的详细,并执行商户的业务程序 //如果有做过处理,不执行商户的业务程序 if(!$this->checkorderstatus($order_sn)){ $result=$this->orderhandle($order_sn); //——请根据您的业务逻辑来编写程序(以上代码仅作参考)—— if($result==true){ header("Location:".C('ALIMOBILEPAY_CONFIG.successpage'));//跳转到配置项中配置的支付成功页面; }else{ header("Location:".C('ALIMOBILEPAY_CONFIG.errorpage'));//跳转到配置项中配置的支付失败页面; } } }else { header("Location:".C('ALIMOBILEPAY_CONFIG.errorpage'));//跳转到配置项中配置的支付失败页面; } }else { //支付宝页面“返回商户”按钮的链接,商品页面 header("Location:".C('ALIMOBILEPAY_CONFIG.product_url')); } } //在线交易订单支付处理函数 //函数功能:根据支付接口传回的数据判断该订单是否已经支付成功; //返回值:如果订单已经成功支付,返回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; } } //处理订单函数 //更新订单状态,写入订单支付后返回的数据 private function orderhandle($order_sn){ try{ //开启事务 $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(); //根据goods_id查找card_name对应的上网时长 $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 大于当前的时间戳就累计,否则就更新:使用当前时间戳 加上 $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'); //查询充值号码是否存在 $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;//支付宝 //执行添加操作 $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'); /**************************请求参数**************************/ //支付类型 $payment_type = "1"; //必填,不能修改 //商户订单号 $out_trade_no = $this->params['WIDout_trade_no']; //商户网站订单系统中唯一订单号,必填 $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.商户网址.com/myorder.html //订单描述 $body = $this->params['WIDbody']; //选填 //超时时间 $it_b_pay = $this->params['WIDit_b_pay']; //选填 //钱包token $extern_token = $this->params['WIDextern_token']; //选填 /************************************************************/ //构造要请求的参数数组,无需改动 $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形式构造(默认),经测试post方法不行 $html_text = $alipaySubmit->buildRequestForm($parameter,"get", "确认"); echo $html_text; }else{ echo 'fail'; } } }
<br /><br /><br /><br /><br /><br /><br />

Hot AI Tools

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

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

Undress AI Tool
Undress images for free

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)

Hot Topics

Alipay PHP...

Problem Description When calling Alipay EasySDK using PHP, after filling in the parameters according to the official code, an error message was reported during operation: "Undefined...

The OKX trading platform offers a variety of rates, including transaction fees, withdrawal fees and financing fees. For spot transactions, transaction fees vary according to transaction volume and VIP level, and adopt the "market maker model", that is, the market charges a lower handling fee for each transaction. In addition, OKX also offers a variety of futures contracts, including currency standard contracts, USDT contracts and delivery contracts, and the fee structure of each contract is also different.

H5. The main difference between mini programs and APP is: technical architecture: H5 is based on web technology, and mini programs and APP are independent applications. Experience and functions: H5 is light and easy to use, with limited functions; mini programs are lightweight and have good interactiveness; APPs are powerful and have smooth experience. Compatibility: H5 is cross-platform compatible, applets and APPs are restricted by the platform. Development cost: H5 has low development cost, medium mini programs, and highest APP. Applicable scenarios: H5 is suitable for information display, applets are suitable for lightweight applications, and APPs are suitable for complex functions.

This article provides a detailed guide to safe download of Ouyi OKX App in China. Due to restrictions on domestic app stores, users are advised to download the App through the official website of Ouyi OKX, or use the QR code provided by the official website to scan and download. During the download process, be sure to verify the official website address, check the application permissions, perform a security scan after installation, and enable two-factor verification. During use, please abide by local laws and regulations, use a safe network environment, protect account security, be vigilant against fraud, and invest rationally. This article is for reference only and does not constitute investment advice. Digital asset transactions are at your own risk.

Gate.io (Sesame Open Door) is the world's leading cryptocurrency trading platform. This article provides a complete tutorial on spot trading of Gate.io. The tutorial covers steps such as account registration and login, KYC certification, fiat currency and digital currency recharge, trading pair selection, limit/market transaction orders, and orders and transaction records viewing, helping you quickly get started on the Gate.io platform for cryptocurrency trading. Whether a beginner or a veteran, you can benefit from this tutorial and easily master the Gate.io trading skills.

The choice of H5 and applet depends on the requirements. For applications with cross-platform, rapid development and high scalability, choose H5; for applications with native experience, rich functions and platform dependencies, choose applets.

This article provides a brief guide to buying and selling of Binance virtual currency updated in 2025, and explains in detail the operation steps of virtual currency transactions on the Binance platform. The guide covers fiat currency purchase USDT, currency transaction purchase of other currencies (such as BTC), and selling operations, including market trading and limit trading. In addition, the guide also specifically reminds key risks such as payment security and network selection for fiat currency transactions, helping users to conduct Binance transactions safely and efficiently. Through this article, you can quickly master the skills of buying and selling virtual currencies on the Binance platform and reduce transaction risks.
