I believe that you code farmers have to call the API provided by major resource websites experience, but there are many such and such problems in access, recently in the industry to do a high-profile micro channel small program project, using the API access of multiple websites, Next I will “Douban film” small program demo to share with you my experience in the use of learning website API, this article is my personal point of view, if there is any improper, please criticize and correct.
1. [wechat Web developer tools] : mainly used for knocking web code, but mainly used for web effect preview. Here I use wechat Web developer tool 0.19.191900, now the latest version is 0.20.191900, the function is basically the same, there is no major change, but it is recommended to use the latest version, more powerful functions, more convenient operation. 2. [Atom editor] : It is mainly used for layout and typesetting, and is also the main battlefield of code knocking. I really think this editor is good. 4. [Iconfont- Alibaba Vector Icon library] : provides all ICONS in the project, rich in resources. 5. [WildDog real-time communication cloud] : Provide data storage and communication functions in the project, and realize wechat login. 6. [Douban Developer Platform] : Application interface and development specification specification document of Douban Film
Iii. Display of directory structure
├ ─ ─ app. Js ├ ─ ─ app. Json ├ ─ ─ app. WXSS ├ ─ ─ pages │ ├ ─ ─ welcome │ ├ ─ ─ mime │ ├ ─ ─ comingSoon │ └ ─ ─ top250 │ ├ ─ ─ the detail │ ├ ─ ─ ├─ search │ ├─ video │ ├─ ├─ download-exercises │ ├─ download-exercises │ ├─ download-exercises │ ├─ download-exercisesCopy the code
"Pages" : [" pages/welcome/welcome / / movie home page "pages/mine/mine", / / my information page "pages/comingSoon/comingSoon", / / released recently "pages/inTheaters/inTheaters" list page, / / popular movie "pages/top250 / top250" list page, / / top250 movie list page "pages/detail/detail", // search page "pages/search/list", // Search page "pages/video/video" // search page"Copy the code
4. Effect preview
Github address: github.com/webstormshi…
Note: all data is due to the project by offering API request douban official remote access, WeChat authorization login is through a third party platform to realize the dragons, so the load may be a bit slow, video playback function owing to address cannot obtain the movie video resources, so the movie play page USES a fixed address access video resources.
V. List of project implementation functions
Movie home View Column List View movie details View Movie Search View movie Play Pause Bullet screen login exitCopy the code
Vi. Analysis of project difficulties
1. Dingo platform API to achieve wechat login configuration
The wilddog.App object is the core of the Wilddog Web SDK. It maintains the global context data of the application, and different modules need to interact with each other through it. The App instance is also our entry point to dingo's various functional modules, so initializing the App instance is a prerequisite for using any other API. To use wilddog authentication, you must include the authDomain in your initialization parameters as follows: var config = {authDomain: "<appId>.wilddog.com"}; wilddog.initializeApp(config); Var wilddog = wilddog.initializeapp (config); Var configA = {authDomain: "<appId-a>.wilddog.com"}; var a = wilddog.initializeApp(configA, "APP_A"); // A.auth ().signinxxx ().then(...) ** Definition ** auth() ** indicates that ** gets wilddog. auth instances. Wilddog. auth instances can only be obtained using this method. Return value * * * * [wilddog Auth] (https://docs.wilddog.com/auth/Web/api/Auth.html) define the sync () * * * * * * that * * get wilddog in sync instance, Wilddog.sync instances can only be obtained in this way. Return value * * * * [wilddog Sync] (https://docs.wilddog.com/sync/Web/api/App.html)Copy the code
Novice due to the directory structure for WeChat applet and WeChat provide apis are not familiar with, may not know how to implement WeChat authorization login, here for the sake of easy to operate, I used the wilddog provided interfaces, let the third party agent to achieve WeChat login (for details see development documentation) operation, and in the project by the following: Copy wilddog-eapp-all. js to the root directory and perform the following configurations in the JS file:
App({ onLaunch: function () { var config = { syncURL : "https://sywx.wilddogio.com", } wilddog.initializeapp (config) this.ref = wilddog.sync().ref('todo') }, login:function(callback){ console.log(callback); wilddog.auth().signInWeapp().then(function(user){ callback(user); Wx. ShowToast ({title: 'login successfully,})}). The catch (function (err) {wx. ShowToast ({title:' login failed,})})},Copy the code
First of all, we should carefully read the API documentation of Douban Developer platform, because each website provides different interface specifications, so we need to understand the routines they use. My brain is not very good, and IT took me a whole day to understand the documentation. However, when obtaining API links, it should be noted that not all interfaces are open, and some data cannot be obtained. I tried several before I found one that works, so before choosing one, I should test whether the following interfaces are available in advance. Finally, the steps of calling the API in wechat applet can be seen in the code in the following project:
GlobalData :{userInfo:null, doubanBase:"https://api.douban.com", // inTheaters:"/v2/movie/ coming_soon", Detail :"/v2/movie/subject/", // movie search:"/v2/movie/search" // movie searchCopy the code
/ / stitching request movie list URL and call the get method onLoad: function (options) {var comingSoonURL = app. GlobalData. DoubanBase + app.globalData.comingSoon+ "?start=0&count=10"; // console.log(comingSoonURL); / / page to initialize the options for the page jump parameters from enclosing getComingSoonListData (comingSoonURL, 'comingSoon', 'released recently'); }Copy the code
Get the recently released film list / / coexist on the data of getComingSoonListData: function (url, settedKey, categoryTitle) {wx. ShowToast ({title: "load", icon:'loading', duration:10000 }); var that = this; wx.request({ url:url, method:'GET', header:{ "Content-Type":"json", }, success:function(res){ that.setData({ comingSoon:res.data.subjects, }) } }); }Copy the code
3. Wechat applet API realizes video playback The video component video (video) of wechat applet can load and play video media information and customize some related properties of the video component. The following shows some related properties of the video component:
Video Component Properties Part List Attribute Type Default Value Description SRC String Address of the resource to play the video duration Number Specifies the video duration controls Boolean true Danmu-list Object Array DanMU-bTN Boolean False Indicates whether to display barrage buttons. This parameter is valid only during initialization. Autoplay Boolean false whether to reduce autoplay loop Boolean false whether to reduce circular play Boolean false whether to reduce muted playCopy the code
// WXML file <! --pages/video/video.wxml--> <view class="section tc"> <video id="myVideo" src="http://wxsnsdy.tc.qq.com/105/20210/snsdyvideodownload?filekey=30280201010421301f0201690402534804102ca905ce620b1241b 726bc41dcff44e00204012882540400&bizid=1023&hy=SH&fileparam=302c020101042530230204136ffd93020457e3c4ff02024ef202031e8d7f0 2030f42400204045a320a0201000400" enable-danmu danmu-btn controls></video> <view class="btn-area"> <input <button bindtap="bindStop" </button> <button bindtap="bindStop" </button> </button> <button bindTap ="bindplay" type="primary" hidden="{{! </button> </view> </view>Copy the code
// pages/video/video.js Page({data: {hiddenVideo:false}, inputValue: '', bindInputBlur: function (e) { wx.login({ success: function(res) {}, fail: function(res) {}, complete: function(res) {}, }) this.inputValue = e.detail.value }, bindSendDanmu: function () { this.videoContext.sendDanmu({ text: this.inputValue, color: getRandomColor() }) }, bindStop:function() { this.videoContext.pause(); this.setData({ hiddenVideo: true }); }, bindplay:function(){ this.videoContext.play(); this.setData({ hiddenVideo: false }); }, onReady: Function () {this.videoContext = wx.createVideoContext('myVideo')}} [] for (let i = 0; i < 3; ++i) { let color = Math.floor(Math.random() * 256).toString(16) color = color.length == 1 ? '0' + color : color rgb.push(color) } return '#' + rgb.join('') }Copy the code
4. Wechat applets call dingo API login
DoLogin: function () {var that = this; Wx. showModal({title: 'login ', content:' Whether tO allow wechat authorized login ', success: function (res) { if (res.confirm) { app.login(function (user) { console.log(user); That.setdata ({userText: user, status: 'exit ', displayInfo: 'block', hiddenInfo:' None '})})}})}Copy the code
DoLogout :function(){var that = this; Wx. showActionSheet({itemList: [' exit ', 're-log '], Success: function (res) {if (! Res.cancel) {that.setData({userText: '', status: 'login ', displayInfo:' None ', hiddenInfo: 'block'})}}})}Copy the code
Seven, API application heart process
In fact, the key to accessing the data resources of the website through API is to accurately splicing out the URL link according to business requirements, and then calling the access method to store the data in data. Therefore, we need to be very careful and pay attention to details when splicing urls. Standardize the form of URL links according to the requirements of the document. Here is an example from a project:
GlobalData :{userInfo:null, doubanBase:"https://api.douban.com", inTheaters:"/v2/movie/in_theaters", comingSoon:"/v2/movie/coming_soon", top250:"/v2/movie/top250", detail:"/v2/movie/subject/", search:"/v2/movie/search" }Copy the code
// Top250 movie list data request URL // "? Start =0&count=10" Take 10 data onLoad: function (options) {/ / page to initialize the options for the page jump parameters from var top250URL = app. GlobalData. DoubanBase + app.globalData.top250 + "? start=0&count=10"; console.log(top250URL ); }Copy the code
When data access is carried out, there will be some parameters. When using the link with parameters, we should pay special attention to the starting position of the page jump, the parameters are transferred from one page to another, the format of the parameters is required, and the parameters are generally received in the onLoad method of JS. You can receive a list of parameters as an assignment. After the method is called, there is usually a return value. Before using the returned data, it is necessary to first clarify the type and structure of the returned data. The returned value types generally include number, Boolean, Object, Array and so on.
Domain: https://api.douban.com/ Resources URI: /v2/movie/search? Q ={text} Example: GET /v2/movie/search? Q = GET /v2/movie/search? Tag = comedyCopy the code
// Search movie list by keyword request URL // InputTap:function(e){var keyword = e.daile.value; var searchURL = app.globalData.doubanBase + app.globalData.search + "? q=" + keyword; console.log(searchURL); }Copy the code
3. Make it clear that concepts such as this, options, and that play a similar role in the jS file of wechat applets as in javascript, both referring to the current object, but the current object in wechat applets refers to the current application, and the method of obtaining the page in Pages is as follows:
var app = getApp(); / gets the current application, which can then be called thisCopy the code
Options in the js file
<! --pages/comingSoon/comingSoon.wxml--> <block wx:for="{{comingSoon}}" wx:key=""> <view class="scroll-view-item" > <navigator URL ="/pages/detail/detail? id={{item.id}}"> <image class="movie-img" src="{{item.images.large}}"/> <view class="movie-name">{{item.title}}</view> <view class="movie-grade"> <view id="{{item.rating.average}}" class="commentStar" style="background-position-y:(10-{{item.rating.average}})*11px"></view> <view id="movie-grade-value">{{item.rating.average}}</view></view> </navigator> </view> </block>Copy the code
Options is an array of parameters passed in from another page to the page link.
OnLoad :function(options){var that = this; onLoad:function(options){var that = this; // Copy this object to the temporary variable that console.log(options); / / print out the optios object, parameter list var detailURL = app. GlobalData. DoubanBase + app. GlobalData. Detail + options. The id; console.log(detailURL); },Copy the code
The above code uses that, mainly because this can change at any time with the execution context. In order to find the object of the original page, the original variable is copied and saved at the beginning, which effectively solves the problem of data loss.
Wechat developer tool can not only preview the current page effect, but also equipped with a console, which can output results. When accessing data using API, we can view the property structure of the object by using console.log() output object or debug breakpoints in this way. Here is a demonstration of the view structure operation of the console in my project:
Page({ data:{}, inTheaters: [], onLoad:function(options){ var inTheatersURL = app.globalData.doubanBase + app.globalData.inTheaters + "? start=0&count=10"; console.log(inTheatersURL); This.getmovielistdata (inTheatersURL, 'inTheaters', 'theaters '); }, getMovieListData: function (url, settedKey, categoryTitle) { var that = this; wx.request({ url: url, method: 'GET', header: { "Content-Type": "json", }, success: function (res) { console.log(res.data); SetData ({inTheaters: res.data. Subjects})}}); }Copy the code
Console output:
https://api.douban.com/v2/movie/in_theaters?start=0&count=10 Object {count: 10, start: 0, total: 32, subjects: Array[10], subjects: Array[10]0: Objectalt: "https://movie.douban.com/subject/26363254/"casts: Array[3]collect_count: 19015directors: Array[1]genres: Array[1]id: "Images: Objectoriginal_title:" Wolverine "rating: Objectsubtype: "Movie "title:" Wolverine "year: "2017"__proto__: Object1: Object2: Object3: Object4: Object5: Object6: Object7: Object8: Object9: Objectlength: 10__proto__: Array[0]title: "Films on Show - Beijing" Total: 32__proto__: ObjectCopy the code
Screenshot of a single object:
image.png
<! --pages/inTheaters/inTheaters.wxml--> <block wx:for="{{inTheaters}}" wx:key=""> <navigator url="/pages/detail/detail? id={{item.id}}"> <view class="movie-list"> <view class="movie-list-info" index="{{index}}"> <! <image class="movieimg" SRC ="{{item.images.large}}" /> <view class="item-box"> <view class="userinfo"> <! - the movie title - > < text class = "movie - the title" > {{item. The title}} < / text > <! - year of film - > < text class = "time" > {{item. Year}} < / text > < / view > <! - film score - > < the view class = "posts - the title" > < text > score: {{item. Rating. Business}} < / text > < / view > <! - film director - > < the view class = "bar - info - item - number" > director: {{item. Directors [0] [' name ']}} < / view > <! <view class="bar-info-item-number"> {{item.casts[0].name}}{{item.casts[1].name}}</view> </view> </view> </view> </navigator> </block>Copy the code
5. Effective debugging code In the process of development, the program bugs is a normal thing, so a quick fix bugs is also the ability to reflect, here I am in the process of development, meet bug solution step is commonly, in the first place in the console view the error message, if it best at a glance, but if you don’t understand the meaning, You can copy and paste the error message into Baidu to see how to fix it, or if not, you can debug it using console.log() as described earlier. Generally after doing a lot of things, as long as you read the wrong newspaper, you can know where the problem is, so it is a good choice to do more practice.
Eight, the total knot
The above wechat small program Demo aims to achieve some basic functions, but there are also some unreasonable points. For example, colleagues who have questions or different opinions about the project can contact me (email: [email protected]; QQ: 1761775849). Learning is a process of continuous summary, I hope some of my learning experience is helpful to you, but the above is my own personal opinion, if there is inappropriate, welcome to comment area criticism and correction, learning is a process of continuous correction.