Home > headlines > body text

Tutorials on how PHP beginners can learn to implement WeChat payment and Alipay payment

伊谢尔伦
Release: 2017-07-05 09:53:02
Original
5670 people have browsed it

The two most popular payment platforms at the moment, WeChat Pay and Alipay Payment, make payments very conveniently through mobile phone QR codes in streets, alleys, shopping malls, supermarkets, convenience stores, etc., reducing the use of cash.

Next, our PHP Chinese website will take PHP beginners to understand how to implement WeChat payment and Alipay payment.

The first thing you need is to have a certain grasp and understanding of PHP knowledge. You can learn through tutorials:

Related links: http ://www.php.cn/course/379.html

You can also learn the popular tp5 framework course in China first:

Related links: http://www.php.cn/course/486.html

WeChat payment

Project premise: use It is a tp framework, PHP language
Download the WeChat payment interface file provided by the WeChat platform, put it in the tp third-party class library vendor, and name it WxpayAPI


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支付实现类
Copy after login


1. The source code has been partially modified

(1) WxPay.Api. Comment out
in php //require_once "WxPay.Exception.php";
//require_once "WxPay.Config.php";
//require_once "WxPay.Data.php ";

(2) In WxPay.Config.php
it is necessary to configure APPID, MCHID, KEY and APPSECRET according to the merchant information.

(3) Comment out
in WxPay.Data.php //require_once "WxPay.Config.php";
//require_once "WxPay.Exception.php";

(4) Comment out
in WxPay.JsApiPay.php //require_once "../lib/WxPay.Api.php";

Configure these. Next is our focus.

2. In the order controller GoodsController.class.php, there are the order function sure() and the 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);
 }
Copy after login

3.[Emphasis! ! ! ] WxpayController .class.php WeChat payment controller implements the call to the WeChat interface

