Declaration: oneself also is a rookie, write of bad place, big men give directions.

Welcome to my blog

Wechat small program mall, continue to update. (Has changed jobs, but still small program related projects/squint)

First talk about the origin of writing small program, I know before the big guy wrote a relatively simple small program, I changed the style and then successfully have my first small program. Then WHEN I was looking for a job, I wrote such a thing on my resume. As a result, the leader said to me earnestly and earnestly that the company’s small program mall will teach you. The key point is that no one in the company knows wechat small program. WTF, didn’t they hire me to write VUE?

So I began to write from scratch micro channel small program mall road.

Micro channel small program of official documents WHAT I will not say, it is sure to see. Tell me about the problem I’ve been having since I started writing about it. I hope to write a small program you can have a little help, because I am also very vegetables.

1, wechat small program RPX

In the official document of wechat, we can see the following sentence:

On the iPhone 6, the screen width is 375px and there are 750 physical pixels, so 750rpx = 375px = 750 physical pixels and 1rpx = 0.5px = 1 physical pixel. Designers can use the iPhone 6 as a visual standard when developing wechat miniprograms. In other words, when designing small programs, designers can do the following:

  • Use the screen size of iPhone 6 (375×667) as the visual size, 1 px = 0.5rpx;
  • Take the standard of 1 px = 1 RPX and set the size of the design draft as 750×1334.

In fact, generally speaking, you say with UI little sister, and then you can be very cool to write the style.

2. Container view of wechat applets

  • A view is just a div, that’s how it works.
  • Scroll-view Indicates the area of the scrollable view. One thing to note about this is the view area that scrolls horizontally. The important thing is that these two inline styles, and other official documentation is quite clear.







3. UI framework of wechat applets

This, very interesting, when I finished writing a TAB I feel very spiritual, before the brothers told me wechat small program has a frame you look to go…


{{item.name}}


No BB, directly on the address github.com/Tencent/weu…


First, I wrote this at the risk of being killed at the same time during my lunch break on Saturday. Please bear with me if there is anything wrong with my writing. I will also share my problems.

Recently I saw a good micro channel small program UI or the old rules directly on the address:

youzan/zanui-weapp

4, wechat small program switchTab

You can use the navigator on the official website. Today, I would like to share the page jump problem I encountered in the small program. What I wrote is a small program of e-commerce mall. After jumping to the details page, there are two ICONS as shown in the figure:

You must be smart enough to guess where these ICONS jump to, and it must be Bindtap, and then wx.navigator will do it. Two simple page jumps, and I was stuck with these two problems for more than an hour. Later, I asked the big guys in the wechat group to solve the problem, because I did not read the document carefully, the two pages jumped are the path of the official bottom TAB of wechat as shown in the figure:

The problem is that in the official Tabbar you use these paths:

Then the solution is:

handleGoIndex: function() {

wx.switchTab({

url: ‘/pages/index/index’

})

},

handleGoCart: function() {

wx.switchTab({

url: ‘/pages/cart/index’

})

}

5. Wechat applet forbids page pull-down

Sometimes you’ll run into pages that don’t pull down, if you think I’m talking about a pull-down refresh API. The one that doesn’t let you slide out. Go directly to the code:

<view catchtouchmove=”stopDrag” class=”container”>

stopDrag(){

return false;

},

But this careful use, I also want to here if there is a god can point out the best, this effect is the visible area of the entire static slide… Spell more small program home page is not the pull-down white bar, but can slide to see the commodity information, ask for advice ~

Latest solution in app. Add this property to json to disable scrolling.

6. Page depth of wechat applets

When I was testing my own project, I found that the logic was fine and the grammar was fine. Suddenly remembered the page stack of the small program is five, so special in the number of two of their own page jump ha ha… Only then did I realize that my understanding was wrong. I did not carefully read the document at the beginning. I thought that more than five pages would be added to the page stack, and the first one opened would be destroyed. I used wX. redirectTo to solve this problem. But who let me learn, so found a god written a particularly perfect understanding of the small program page jump principle.

