Home > Article > WeChat Applet > Asynchronous notification and verification order method of calling SDK after payment in WeChat applet
The following is a WeChat applet that uses the SDK’s asynchronous notification and verification method to process orders after payment. It has a good reference value and I hope it will be helpful to everyone
Asynchronous verification and order processing after the applet
<?php /** * Created by YuanPan. * User: YuanPan * Date: 2017/12/21 * Time: 15:15 */ namespace app\api\service; use app\api\model\Product; use app\lib\enum\OrderStatusEnum; use think\Db; use think\Exception; use think\Loader; use app\api\model\Order; //在这里依然引入WxPay.API.php即可完成引入 Loader::import('WxPay.WxPay',EXTEND_PATH,'.Api.php'); class WxNotify extends \WxPayNotify { //继承了父类,所以直接重写方法 public function NotifyProcess($data, &$msg) { //如果返回支付成功信息 if($data['return_code'] = 'SUCCESS'){ $orderNo = $data['out_trade_no']; Db::startTrans(); try { //判断订单状态 //在这里可以进行对数据库进行所机制 //简单说,当一个执行sql语句的事务想要操作表记录之前,先向数据库发出请求,对你访问的记录集加锁 //在这个事务释放这个锁之前,其他事务不能对这些数据进行更新操作 Order::where(['order_no'=>$orderNo])->lock(true)->find(); // $order = Order::get(['order_no'=>$orderNo]); //如果未支付 if ($order->status == 1) { $service = new \app\api\service\Order(); //查询到该订单号的商品和库存量信息 $stockStatus = $service->checkOrderStock($order->id); //如果库存量有,更新订单状态,以及减去商品库存 if ($stockStatus['pass']) { $this->updateOrderStatus($order->id, true); $this->reduceStock($stockStatus); //如果没有库存,订单状态修改为已支付,但订单未处理 } else { $this->updateOrderStatus($order->id, false); } } Db::commit(); //返回给微信 return true; }catch (Exception $e){ Db::rollback(); return fasle; } }else{ //如果微信返回失败的处理信息,那我们这里依然返回true,向微信表明态度 return true; } } //支付成功,减去商品库存 private function reduceStock($stockStatus) { //遍历减去 foreach ($stockStatus['pStatusArray'] as $v) { //使用tp5的setDec方法 Product::where(['id'=>$v['id']])->setDec('stock',$v['count']); } } //success为真,则订单修改为PAID,如果为假则修改为已支付,但订单未处理的状态,对应枚举信息修改 private function updateOrderStatus($orderID,$success) { $status = $success?OrderStatusEnum::PAID:OrderStatusEnum::PAID_BUT_OUT_OF; Order::where(['id'=>$orderID])->update(['status'=>$status]); } }
The controller is as follows:
public function receiveNotify() { //1:检查库存量防止超卖 //2:更新status状态 //3:减库存 //如果成功处理,返回成功处理信息,否则返回没有成功处理信息 $notify = new WxNotify(); $notify->handle(); }
The above is the entire content of this article. I hope it will be helpful to everyone’s study. For more related content, please pay attention to the PHP Chinese website!
Related recommendations:
Implementation of shopping cart function in WeChat mini program
Communication between pages in WeChat mini program Method
Introduction to defining global data and function reuse and templates in WeChat mini-program
The above is the detailed content of Asynchronous notification and verification order method of calling SDK after payment in WeChat applet. For more information, please follow other related articles on the PHP Chinese website!