<?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(&#39;Y-m-d&#39;) . &#39;.log&#39;);
  $log = \Log::Init($logHandler, 15);
  $this->model = D("Wine/Orders");
  $this->url = MODULE_NAME . &#39;/&#39; . CONTROLLER_NAME . &#39;/index&#39;;
 }
 
 /**
  * 显示支付页面
  *
  */
 public function index() {
  // 判断当前订单是否被支付
  $orderid = I("get.o_id", 0, "intval");
  $orderid || $this->error("非法操作!");
  $this->assign(&#39;orderid&#39;,$orderid);
  $info = $this->model->findone(array("a.id" => $orderid, &#39;a.status&#39; => array(&#39;neq&#39;, &#39;-1&#39;)));
  $info || $this->error("暂未查询到该订单!");
  //10代表订单待支付的状态
  if ($info[&#39;order_status&#39;] != 10) {
   $this->error("订单已支付!");
  }
  //①、获取用户openid
  $tools = new \JsApiPay();
  $openId = $tools->GetOpenid(); #无法使用
  //初始化日志
  \Log::INFO(&#39;订单&#39; . var_export($info, true));
  $out_trade_no = \WxPayConfig::MCHID . date("YmdHis");
  $this->model->where(array("id" => $orderid))->save(array(&#39;out_trade_no&#39; => $out_trade_no));
//  $openId ="123"; #无法使用
  //②、统一下单
  $input = new \WxPayUnifiedOrder();
  $input->SetBody($info[&#39;mode_name&#39;]);
  $input->SetAttach($orderid);
  $input->SetOut_trade_no($out_trade_no);
//  $input->SetTotal_fee($orderArr[&#39;total_price&#39;]*100);实际支付价格
  $input->SetTotal_fee($info[&#39;pay_price&#39;]*100); //测试时请将支付价格改为0.01,土豪请避开此注释
  $this->assign(&#39;pay_price&#39;,$info[&#39;pay_price&#39;]);
  $input->SetTime_start(date("YmdHis"));
  $input->SetTime_expire(date("YmdHis", time() + 600));
//  $input->SetGoods_tag("test");# 优惠券
  $input->SetNotify_url(&#39;http://&#39; . $_SERVER[&#39;HTTP_HOST&#39;] . "/index.php/Wine/Wxpay/callback"); //回调地址
  $input->SetTrade_type("JSAPI");
  $input->SetOpenid($openId);
  $order = \WxPayApi::unifiedOrder($input);
//  echo &#39;<font color="#f00"><b>统一下单支付单信息</b></font><br/>&#39;;
//  $this->printf_info($order);//打印参数
    $this->assign(&#39;o_id&#39;,$orderid);
  $this->assign(&#39;jsApiParameters&#39;, $tools->GetJsApiParameters($order));
  //获取共享收货地址js函数参数
//  $this->assign(&#39;editAddress&#39;, $tools->GetEditAddressParameters());
  $this->display(&#39;wxpay&#39;);
  exit;
 }
 
 /**
  * 打印输出数组信息
  * @param type $data
  */
 public function printf_info($data) {
  foreach ($data as $key => $value) {
   echo "<font color=&#39;#00ff55;&#39;>$key</font> : $value <br/>";
  }
 }
 
 /* 支付成功回调函数 */
 
 public function callback() {
  /* 返回给微信服务器 */
//  $mes = array(
//   &#39;return_code&#39; => &#39;SUCCESS&#39;,
//   &#39;return_msg&#39; => &#39;OK&#39;
//  );
//  $this->ajaxReturn($mes, &#39;XML&#39;);
  $logHandler = new \CLogFileHandler("/projects/wine.huishuocs.com/data/pay_log/" . date(&#39;Y-m-d&#39;) . &#39;.log&#39;);
  $log = \Log::Init($logHandler, 15);
  //$streamData = isset($GLOBALS[&#39;HTTP_RAW_POST_DATA&#39;]) ? $GLOBALS[&#39;HTTP_RAW_POST_DATA&#39;] : &#39;&#39;;
 
  $streamData = file_get_contents(&#39;php://input&#39;);
  if ($streamData != &#39;&#39;) {
   $arr = $this->xmlToArray($streamData);
   \Log::INFO(&#39;支付&#39; . var_export($arr, true));
  } else {
   $ret = false;
  }
  // 回调值
  if (!empty($arr)) {
   # 数据
    \Log::INFO(&#39;数据1&#39; . var_export($arr, true));
   #修改订单状态
   $out_trade_no = $arr[&#39;out_trade_no&#39;];
   $newArr = array(&#39;order_status&#39; => 11,&#39;status&#39;=>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, &#39;a.status&#39; => array(&#39;neq&#39;, &#39;-1&#39;)));
   $sql = $this->model->getLastSql();
   \Log::INFO(&#39;数据2&#39; . $sql);
   #添加支付记录pay
   $pay = array(
    &#39;payment_code&#39; => &#39;wxpay&#39;,
    &#39;trade_no&#39;=>$info[&#39;order_code&#39;],
    &#39;out_trade_no&#39;=>$out_trade_no,
    &#39;order_id&#39;=>$info[&#39;id&#39;],
    &#39;create_time&#39;=>time()
   );
   M(&#39;payment_record&#39;)->add($pay);   
  }
 
  /* 返回给微信服务器 */
  $mes = array(
   &#39;return_code&#39; => &#39;SUCCESS&#39;,
   &#39;return_msg&#39; => &#39;OK&#39;
  );
  $this->ajaxReturn($mes, &#39;XML&#39;);
 }
 
 //将XML转为array
 public function xmlToArray($xml) {
  //禁止引用外部xml实体
  libxml_disable_entity_loader(true);
  $values = json_decode(json_encode(simplexml_load_string($xml, &#39;SimpleXMLElement&#39;, LIBXML_NOCDATA)), true);
  return $values;
 }
 
}
 
?>
Copy after login

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="TMPLPublic/css/weui.css" rel="external nofollow" type="text/css" rel="stylesheet"/>
  <title>微信订单支付</title>
  <script type="text/javascript">
   //调用微信JS api 支付
   function jsApiCall()
   {
    WeixinJSBridge.invoke(
      &#39;getBrandWCPayRequest&#39;,
      <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 = &#39;{:U("Orders/pay_ok",array("o_id"=>$o_id))}&#39;;
       } else {
        // 统一跳转
       }
 
      }
    );
   }
 
   function callpay()
   {
    if (typeof WeixinJSBridge == "undefined") {
     if (document.addEventListener) {
      document.addEventListener(&#39;WeixinJSBridgeReady&#39;, jsApiCall, false);
     } else if (document.attachEvent) {
      document.attachEvent(&#39;WeixinJSBridgeReady&#39;, jsApiCall);
      document.attachEvent(&#39;onWeixinJSBridgeReady&#39;, 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:;" rel="external nofollow" class="weui_btn weui_btn_primary" onclick="callpay()">立即支付</a>
       <!--<a href="{:U(&#39;Order/pay_ok&#39;,array(&#39;o_id&#39;=>$_GET[&#39;o_id&#39;]))}" rel="external nofollow" class="weui_btn weui_btn_default">取消支付</a>-->
      </p>
     </p>
     <!--     <p class="weui_extra_area">
           <a href="/wap/order/order_det/<?php echo $order[&#39;id&#39;]?>.html" rel="external nofollow" >查看详情</a>
          </p>-->
    </p>
   </p>
  </p>
 </body>
</html>
Copy after login

5. Jump to when payment is successful OrderController.class.php, order payment completed

/**
* 支付页面
*/
 public function pay_ok() {
  $o_id = I("get.o_id", 0, "intval");
  $info = $this->model->findone(array("a.id" => $o_id, &#39;a.status&#39; => array(&#39;neq&#39;, &#39;-1&#39;)));
  if (empty($info)) {
   # 获取最新可用的商品编号
   $goods = D(&#39;Goods&#39;)->where(array(&#39;status&#39; => &#39;1&#39;))->order(&#39;id desc&#39;)->find();
   $this->error("该订单不存在,请重新正确进入", U(&#39;Goods/sale&#39;, array(&#39;id&#39; => $goods[&#39;id&#39;])));
  }
  $this->assign(&#39;imgurl&#39;, "/wine/img/ok.png");
  $this->assign(&#39;tips&#39;, "订购成功");
  if (&#39;4&#39; == $info[&#39;pay_id&#39;]) {
   //微信支付成功
   $this->assign($info);
   $this->display();
  } else {
   $this->assign($info);
   $this->assign(&#39;tips&#39;, "订购失败");
   $this->assign(&#39;imgurl&#39;, "/wine/img/nook.png");
   $this->display();
  }
 }
Copy after login

At this point, the WeChat payment process ends.

Alipay payment

Without further ado, let’s go straight to the code!

Note:
1. The payment file is taken directly from Alipay
2. It is still a TP framework

[1]Put the file into a third party Class library:

(1)
* Class name: AlipayConfig.php
* Function: AlipayConfiguration file
* Modify configuration:

 // MD5密钥,安全检验码,由数字和字母组成的32位字符串,查看地址:https://b.alipay.com/order/pidAndKey.htm
  $alipay_config[&#39;key&#39;] = &#39;&#39;;//(**从支付宝中获取**)
 
 // 服务器异步通知页面路径 需http://格式的完整路径,不能加?id=123这类自定义参数,必须外网可以正常访问
  $alipay_config[&#39;notify_url&#39;] = &#39;http://&#39; . $_SERVER[&#39;SERVER_NAME&#39;] . &#39;/index.php/Wine/PayCallback/alipay_notify&#39;;
 
 // 页面跳转同步通知页面路径 需http://格式的完整路径,不能加?id=123这类自定义参数,必须外网可以正常访问
  $alipay_config[&#39;return_url&#39;] = &#39;http://&#39; . $_SERVER[&#39;SERVER_NAME&#39;] . &#39;/index.php?g=Wine&m=Orders&a=alipay_return&#39;;
Copy after login

(2)
* Class name: AlipayNotify.php
* Function: Alipay notification processing class
* Details: Process Alipay interface notification returns

(3 )
* Class name: Alipay.php
* Function: Mobile website payment interface access page
* Details: Process Alipay interface notifications and return

class Alipay {
 
 public function submit($params) {
//建立请求
  $alipaySubmit = new AlipaySubmit($alipay_config);
  $html_text = $alipaySubmit->buildRequestForm($parameter, "get", "确认");
  return &#39;<!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>&#39; . $html_text . &#39;
  </body>
  </html>&#39;;
 }
}
Copy after login

(4)
* Class name: notify_url.php
* Function: Alipay server asynchronous notification page
* Details: Process Alipay interface notification returns

[2] Payment business logic
(1) Go to GoodsController.class.php and submit the order ajax_sure()

public function ajax_sure() {<br>
 $data[&#39;order_code&#39;] = $order_code;
 $addr[0] = $_POST[&#39;prov&#39;];
 $addr[1] = $_POST[&#39;city&#39;];
 $addr[2] = $_POST[&#39;dist&#39;];
 $addr[3] = $_POST[&#39;area&#39;];
 $data[&#39;area&#39;] = serialize($addr);
 $data[&#39;create_time&#39;] = time();
 $data[&#39;update_time&#39;] = time();
 $data[&#39;ip&#39;] = $_SERVER[&#39;REMOTE_ADDR&#39;];
 if ($data[&#39;pay_id&#39;] == 1) {
   $data[&#39;order_status&#39;] = 11; //已付款
   $data[&#39;status&#39;] = &#39;1&#39;;
 } else {
   $data[&#39;order_status&#39;] = 10; //待付款
   $data[&#39;status&#39;] = &#39;1&#39;;
 }
 //函数调用 返回信息
 $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 (&#39;3&#39; == $data[&#39;pay_id&#39;]) {
   //支付宝支付
   $msg = &#39;正在为您跳转到支付宝支付页面,请等待……&#39;;
   $url = U("Pay/doalipay", array(&#39;o_id&#39; => $add_id));
  }
  $this->success("订单提交成功!" . $msg, $url);
 }
Copy after login

(2) PayController.class.php and go to

 /**
  * 支付页面
  */
 public function doalipay() {
  $o_id = I("get.o_id", 0, "intval");
  $info = $this->model->findone(array("a.id" => $o_id, &#39;a.status&#39; => array(&#39;neq&#39;, &#39;-1&#39;)));
  //10代表订单待支付的状态
  if ($info[&#39;order_status&#39;] != 10) {
   $this->error("订单已支付!");
  }
  vendor("Payment.Alipay.Alipay");
  $alipay = new \Alipay();
  $param[&#39;order_sn&#39;] = $info[&#39;order_code&#39;];
//  $param[&#39;order_amount&#39;] = $info[&#39;pay_price&#39;];
  $param[&#39;order_amount&#39;] = 0.01;//测试支付时,将支付价格设为0.01元,土豪朋友忽略此提示O(∩_∩)O~
  $param[&#39;order_subject&#39;] = &#39;支付宝支付测试&#39;;
  $param[&#39;return_url&#39;] = &#39;http://&#39; . $_SERVER[&#39;SERVER_NAME&#39;] . &#39;/index.php/Wine/Orders/pay_ok/o_id/&#39;.$o_id;
  $return = $alipay->submit($param);
  echo $return;
  exit;
 }
Copy after login

It’s just a few simple steps. At this point, Alipay The payment process is over.


Recommended related articles:

1. Share the example code of the mini program payment function Tutorial

2. How to use the WeChat mini program for online payment? Summary of online payment example usage



Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!