Home  >  Article  >  Backend Development  >  Teach you to use EasyWeChat and PHP to build the reservation and queuing functions of the WeChat applet

Teach you to use EasyWeChat and PHP to build the reservation and queuing functions of the WeChat applet

王林
王林Original
2023-07-18 09:45:132072browse

Teach you to use EasyWeChat and PHP to build the reservation and queuing functions of WeChat mini-programs

Introduction:
With the increasing popularity of WeChat mini-programs, more and more companies are beginning to provide them in mini-programs Reservations and queuing services. This article will teach you how to use EasyWeChat and PHP to build the reservation and queuing functions of the WeChat applet, allowing users to make instant online reservations and wait in line. This article will introduce the specific implementation process in detail through code examples.

1. Environmental requirements

  • Server environment: It is recommended to use a Linux environment, and have PHP and MySQL installed;
  • EasyWeChat: a library that facilitates the development of WeChat applications.

2. Build the environment

  1. Download EasyWeChat
    First, we need to download and configure EasyWeChat in our project. It can be installed through composer and run the following command:

    composer require overtrue/wechat
  2. Configure application
    Create a new service provider in the application and configure EasyWeChat:

    <?php
    // services/WeChatServiceProvider.php
    
    use EasyWeChatFactory;
    use PimpleContainer;
    use PimpleServiceProviderInterface;
    
    class WeChatServiceProvider implements ServiceProviderInterface
    {
     public function register(Container $app)
     {
         $config = [
             'app_id' => 'your-app-id',
             'secret' => 'your-app-secret',
             'token' => 'your-token',
             'response_type' => 'array',
             'log' => [
                 'level' => 'debug',
                 'file' => '/path/to/your/log/file.log',
             ],
         ];
    
         $app['wechat'] = function () use ($config) {
             return Factory::officialAccount($config);
         };
     }
    }

    In the above In the code, you need to replace it with the ID, secret key and token of your own applet. At the same time, log configuration can be performed as needed.

  3. Register service provider
    Register WeChatServiceProvider to the service provider in the project:

    $app->register(new WeChatServiceProvider());

3. Implement the appointment function