(Depth is now 10 layers, but there are still some bugs in ios 10, and there are still scenarios like page depth to consider.)

Still hey hey: small program foundation page routing – wechat small program club www.wxappclub.com.

7, wechat small program on the pull and load

The project of my current company is a small program for e-commerce. Drop-down refresh is clearly written on the official website. It cannot be used with Scroll View at the same time. I’m using both onReachBottom and scroll view bindscrolltolower in the case of brain watts. After my practice, I recommend onReachBottom. If some tabs also have pull-down refresh, this is convenient to go directly to the code:

onReachBottom() {
        let isPush = this.data.index,
            val = this.data.inputVal;
        this.setData({
            isBtnShow: true
        });
        if (isPush ==1) {
            let num = this.data.limitIndex;
            this.setData({
                limitIndex: num+1}) // Performance optimization for pull-up loadingsetTimeout(()=>{// Number of times to pass a drop-down refresh to the back end +1 const data = {limitIndex: this.data.limitIndex
                    };
                    utils.sendRequest(api.AllGoodsUrl, data, this.handleReachBottom.bind(this));
            },1500)
        };
        if(val ! =' ') {
            setTimeout(()=>{
                let num = this.data.limitIndex;
                    this.setData({
                        limitIndex: num+1}) const data = {Index: num+1})limitIndex: this.data.limitIndex, data:{ name: this.data.inputVal, } }; utils.sendRequest(api.AllGoodsUrl, data, this.handleLoadMore.bind(this)); }}, 1500); }, this code is mainly to judge the TAB state to delay the request interface. The realization effect is shown as follows:Copy the code

This is my practice with pull-up loading in the hope that someone will come up with a better suggestion.

8. Data interaction of wechat applets

At this point, I would like to share some of my experiences about data interaction

