PHP development of WeChat payment and Alipay payment examples
This article mainly shares with you PHP development of WeChat payment and Alipay payment examples. There is no explanation about the payment process. You can search on the PHP Chinese website by yourself.
-
##WeChat payment
##项目前提:本人用的是tp框架,PHP语言下载到微信平台提供的微信支付接口文件,放在了tp第三方类库vendor,命名为WxpayAPI,
Copy after login
WxpayAPI/lib/WxPay.Api.php 接口访问类; WxpayAPI/lib/WxPay.Config.php 配置账号信息; WxpayAPI/lib/WxPay.Data.php 数据对象基础类; WxpayAPI/lib/WxPay.Exception.php 微信支付API异常类; WxpayAPI/lib/WxPay.Notify.php 回调基础类 WxpayAPI/example/WxPay.JsApiPay.php JSAPI支付实现类
1. Partially modified the source code
(1)WxPay.Api.php 里注释掉 //require_once "WxPay.Exception.php"; //require_once "WxPay.Config.php"; //require_once "WxPay.Data.php"; (2)WxPay.Config.php里 需要根据商户信息对APPID , MCHID ,KEY , APPSECRET 进行配置。 (3)WxPay.Data.php 里注释掉 //require_once "WxPay.Config.php"; //require_once "WxPay.Exception.php"; (4)WxPay.JsApiPay.php 里注释掉 //require_once "../lib/WxPay.Api.php";
After configuring these, the next step is our focus. .
2. In the order controller GoodsController.class.php there are order function sure() and callback information function Callback_url()
/** * 提交订单函数 */ public function sure() { $o_model = D("Wine/Orders"); if (IS_AJAX) { $data = I("post."); if ($o_model->create($data)) { if (!sp_check_verify_code()) { $this->error("验证码错误!"); } #生成随机订单号 $order_code = 'O' . date('YmdHis') . $o_model->get_order_code(4); while ($o_model->findone(array("order_code" => $order_code))) { $order_code = 'O' . date('YmdHis') . $o_model->get_order_code(4); } $data['order_code'] = $order_code; $addr[0] = $_POST['prov']; $addr[1] = $_POST['city']; $addr[2] = $_POST['dist']; $addr[3] = $_POST['area']; $data['area'] = serialize($addr); $data['create_time'] = time(); $data['update_time'] = time(); if ($data['pay_id'] == 1) { $data['order_status'] = 11; //已付款 $data['status'] = '1'; } else { $data['order_status'] = 10; //待付款 $data['status'] = '1'; } //函数调用 返回信息 $this->Callback_url($data); } else { $this->error($o_model->getError()); } } else { $this->error($o_model->getError()); } } /** * 回调信息函数 * @param type $data */ public function Callback_url($data) { $o_model = D("Wine/Orders"); $add_id = $o_model->add($data); if (!$add_id) { $this->error("订单提交失败,请稍后重试!"); } if ('4' == $data['pay_id']) { if ('4' == $data['pay_id']) { //微信支付 $msg = '正在为您跳转到微信支付页面,请等待……'; $url = "/index.php/wine/wxpay/index/?o_id=$add_id"; } $this->success("订单提交成功!" . $msg, $url); }
##3.
[Key point! ! ! ]
<?php /** * 微信支付接口调用 */ namespace Wine\Controller; use Common\Controller\HomebaseController; class WxpayController extends HomebaseController { public function _initialize() { parent::_initialize(); Vendor("WxpayAPI/example/log");//订单数据写入日志 //注: 引入第三方类库中的微信接口文件,对于文件名含有.的,皆用#代替连接才能引入,后缀名不写。 Vendor("WxpayAPI/example/WxPay#JsApiPay"); Vendor("WxpayAPI/lib/WxPay#Config"); Vendor("WxpayAPI/lib/WxPay#Data"); Vendor("WxpayAPI/lib/WxPay#Exception"); Vendor("WxpayAPI/lib/WxPay#Notify"); Vendor("WxpayAPI/lib/WxPay#Api"); //初始化日志 $logHandler = new \CLogFileHandler("/projects/wine.huishuocs.com/data/pay_log/" . date('Y-m-d') . '.log'); $log = \Log::Init($logHandler, 15); $this->model = D("Wine/Orders"); $this->url = MODULE_NAME . '/' . CONTROLLER_NAME . '/index'; } /** * 显示支付页面 * */ public function index() { // 判断当前订单是否被支付 $orderid = I("get.o_id", 0, "intval"); $orderid || $this->error("非法操作!"); $this->assign('orderid',$orderid); $info = $this->model->findone(array("a.id" => $orderid, 'a.status' => array('neq', '-1'))); $info || $this->error("暂未查询到该订单!"); //10代表订单待支付的状态 if ($info['order_status'] != 10) { $this->error("订单已支付!"); } //①、获取用户openid $tools = new \JsApiPay(); $openId = $tools->GetOpenid(); #无法使用 //初始化日志 \Log::INFO('订单' . var_export($info, true)); $out_trade_no = \WxPayConfig::MCHID . date("YmdHis"); $this->model->where(array("id" => $orderid))->save(array('out_trade_no' => $out_trade_no)); // $openId ="123"; #无法使用 //②、统一下单 $input = new \WxPayUnifiedOrder(); $input->SetBody($info['mode_name']); $input->SetAttach($orderid); $input->SetOut_trade_no($out_trade_no); // $input->SetTotal_fee($orderArr['total_price']*100);实际支付价格 $input->SetTotal_fee($info['pay_price']*100); //测试时请将支付价格改为0.01,土豪请避开此注释 $this->assign('pay_price',$info['pay_price']); $input->SetTime_start(date("YmdHis")); $input->SetTime_expire(date("YmdHis", time() + 600)); // $input->SetGoods_tag("test");# 优惠券 $input->SetNotify_url('http://' . $_SERVER['HTTP_HOST'] . "/index.php/Wine/Wxpay/callback"); //回调地址 $input->SetTrade_type("JSAPI"); $input->SetOpenid($openId); $order = \WxPayApi::unifiedOrder($input); // echo '<font color="#f00"><b>统一下单支付单信息</b></font><br/>'; // $this->printf_info($order);//打印参数 $this->assign('o_id',$orderid); $this->assign('jsApiParameters', $tools->GetJsApiParameters($order)); //获取共享收货地址js函数参数 // $this->assign('editAddress', $tools->GetEditAddressParameters()); $this->display('wxpay'); exit; } /** * 打印输出数组信息 * @param type $data */ public function printf_info($data) { foreach ($data as $key => $value) { echo "<font color='#00ff55;'>$key</font> : $value <br/>"; } } /* 支付成功回调函数 */ public function callback() { /* 返回给微信服务器 */ // $mes = array( // 'return_code' => 'SUCCESS', // 'return_msg' => 'OK' // ); // $this->ajaxReturn($mes, 'XML'); $logHandler = new \CLogFileHandler("/projects/wine.huishuocs.com/data/pay_log/" . date('Y-m-d') . '.log'); $log = \Log::Init($logHandler, 15); //$streamData = isset($GLOBALS['HTTP_RAW_POST_DATA']) ? $GLOBALS['HTTP_RAW_POST_DATA'] : ''; $streamData = file_get_contents('php://input'); if ($streamData != '') { $arr = $this->xmlToArray($streamData); \Log::INFO('支付' . var_export($arr, true)); } else { $ret = false; } // 回调值 if (!empty($arr)) { # 数据 \Log::INFO('数据1' . var_export($arr, true)); #修改订单状态 $out_trade_no = $arr['out_trade_no']; $newArr = array('order_status' => 11,'status'=>1); $this->model->where(array("out_trade_no" => $out_trade_no))->save($newArr); $info = $this->model->findone(array("a.out_trade_no" => $out_trade_no, 'a.status' => array('neq', '-1'))); $sql = $this->model->getLastSql(); \Log::INFO('数据2' . $sql); #添加支付记录pay $pay = array( 'payment_code' => 'wxpay', 'trade_no'=>$info['order_code'], 'out_trade_no'=>$out_trade_no, 'order_id'=>$info['id'], 'create_time'=>time() ); M('payment_record')->add($pay); } /* 返回给微信服务器 */ $mes = array( 'return_code' => 'SUCCESS', 'return_msg' => 'OK' ); $this->ajaxReturn($mes, 'XML'); } //将XML转为array public function xmlToArray($xml) { //禁止引用外部xml实体 libxml_disable_entity_loader(true); $values = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true); return $values; } } ?>
4. Front-end WeChat payment page wxpay.html
<html> <head> <meta http-equiv="content-type" content="text/html;charset=utf-8"/> <meta name="viewport" content="width=device-width, initial-scale=1"/> <link href="__TMPL__Public/css/weui.css" type="text/css" rel="stylesheet"/> <title>微信订单支付</title> <script type="text/javascript"> //调用微信JS api 支付 function jsApiCall() { WeixinJSBridge.invoke( 'getBrandWCPayRequest', <php> echo $jsApiParameters; </php>, function(res) { WeixinJSBridge.log(res.err_msg); if (res.err_msg == "get_brand_wcpay_request:ok") { // alert(res.err_code + res.err_desc + res.err_msg); // 成功跳转页面 window.location.href = '{:U("Orders/pay_ok",array("o_id"=>$o_id))}'; } else { // 统一跳转 } } ); } function callpay() { if (typeof WeixinJSBridge == "undefined") { if (document.addEventListener) { document.addEventListener('WeixinJSBridgeReady', jsApiCall, false); } else if (document.attachEvent) { document.attachEvent('WeixinJSBridgeReady', jsApiCall); document.attachEvent('onWeixinJSBridgeReady', jsApiCall); } } else { jsApiCall(); } } </script> </head> <body> <br/> <p class="container" id="container"><p class="msg"> <p class="weui_msg"> <p class="weui_icon_area"><i class="weui_icon_success weui_icon_msg"></i></p> <p class="weui_text_area"> <h2 class="weui_msg_title">订单已生成</h2> <p class="weui_msg_desc">该笔订单支付金额为:<php> echo $pay_price;</php></p> </p> <p class="weui_opr_area"> <p class="weui_btn_area"> <a href="javascript:;" class="weui_btn weui_btn_primary" onclick="callpay()">立即支付</a> <!--<a href="{:U('Order/pay_ok',array('o_id'=>$_GET['o_id']))}" class="weui_btn weui_btn_default">取消支付</a>--> </p> </p> <!-- <p class="weui_extra_area"> <a href="/wap/order/order_det/<?php echo $order['id']?>.html">查看详情</a> </p>--> </p> </p> </p> </body> </html>
5. The payment successfully jumps to OrderController.class.php, and the order payment is completed
At this point, the WeChat payment process ends.
Alipay payment
Not much to say, just direct Get on the code!
注:1.支付文件是从支付宝上直接拿过来的2.依旧是TP框架
【1】将文件放入第三方类库:
/** * 支付页面 */ public function pay_ok() { $o_id = I("get.o_id", 0, "intval"); $info = $this->model->findone(array("a.id" => $o_id, 'a.status' => array('neq', '-1'))); if (empty($info)) { # 获取最新可用的商品编号 $goods = D('Goods')->where(array('status' => '1'))->order('id desc')->find(); $this->error("该订单不存在,请重新正确进入", U('Goods/sale', array('id' => $goods['id']))); } $this->assign('imgurl', "/wine/img/ok.png"); $this->assign('tips', "订购成功"); if ('4' == $info['pay_id']) { //微信支付成功 $this->assign($info); $this->display(); } else { $this->assign($info); $this->assign('tips', "订购失败"); $this->assign('imgurl', "/wine/img/nook.png"); $this->display(); } }
(1) * 类名:AlipayConfig.php * 功能:支付宝配置文件 * 修改配置: // MD5密钥,安全检验码,由数字和字母组成的32位字符串,查看地址:https://b.alipay.com/order/pidAndKey.htm $alipay_config['key'] = '';//(**从支付宝中获取**) // 服务器异步通知页面路径 需http://格式的完整路径,不能加?id=123这类自定义参数,必须外网可以正常访问 $alipay_config['notify_url'] = 'http://' . $_SERVER['SERVER_NAME'] . '/index.php/Wine/PayCallback/alipay_notify'; // 页面跳转同步通知页面路径 需http://格式的完整路径,不能加?id=123这类自定义参数,必须外网可以正常访问 $alipay_config['return_url'] = 'http://' . $_SERVER['SERVER_NAME'] . '/index.php?g=Wine&m=Orders&a=alipay_return'; (2) * 类名:AlipayNotify.php * 功能:支付宝通知处理类 * 详细:处理支付宝各接口通知返回 (3) * 类名:Alipay.php * 功能:手机网站支付接口接入页 * 详细:处理支付宝各接口通知返回 class Alipay { public function submit($params) { //建立请求 $alipaySubmit = new AlipaySubmit($alipay_config); $html_text = $alipaySubmit->buildRequestForm($parameter, "get", "确认"); return '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>支付宝支付</title> </head>' . $html_text . ' </body> </html>'; } } (4) * 类名:notify_url.php * 功能:支付宝服务器异步通知页面 * 详细:处理支付宝各接口通知返回
##Paste_Image.png
【2】支付业务逻辑 (1)GoodsController.class.php 下提交订单 ajax_sure() public function ajax_sure() {<br> $data['order_code'] = $order_code; $addr[0] = $_POST['prov']; $addr[1] = $_POST['city']; $addr[2] = $_POST['dist']; $addr[3] = $_POST['area']; $data['area'] = serialize($addr); $data['create_time'] = time(); $data['update_time'] = time(); $data['ip'] = $_SERVER['REMOTE_ADDR']; if ($data['pay_id'] == 1) { $data['order_status'] = 11; //已付款 $data['status'] = '1'; } else { $data['order_status'] = 10; //待付款 $data['status'] = '1'; } //函数调用 返回信息 $this->Callback_url($data); } /** * 回调信息函数 * @param type $data */ public function Callback_url($data) { $o_model = D("Wine/Orders"); $add_id = $o_model->add($data); if (!$add_id) { $this->error("订单提交失败,请稍后重试!"); }<br> if ('3' == $data['pay_id']) { //支付宝支付 $msg = '正在为您跳转到支付宝支付页面,请等待……'; $url = U("Pay/doalipay", array('o_id' => $add_id)); } $this->success("订单提交成功!" . $msg, $url); } (2)PayController.class.php 下 /** * 支付页面 */ public function doalipay() { $o_id = I("get.o_id", 0, "intval"); $info = $this->model->findone(array("a.id" => $o_id, 'a.status' => array('neq', '-1'))); //10代表订单待支付的状态 if ($info['order_status'] != 10) { $this->error("订单已支付!"); } vendor("Payment.Alipay.Alipay"); $alipay = new \Alipay(); $param['order_sn'] = $info['order_code']; // $param['order_amount'] = $info['pay_price']; $param['order_amount'] = 0.01;//测试支付时,将支付价格设为0.01元,土豪朋友忽略此提示O(∩_∩)O~ $param['order_subject'] = '支付宝支付测试'; $param['return_url'] = 'http://' . $_SERVER['SERVER_NAME'] . '/index.php/Wine/Orders/pay_ok/o_id/'.$o_id; $return = $alipay->submit($param); echo $return; exit; }
It’s just a few simple steps. At this point, Alipay payment The process is over. Related recommendations:
php develops WeChat payment enterprise payment example code
Alipay payment PHP background signature implementation method
The above is the detailed content of PHP development of WeChat payment and Alipay payment examples. For more information, please follow other related articles on the PHP Chinese website!

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











PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.