In the WeChat applet, we can implement the reservation function through template messages. In the mini program, after the user fills in the relevant reservation information and submits it, a reservation record will be generated in the background, and the information in the record will be sent to the user as a template message.

  1. Database table design
    First, create a database table named appointment to store user appointment information. The table structure reference is as follows:

    CREATE TABLE `appointment` (
      `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
      `openid` varchar(100) NOT NULL,
      `name` varchar(50) NOT NULL,
      `phone` varchar(20) NOT NULL,
      `date` date NOT NULL,
      `time` time NOT NULL,
      `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
      PRIMARY KEY (`id`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
  2. Mini program page
    In the mini program, we need to create a reservation page, and the user fills in the relevant information and submits it. An example is as follows:

    <view class="container">
      <form bindsubmit="submitForm">
     <view class="form-item">
       <text>姓名:</text>
       <input type="text" name="name" placeholder="请输入姓名" bindinput="bindNameInput" />
     </view>
     <view class="form-item">
       <text>手机号:</text>
       <input type="number" name="phone" placeholder="请输入手机号" bindinput="bindPhoneInput" />
     </view>
     <view class="form-item">
       <text>日期:</text>
       <picker mode="date" bindchange="bindDateChange">
         <view>{{ date }}</view>
       </picker>
     </view>
     <view class="form-item">
       <text>时间:</text>
       <picker mode="time" bindchange="bindTimeChange">
         <view>{{ time }}</view>
       </picker>
     </view>
     <view class="form-item">
       <button form-type="submit" class="btn-submit">提交</button>
     </view>
      </form>
    </view>

In the above code, we use bindsubmit to bind the submission event of the form. After the user fills in the information, click the submit button to trigger the event.

  1. Background processing
    In the background PHP, we need to write the code to process the reservation request, save the information submitted by the user to the database, and send the template message to the user. An example is as follows:

    <?php
    // save appointment
    $openid = $_SESSION['openid'];
    $name = $_POST['name'];
    $phone = $_POST['phone'];
    $date = $_POST['date'];
    $time = $_POST['time'];
    
    $db->query("INSERT INTO appointment (openid, name, phone, date, time) VALUES ('$openid', '$name', '$phone', '$date', '$time')");
    
    // send template message
    $app = $app['wechat'];
    
    $result = $app->template_message->send([
     'touser' => $openid,
     'template_id' => 'your-template-id',
     'url' => 'your-url',
     'data' => [
         'first' => '您已成功预约!',
         'keyword1' => $name,
         'keyword2' => $date . ' ' . $time,
         'remark' => '请准时到达!',
     ],
    ]);
    
    if ($result['errcode']) {
     // handle error
     echo $result['errmsg'];
    }
    

    In the above code, we first get the user's openid from the session and insert the information submitted by the user into the database. Then, use the template message function provided by EasyWeChat to send the user a template message indicating that the reservation is successful.

4. Implement the queuing function

For the queuing function, we can use the auto-incrementing ID in the database for counting. When a user queues, a queuing number is generated for the user based on the current number of people queuing, and the queuing number and related information are saved in the database. Users can query their queue number and current queue number at any time, and obtain the latest queue status through polling.

  1. Database table design
    Create a database table named queue to store user queuing information. The table structure reference is as follows:

    CREATE TABLE `queue` (
      `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
      `openid` varchar(100) NOT NULL,
      `name` varchar(50) NOT NULL,
      `phone` varchar(20) NOT NULL,
      `queue_no` int(11) unsigned NOT NULL,
      `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
      PRIMARY KEY (`id`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
  2. Query the current number of people in queue
    In the background PHP, we need to write code to query the current number of people in queue. The example is as follows:

    <?php
    // query queue number
    $count = $db->query("SELECT COUNT(*) FROM queue")->fetchColumn();
    
    echo $count;

    In the above example code, we use SELECT COUNT(*) to query the current number of people in queue and return it to the front end.

  3. User queue
    In the mini program, users can click the queue button to queue and submit relevant information to the background for processing. An example is as follows:

    // index.js
    // enqueue
    function enqueue() {
      wx.request({
     url: 'your-api-url',
     method: 'POST',
     data: {
       openid: getApp().globalData.openid,
       name: this.data.name,
       phone: this.data.phone
     },
     success: function(res) {
       wx.showToast({
         title: '排队成功',
         duration: 1500
       })
     }
      })
    }

    In the above example code, we use wx.request to initiate a background request and submit the user's openid, name and mobile phone number to the background for queuing processing.

  4. Query queue number
    Users can check their queue number and the current number of people in queue at any time. In the mini program, we can use setInterval to perform polling queries and update the page display. The example is as follows:

    // index.js
    // get queue number
    function getQueueNumber() {
      var intervalId = setInterval(function() {
     wx.request({
       url: 'your-api-url',
       method: 'GET',
       success: function(res) {
         var queueNo = res.data.queue_no;
         var count = res.data.count;
    
         if (queueNo > 0) {
           clearInterval(intervalId);
           wx.showModal({
             title: '排队成功',
             content: '当前排队人数:' + count + '
    您的排队号:' + queueNo
           })
         }
       }
     })
      }, 2000);
    }

    In the above example code, we use wx.request to poll and query the user's queuing information. If the queuing number is greater than 0, it means the queuing is successful and the current The number of people in the queue and the user’s queue number.

Summary:
Through the above steps, we can build a simple WeChat applet with reservation and queuing functions through EasyWeChat and PHP. Users can make online reservations through the mini program and check their queuing status in real time, providing users with more convenient reservation and queuing services. Hope this article is helpful to you!

The above is the detailed content of Teach you to use EasyWeChat and PHP to build the reservation and queuing functions of the WeChat applet. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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