function sendRequest(path, data, callback) {
    wx.request({
        url: path, 
        data: data,
        header: {
            'content-type': 'application/json'
        },
        method: "POST", success: callback, fail:(res)=>{console.log(res)}})function promiseRequest(url, data = {}) {
  return new Promise(function (resolve, reject) {
    wx.request({
      url: url,
      data: data,
      method: 'POST',
      header: {
        'Content-Type': 'application/json',
      },
      success:(res) => {
        if (res.statusCode == 200) {
            resolve(res);
        } else {
          reject(res.errMsg);
        }

      },
      fail: (err) => {
        reject(err)
        console.log("failed")}})}); PromiseRequest (api.bannerurl). Then (res => {if(res.data.error == 0){//dosomething... }else {
          utils.showModal(res.data.err_msg)
      }
  });
Copy the code

Expose the interface to be invoked on other pages

Hope someone can help with the componentization best practices of small programs ~

9, wechat applets Android request failure pit

The situation I encountered at that time was that there was no problem in the simulator and IOS environment to request data. When testing the Android environment, I found the request failed as shown below

This mistake also caused me to quarrel with the big brother of operation and maintenance for a long time haha, first of all, this mistake, brother, the pot can be completely transferred to the big brother of operation and maintenance, leaving no room. Then you can help brother to provide some information, step by step investigation, first check your project binding domain name:

1. HTTPS certificate problem: SSL certificate configuration requires pem, not CRT.

2. Server version information: the TLS version problem has been mentioned in the official document of wechat mini program. The server TLS version must support 1.2 (enable 1.2, disable 1.1, 1.0 and other earlier versions).

3. Some people say that the first two methods can be solved after consulting the data, but for our company, after checking the first two items, operation and maintenance brother used Nginx to forward them, and solved the problem of Android request failure. I hope I can help you

10. Address page three-level linkage of wechat applets

Say this question, now post an address to everybody, thank god open source very much: blog.csdn.net/sinat_17775…

So once you look at the code, you sort of figure out the back-end data that you’re dealing with and the address requirements and so forth, and the problem THAT I ran into was



The data sent to me by the back end contains the ID corresponding to each address, such as Beijing: 2, Beijing: 50, Dongcheng District: 500

While processing this data, I made some modifications to the original God code,

let val = e.detail.value,
            t = this.data.values,
            cityData = this.data.cityData,
            index = this.data.id,
            list = this.data.addrList;
            list[index].area = true;
            try {
                if(val[0] ! Const citys = []; const citys = []; const countys = []; cityData[val[0]].child.map(item => citys.push({name:item.name,id:item.id})); cityData[val[0]].child[0].child.map(item => countys.push({name:item.name,id:item.id})); list[index].provinceName = this.data.provinces[val[0]].name; CityName = cityData[val[0]].child[0].name; // List [index].districtName = cityData[val[0]].child[0].child[0].name; / / region list [index] province = this. Data. The provinces [val [0]]. Id; ID list[index]. City = cityData[val[0]].child[0].id; ID list[index]. District = cityData[val[0]].child[0].child[0].id; SetData ({citys: citys, countys: countys, values: val, value: [val[0], 0, 0], addrList: list})return;
                }
                if(val[1] ! Const countys = []; const countys = []; cityData[val[0]].child[val[1]].child.map(item => countys.push({name:item.name,id:item.id})); list[index].cityName = this.data.citys[val[1]].name; List [index]. City = this.data.citys[val[1]].id; DistrictName = cityData[val[0]].child[val[1]].child[0].name; List [index]. District = cityData[val[0]].child[val[1]].child[0].id; SetData ({countys: countys, values: val, value: [val[0], val[1], 0], addrList: list})return;
                }
                if(val[2] ! List [index].districtname = this.data.countys[val[2]].districtname; List [index]. District = this.data.countys[val[2]].id; SetData ({county: this.data.countys[val[2]]. Name, values: val, addrList: list})return; } } catch(e) { // statements console.log(e); } list does have the consignee, the phone number, and so on, but I'm only handling the change of address in the change array,Copy the code





The layout needs some modification



I posted so many pictures because I really don’t know how to say, tuning this page for two days. Can only provide a general direction, still have to step by step processing the data, Goodluck ~

11. Horizontal scrolling in the Android environment for wechat applets

<view class="tab bg">
          <scroll-view class="" scroll-x="true" style="width: 100%; white-space: nowrap; display: flex; overflow-x: auto;">
              <view style="display: inline-block" bindtap="switchIndex" class="tab-list {{index === 1 ? 'on':''}}"</view> <view wx:for="{{tab}}" wx:key="index" data-id="{{item.id}}" data-index="{{index}}"
                 style="display: inline-block" bindtap="switchTab" class="tab-list {{tabIndex === index? 'on':''}}"> {{item.nav_name}} </view> </scroll-view> </view> Ha, ha, haCopy the code

12. Playing problem of mp4 in Ios environment with wechat mini program

When you come across your MP4 format that works or doesn’t play, just take a look at your MP4 encoding format, which must be H264.

13, wechat mini program wechat pay pit

This because I am also the first time to write small procedures, the back end of the eldest brother, in the MALL of H5 what are achieved once, non said all kinds of no problem, only stick two figures to understand the first

All data in this API is returned to you by the back end, do not accept his blame lol.

There is to be sure to let the back end good look wechat payment documents, general company development mall are service providers version of the payment service, here is me and the back end brother of the way to shake the pan, he did not bind me to the small program APPID, and then all kinds of said can not be adjusted…

Go here and configure, and the front end just needs to call the API pass

14. Picture uploading of wechat mini program

I haven’t updated it for a long time. I’m swamped by the company’s business.

Same old rule. Just go to the code.

handleCancelPic() {
        letid = this.data.dbId; Wx. chooseImage({count: 3, // default 9 sizeType: ['compressed'], // You can specify whether the image is original or compressed. By default, both are availablesourceType: ['album'.'camera'], // You can specify whether the source is photo album or camera, and default to both success: Var tempFilePaths = res.tempfilepaths; res => {// Returns the list of local file paths for the selected photos. this.setData({ src: tempFilePaths }) upload(this,tempFilePaths,' '.' '); }})} and then a wrapped methodfunction upload(page, path,way,id) {
    console.log(path)
  wx.showToast({
    icon: "loading",
    title: "Uploading"
  });
  var test = [],
    that = this;
  for (var i = 0; i<path.length; i++) {
        wx.uploadFile({
          url: api.CancelImg,
          filePath: path[i],          
          name: 'file',
          header: { "Content-Type": "multipart/form-data" },
          success: res => {
            test.push(res);
            wx.setStorageSync('cancelImg'.test)
            console.log(test)
            if(res.statusCode ! = 200) { wx.showModal({ title:'tip',
                content: 'Upload failed',
                showCancel: false
              })
              return;
            }else {
                wx.showModal({
                    title: 'tip',
                    content: 'Upload successful',
                    showCancel: false
                }) 
            }
          },
          fail: function (e) {
            console.log(e);
            wx.showModal({
              title: 'tip',
              content: 'Upload failed',
              showCancel: false
            })
          },
          complete: function() { wx.hideToast(); / / hide the Toast}})} this is the method of multiple image upload, a single image upload, remove the cycle. Mainly because wechat official default is to upload a picture at a time, which is very painful. It's the only way...Copy the code

15. E-commerce shopping cart logic of wechat applets

Then to share a small program shopping cart all logic processing, this or to thank my old sister taught me, a developer to do things must be rigorous, no matter how ugly the UI design, the logic you must do.

The first thing we need to do is that when the user clicks on the third item, the all button is automatically selected, or after all, as long as one item is not selected, the all button has to change. Let me show you the code:

You need to define some data that you need to render each time the page onload is loaded

Data: {likeList: [], carts:[], // carts list hasList:false//totalPrice:0, //totalPrice, starting with 0 selectAllStatus:false, / / selection state, the default selection, goodsNums: 0, allclick: []} every product of a single selected logical processing selectList (e) {const index = e.c. with our fabrication: urrentTarget. Dataset. The index; // Get the shopping cart ID for each clickletcarts = this.data.carts, selected = carts[index].select, all = this.data.allclick; carts[index].select = ! selected; carts[index].select ==true ? all.push(index):all.splice(index,1);
all.length == carts.length ?
this.setData({
  selectAllStatus: true
}):this.setData({
  selectAllStatus: false}); this.getTotalPrice(); }, the above code, the first thing to do is to radio the page rendering effect. Judging part of the code is the primary step in handling the all-selection logic. I'm sure you'll notice here that I've defined an empty array for AllClick in data, and then the following logic:Copy the code

  • When the button is selected, take out the corner markers corresponding to the item and put them into the new ARR. Here, because I have done well the logic of settlement before, I just push data into the array casually, but in fact, it can be used as some more important data processing of the corresponding goods.
  • The unchecked button is removed from the data corresponding to the index of the item found in the new ARR
  • After completing the above two steps, judge the length of ARR and cart each time the button state changes.

This is my processing, can also cycle, there are many ways to achieve, just take out for no contact with small partners to do a reference ~

Data: {likeList: [], carts:[], // carts list hasList:false//totalPrice:0, //totalPrice, starting with 0 selectAllStatus:false, / / selection state, the default selection, goodsNums: 0, allclick: []} every product of a single selected logical processing selectList (e) {const index = e.c. with our fabrication: urrentTarget. Dataset. The index; // Get the shopping cart ID for each clickletcarts = this.data.carts, selected = carts[index].select, all = this.data.allclick; carts[index].select = ! selected; carts[index].select ==true ? all.push(index):all.splice(index,1);
all.length == carts.length ?
this.setData({
  selectAllStatus: true
}):this.setData({
  selectAllStatus: false}); this.getTotalPrice(); }, this code also handles the all-selected state first, and then the associative state.Copy the code

  • Change all item information buttons to false when select all is not checked and empty allClick array directly.
  • When all items are checked, change the button in all item information to true, clear first, then push again, and then assign.

After these steps of operation will solve all the logic in this area, feel useful partners, remember to comment, concern yo ~

16. Use Map objects for wechat applets

This is my master Liang told me about this matter, I am a small program, she is Android, the same project. We were close, and she taught me to use this Map object, which is actually a Java Map object. It’s really fun to use. Cut the crap and go straight to the code.

This has also been introduced as a Map object in the ES6 standard. To borrow a passage from ruan Da Shen’s book:

JavaScript objects are essentially collections of key-value pairs (Hash structures), but traditionally strings can only be used as keys. This puts a great limit on its use. const data = {}; const element = document.getElementById('myDiv');
data[element] = 'metadata';
data['[object HTMLDivElement]'] / /"metadata"The above code is intended to use a DOM node as the key of the data object, but since objects only accept strings as key names, element is automatically converted to a string. To solve this problem, ES6 provides Map data structures. It is a collection of key-value pairs similar to objects, but the range of "keys" is not limited to strings. Values of all types (including objects) can be used as keys. In other words, the Object structure provides string-value mapping, and the Map structure provides value-value mapping, which is a more complete Hash structure implementation. If you need key-value data structures, Map is better than Object.Copy the code

For those interested, go to ES6 to get started with Map Set

let localMap = new Map(),// define a global Map objecttypeCode = ' '; // Click handleClickTabs(e) {let id = e.target.dataset.index,
 code = e.target.dataset.id; 
typeCode = code; // Define code here and use this.setData({leftTab: id}) in the request callback;if (localMap! =null) {// Map objectlet list = localMap.get(typeCode); // Get the corresponding categorytypeThe code ofif(list! =null) {this.setData({tabSonList:list})}elseConst data = {goodsTypeCode: code}; utils.sendRequest(api.ClassifySon, data, this.handleGoodsSon.bind(this)); }}else{ const data = { goodsTypeCode: code }; utils.sendRequest(api.ClassifySon, data, this.handleGoodsSon.bind(this)); }}, // Sort the contents inside handleGoodsSon(res) {let list = res.data; localMap.set(type/ / save corresponding Code, a list)typeCode list this.setData({tabSonList:list})},Copy the code

This allows you to optimize the tabs and reassign them if the interface gets too much data. Although I added drama to myself, it was also my working attitude. I learned new things and optimized the project.

The global variable cache problem of applets

The emergence of the problem was because, in the input events, I didn’t find better ways to monitor the keyboard back, but also for a better user experience, so the resulting problem is a global variable, user exit the page after the assignment, global variables are WeChat cache, and then, after a user input, Failed to modify the mobile phone number. Procedure

let Btel = ' ',// Prevent users from modifying mobile phone numbers Byzm =' '; HandleTel (e) {this.setData({tel: e.dail.value})}, handleYzm(e) { this.setData({ Yzm:e.detail.value }) Byzm = e.detail.value;let psd = this.data.psd,
            yzm = this.data.Yzm;
        yzm == psd ? this.setData({isYzm:0}):' ';
    },
    handleGetYzm() {
        let reg = common.telReg,
            val = this.data.tel;    
        if(! reg.test(val)) { wx.showModal({ content:'Please enter the correct mobile phone number',
                showCancel:false,
                confirmColor:'#3cc51f'// The default value is#3cc51f
                success:res =>{
                    if(res.confirm){
                        this.setData({
                            tel:' '})}}})}else{// Use the mobile number of the global variable when sending the captcha Btel = val; This.setdata ({isReset:true,
                isNoClick: true}) const data ={tel:val; utils.sendRequest(api.YanZhengMa, data, this.handleGetYzmSucc.bind(this)); / / button timerlet time = setInterval(()=>{
            let phoneCode = this.data.time;
                phoneCode --
                this.setData({
                    time : phoneCode
                })
                if(phoneCode == 0){
                     clearInterval(time)
                     this.setData({
                        isReset : false,
                        isNoClick: false, time:60})}},1000)}}, // Then this step is to check whether the user has modified the mobile phone after the verification code interface and savehandleSave() {
        let name = this.data.name,
            telNum = this.data.tel,
            yzm = Byzm,
            status = this.data.isYzm,
            card = wx.getStorageSync('UserCard');
        let timestamp= new Date().getTime();
        if (yzm == ' ') {
            wx.showModal({
                content:'Please enter the verification code.',
                showCancel:false,
                confirmColor:'#3cc51f'
            })
            return false;
        }
        if(name! =' '&&telNum! =' ') {
            if(Btel ! = telNum) { utils.showModal('The mobile phone number has changed. Please obtain the verification code again. ');
            }else{ const data ={ distribution_id:card.distribution_id, post:{ user_name:name, user_tel:Btel, user_code:yzm }, user_id:card.user_id, password:yzm+timestamp }; utils.sendRequest(api.BindTel, data, this.handleSaveTel.bind(this)); }}else {
            utils.showModal('Please fill in the complete information.'); }}, // Then after the save is successful, the user clicks OK to clear the global variables. It can also clear the global variables during the hidden and unloaded life cycle. handleSaveTel(res) {if (res.data.error == 0) {
            let go = this.data.go,
                id = res.data.data.id,
                lv = res.data.data.level;
            wx.showModal({
                content:'Binding successful ~',
                showCancel:false,
                confirmColor:'#3cc51f'// The default value is#3cc51f
                success:res =>{
                    if(res.confirm){
                        Byzm = ' '; // Clear the applet global variable cacheif (go) {
                            wx.redirectTo({
                              url: '/pages/user/cash/cash'})}else {
                            if(id ! = 0) {let card = wx.getStorageSync('UserCard');
                                card.distribution_id = id;
                                card.distribution_level = lv;
                                wx.setStorageSync('UserCard',card);
                                wx.setStorageSync('seller'.true)
                            }
                            wx.switchTab({
                              url: '/pages/user/index'})}}}})return false
        }else{ utils.showModal(res.data.err_msg); }}Copy the code

