Home WeChat Applet Mini Program Development WeChat applet realizes interaction with background PHP

WeChat applet realizes interaction with background PHP

Mar 29, 2018 am 11:39 AM
php interaction Applets

Next, I will talk about how the backend interacts with the frontend for data and pictures. I believe this point is of concern to many people, because at that time I was responsible for backend development in the team, so I didn’t know much about the frontend. Here I will Post some screenshots of the code during front-end development. The official API introduction address of the WeChat applet is:

https://mp.weixin.qq.com/debug/wxadoc/dev/api/api -network.html

The data communication between WeChat and the backend server is achieved by calling wx.request(OBJECT). This is explained in the official api interface,

For example, when the front desk sends data to the background, it needs to link to the specific php file under the server php action path and encapsulate the json format data in key-value form. Please see the following code:

url is the domain name of the server and the location of isbn.php on the server. This location is a relative location. In the image I purchased in the previous article, the default php file path is:

/yjdata/www/ , this means that the php placed directly in this folder only needs to be directly /+*.php after the domain name. If a folder is created in this directory for convenient management Then just enter /folder name/*.php after the domain name.

In addition, the data transmitted from the front end to the background is encapsulated in json format. The data written in the data in the picture has the key in the front and the specific information in the back. The value value is obtained based on the previous key value when obtained by the background. In addition, the method determines how the background and the front desk communicate. The GET method is used here. The background and front desk methods must be used in pairs. One cannot be GET and the other One end is POST. When doing the WeChat payment function, some data with high security and privacy must be interacted with through POST.

The result transmitted from the front end to the backend here is the ISBN code of the book, because the small program we made has a function that calls the camera to scan the barcode on the back of the book to obtain the ISBN code. , the front end sends the ISBN code to the backend, and the backend program will call the third-party Douban book interface to query book information based on the ISBN code, and return the book information to the frontend. Here I post the server-side code for your reference:

<?php$result=$_GET["result"];/*获取前端微信小程序扫书的isbn结果*/
Copy after login
/*与第三方接口通信获取书本信息*/
Copy after login
$book_info=file_get_contents("https://api.douban.com/v2/book/isbn/:".$result);$jsondecode = json_decode($book_info,true);/*将获取到的书本信息JSON解码*/$title=$jsondecode["title"];/*将解码后书名赋值给title变量*/$author=$jsondecode["author"];/*将解码后作者赋值给author变量*/$publisher=$jsondecode["publisher"];/*将解码后出版社名赋值给publisher变量*/echo "title=".$title; /*向前端返回书名*/echo "author=".$author; /*向前端返回作者名*/echo "publisher=".$publisher; /*向前端返回出版社名*/?>
Copy after login

The specific comments are written in detail. To return data to the front desk, you can directly use echo. Generally, development requires dealing with the database. , therefore, the background program needs to operate the database based on the data transmitted from the front desk. This part actually accepts the data from the front desk and performs the corresponding database operations. This part will be included as long as it talks about PHP database operations. I will not cover it here. No more elaboration.

In addition, for a WeChat applet, pictures are essential, and picture resources are stored in the server, so how to store pictures is a key. Next, we will explain the specific process of inserting book information into the database. . . (In fact, the comments are very detailed)

