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

WeChat applet realizes interaction with background PHP

小云云
Release: 2018-03-29 11:39:54
Original
39530 people have browsed it

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!

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