Small program of wechat pay pit

The thing is, because of corporate ownership change, tax avoidance and all that stuff. For our company’s small program, we need to change the wechat payment. After the financial department gave us the application number and merchant number, we scheduled midnight to cut the environment. I remember it was a Thursday night, we started to cut the environment at 12 o ‘clock, and after the back-end code database was ready, we re-bound wechat Pay, thinking we were done. Friday can also be flexible all morning happy ~

Unexpectedly, I just submitted a test, which said wechat Payment could not be used, reminding us that we did not have authorization. WTF, it is not appropriate for you to prompt it like this. In accordance with the error of a check, I went to the small program community to see.

Can you believe it? The merchant number of wechat open platform and the public merchant number are two different things. Small program to support the public number of merchant number, but you in the open platform binding small program wechat pay, the official tip to you is binding success ~.

And then it’s 7:00 in the morning…

Blood lesson ah!!

Small program landing revision

https://juejin.cn/post/6844903614792597518

Hey hey, write finish stick an address to get ~

20, small program webview in ios can not access the pit

Some pages of ios applet display a blank screen, and the problem we found later is that the parameters carried in SRC of web-view contain Chinese characters. Ios does not allow Chinese characters in links, so we can only transcode Chinese characters. When extracting parameters of H5 page, we can decode them again