<?phpheader(&#39;content-type:application/json;charset=utf8&#39;);$mysql_server_name="localhost";/*数据库服务器名称*/$mysql_username="root";/*数据库用户名*/$mysql_password="123456";/*数据库用户密码*/$mysql_databasename="zhishu";/*进入数据库后数据库名*/$conn=mysqli_connect($mysql_server_name,$mysql_username,$mysql_password,$mysql_databasename);/*数据库连接语句*/;;$bookname=$_POST["bookname"];/*从小程序前端获取书本名字*/$authorname=$_POST["authorname"];/*从小程序前端获取书本作者名字*/$bookintroduce=$_POST["introduce"];/*从小程序前端获取书本介绍信息*/$bookholder_name=$_POST["openid"];/*从小程序前端获取书本持有人昵称*/$bookclass=$_POST[&#39;classification&#39;];;/*从小程序前端获取书本分类*/date_default_timezone_set(&#39;PRC&#39;); /*设置默认时区为中国*/$time=(string)date("Y-m-d-h-i",time());/*获取时间*/function Unioname($a) /*将时间格式更改的函数*/{
    $a=explode(&#39;-&#39;,$a);
    $a=implode(&#39;&#39;,$a);
    return $a;
}$time=Unioname($time);$allowedExts = array("gif", "jpeg", "jpg", "png"); /*这里的内容同用户注册时代码含义一样,只不过那时是为了存用户头像并修改用户头像名字,这里是存书本图像并修改书本图像的名字*/$temp = explode(".", $_FILES["file"]["name"]);//将图片名字以.分割成两个字符串$extension = end($temp);     // 获取图片后缀名if ((($_FILES["file"]["type"] == "image/gif")
        || ($_FILES["file"]["type"] == "image/jpeg")
        || ($_FILES["file"]["type"] == "image/jpg")
        || ($_FILES["file"]["type"] == "image/pjpeg")
        || ($_FILES["file"]["type"] == "image/x-png")
        || ($_FILES["file"]["type"] == "image/png"))
    && ($_FILES["file"]["size"] < 1024000)   // 小于 1MB
    && in_array($extension, $allowedExts))
{
    if ($_FILES["file"]["error"] > 0) {
        echo "错误:: " . $_FILES["file"]["error"] . "<br>";
    } else {
        // 判断当期目录下的 upload 目录是否存在该文件        // 如果没有 upload 目录,你需要创建它,upload 目录权限为 777
        if (file_exists("bookimage/" . $_FILES["file"]["name"])) {
            echo $_FILES["file"]["name"] . " 文件已经存在。 ";
        } else {
            // 如果 upload 目录不存在该文件则将文件上传到 upload 目录下            move_uploaded_file($_FILES["file"]["tmp_name"], "bookimage/".$_FILES["file"]["name"]);
            $oldname = "bookimage/" . $_FILES["file"]["name"];
            $newname = "bookimage/" . $time .$bookholder_name.".".$extension;
            rename($oldname, $newname);
            $sql_num="select * from book";
            $reasult=mysqli_query($conn,$sql_num);
            $reasult_num=mysqli_num_rows($reasult); /*将获取到书本信息插入数据库语句*/            $sql_insert="insert into book (book_id,bookname,authorname,book_intro,bookclass,bookholder_openid,bookpicture_path,is_CunZai,ChengJiao_num) VALUES ($reasult_num+1,'$bookname','$authorname','$bookintroduce','$bookclass','$bookholder_openid','$newname','1',0)";
Copy after login
            if( mysqli_query($conn,$sql_insert))
            {
                echo "插入书籍成功!";
            }
            else
            {
                echo "插入失败";
            }
        }
    }
}mysqli_close($conn); /*关闭数据库连接*/?>
Copy after login

First use the $[FILE] global array to accept files, which has several The attributes are as follows:

$_FILES["file"]["name"] - the name of the uploaded file

$_FILES["file "]["type"] - The type of the uploaded file

$_FILES["file"]["size"] - The size of the uploaded file, in bytes
$_FILES["file"]["tmp_name"] - The name of the temporary copy of the file stored on the server
$_FILES["file"]["error"] - The error code caused by the file upload
This is a very simple way to send and receive files. After receiving the file name, split it with "." in order to obtain the suffix. Next, you need to judge the suffix to see if it is a commonly used image suffix format. If Yes and the image size is less than 1MB, proceed to the next operation. At this time, the image is in the cache area, so the image must be renamed and stored in the book image folder. This part is implemented in the code. In addition, the image needs to be The path is stored in the database together with other information about the book. At this point, I have talked about most of the interactions between the basic mini program and the backend, and you can basically complete a simple mini program.

Related recommendations:

WeChat applet PHP background implementation method

The above is the detailed content of WeChat applet realizes interaction with background PHP. 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)

Hot Topics

Java Tutorial
1653
14
PHP Tutorial
1251
29
C# Tutorial
1224
24
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

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

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.

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

PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

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.

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.

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

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

See all articles