Home Backend Development PHP Tutorial 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

Jul 18, 2023 am 09:45 AM
php Appointment function easywechat

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
    Copy after login
  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);
         };
     }
    }
    Copy after login

    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());
    Copy after login

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;
    Copy after login
  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>
    Copy after login

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'];
    }
    
    Copy after login

    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;
    Copy after login
  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;
    Copy after login

    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
       })
     }
      })
    }
    Copy after login

    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);
    }
    Copy after login

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

7 PHP Functions I Regret I Didn't Know Before 7 PHP Functions I Regret I Didn't Know Before Nov 13, 2024 am 09:42 AM

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

See all articles