1 Chinese transcoding

encodeURI(url)1Copy the code

2 the decoding

decodeURI(url)Copy the code

A few more things about WebViews

  1. Each page can only have a
    ,
    will automatically spread the entire page, and cover other components, small program to webView monitoring state basically no, can only set SRC to set url.
  2. → Applet can only return the applet page through the interface provided by JSSDK 1.3.0, set parameters to pass values, conversely, applet to webView is the same, can only be SRC path with parameters;
  3. Web-view does not support the ability to pay, which means that it cannot invoke the direct payment window of the small program. It should support the set of h5 payment, but the JSAPI of wechat payment cannot be used in web-view, that is, it may be able to pay by the relevant payment center of H5.
  4. In terms of hierarchies, you can go from webView to webView indefinitely, and you can go back to the previous page for navigation bar returns and physical key returns until you exit the WebView, likehistory.back.
  5. The title of the HTML in the WebView is automatically placed in the header of the applet as the title;

21, small program to call the last page method

Because, now the project is small program nested H5, financial category, do face recognition in the small program, and then buy financial management, deposit and so on in H5, after identification to return to the original H5 page according to the original path.

Remember that getCurrentPages() does not change the route, but still gets the method of the page, so I can do what I want. The code is as follows:

let pages = getCurrentPages();      
let lastpage = pages[pages.length - 2]      
if (lastpage.route === "pages/webview/webview") {        
        lastpage.changeUrl();        
    setTimeout((a)= > {          
        clearInterval(this.data.time);          
        wx.navigateBack({})        
    }, 500)}Copy the code

Then I just need to change the route to H5 in my WebView js:

  changeUrl() {    
        if (wx.getStorageSync('faceSucc')) {      
            let url = app.config.h5url + "/" + Util.formatParm(app.globalData.face_retCode, app.parm.h5_servid_url);      // console.log(app.globalData.header) // url = url + "? Param =" + encodeURIComponent(json.stringify (app.globaldata.header)) // Cache bug
            if (url.indexOf("?")! = =- 1) {        
                url = url + "&d=" + new Date().getTime()      
            } else {        
                url = url + "? d=" + new Date().getTime()      
            }      
            this.setData({        
                url: url      
            })    
        }  
    },Copy the code

The h5 route of the previous page has been modified at the time of back. Isn’t that convenient?

Small programs using AES encryption and NPM

The project needs AES encryption, so we can use crypto-JS to do it. Someone wrote a good JS file and so on, paste over can be ready to develop. But remember what I said, code elegantly. I happen to have been paying attention to wechat mini program ecology and know that I can use NPM. There’s a package for Crypto-JS, just do it.

First, execute NPM init –yes in the applet’s project directory to generate a package.json. The official documentation also recommends that NPM install –production be executed when downloading the NPM package.

NPM install –production –save crypto-js

So we have everything we want, mainly AES encryption, la la la.

Let’s introduce it first



/** * AES encryption * {encryption field} word * {secret key} keyStr */function encrypt_aes(word, keyStr) {    
    let key = CryptoJS.enc.Utf8.parse(keyStr);    
    let srcs = CryptoJS.enc.Utf8.parse(word);    
    let encrypted = CryptoJS.AES.encrypt(srcs, key, {        
        mode: CryptoJS.mode.ECB,        
        padding: CryptoJS.pad.Pkcs7    
    });    
    let result = encrypted.toString();    
    console.log("Aes encryption field", result)    
    returnresult; } /** * AES decrypt * {encryption field} word * {secret key} keyStr */function decrypt_aes(word, keyStr) {    
    let key = CryptoJS.enc.Utf8.parse(keyStr);    
    let decrypt = CryptoJS.AES.decrypt(word, key, {        
        mode: CryptoJS.mode.ECB,        
        padding: CryptoJS.pad.Pkcs7    
    });    
    let result = CryptoJS.enc.Utf8.stringify(decrypt).toString();    
    console.log("Aes decryption field", result)    
    return result;
}Copy the code

The effect is as follows:



This can achieve front-end AES encryption. Can send me a small hair ~

———————————————————————


Step by step to record their own pit course ~ I want to do my technology is not the best, but I give you a summary of the small procedures of things is the most simple and crude ha ha ha