In 2020, I did H5 development. After I finished, I wanted to make a summary, but I always dealt with it carelessly, which is completely against the spirit of developers. The past can not be pursued, seize the present, do what needs to be done now! The following summary of their own development process encountered problems, such as mistakes hope to correct.
WeChat share
Follow the official documentation step by step. Developers.weixin.qq.com/doc/offiacc… Here are the pits I’ve come across
- When obtaining the signature, you need to send the URL of the current page to the backend. As a result, you directly send the URL of the current page without being fully familiar with the official document, and then encounter invalid signature problem. The solution is that urls passed to the back end can’t contain # and the rest of the content, but links can be shared with # and the rest
let shareLink = window.location.href.split("#") [0]; // Note: the URL of the current page does not contain # or the following part
const { data } = await getWechatShareSignAPI({
params: { url: encodeURIComponent(shareLink) },
});
Copy the code
Wechat Pay and Alipay
WeChat pay donate need to adjust the payment in time, is more complex, the reference website tutorial pay.weixin.qq.com/wiki/doc/ap… , and most of the contract deduction is processed by the back end, the front end only need to jump to the page. Pay treasure payment reference, official Demo opensupport.alipay.com/support/hel… . Note the following:
- Get wechat openId. If it is the current page obtains opnedId jump and jump to the current page, will appear in the ios can back many times, more affect user experience, oneself at that time in dealing with this problem also spent a lot of time, try the initiative back to offset a browsing history method, routing guard to processing methods such as jump, It didn’t solve the problem. The final solution is to get the openId when the home page jumps to the payment origination page
generateUserAuthorizesUrl: debounce(async function() {
const redirectUrl =
process.env.NODE_ENV === "production"
? `https://The ${window.location.host}/prm/fr/mobile/index/#/donationInfo` // No arguments
: "https://121419d838.goho.co/pay/#/donationInfo"; // My IP address is forwarded to the domain name configured by the public account
const { data } = await generateUrlForOpenIdAPI({
redirectUrl
});
if (data.data) {
const userAuthorizesUrl = data.data;
this.$store.commit("cannotGetAuthorizesurl");
location.replace(userAuthorizesUrl);
} else {
this.$toast.fail(data.errmsg); }},1000)
Copy the code
- The payment result returned by wechat is not reliable, so the front end needs to get the order ID, and the back end polls the payment result.
- Because the payment authorization directory needs to be configured, the test is performed in only one environment and the domain name needs to be configured. The official solution is to check whether the merchant number used in the ordering interface is configured with a corresponding payment directory on the merchant platform (pay.weixin.qq.com).
- OpenId can be obtained from the home page to the donation page, but the interface will be called several times if continuously clicked, so three measures are adopted to process.
- With the debounce function, it can be executed immediately at first and is later called with a delay of one second
generateUserAuthorizesUrl: debounce(async function() {},1000)export const debounce = (func, wait) = > {
let timeout;
return function() {
let context = this;
let args = arguments;
if (timeout) clearTimeout(timeout);
letcallNow = ! timeout; timeout =setTimeout(() = > {
timeout = null;
}, wait);
if (callNow) func.apply(context, args);
};
};
Copy the code
- Use global loading and a mask layer so that the page cannot be clicked during the request
- After the interface returns the result, the lock for obtaining the authorized address is added to prevent the call from being invoked again
this.$store.commit("cannotGetAuthorizesurl");
this.getAuthorizesUrlFlag && this.generateUserAuthorizesUrl();
Copy the code
- When using nodes to process back-end form strings, you need to ensure that the nodes are unique so that the order generated in the case of a second payment is still the first payment.
// Error scheme
const div = document.createElement("div"); // You need to set it to a specific div to prevent repeated accumulation of the same order
div.innerHTML = data.data.payResult;
document.body.appendChild(div);
Copy the code
// Complete scheme after modification
const alipayForm = document.getElementById("alipayForm");
alipayForm.innerHTML = data.data.payResult;
let queryParam = "";
Array.prototype.slice
.call(document.querySelectorAll("input[type=hidden]"))
.forEach(function (ele) {
queryParam += "&" + ele.name + "=" + encodeURIComponent(ele.value);
});
let gotoUrl =
document.getElementsByName("punchout_form") [0].getAttribute("action") +
queryParam;
_AP.pay(gotoUrl); // The method provided after importing @/utils/ap
Copy the code
- In the page prompted to open the browser, open the page through the browser, and then jump to the Alipay payment interface. Be familiar with the processing roadmap of official Demo
var ua = navigator.userAgent.toLowerCase();
if (ua.indexOf("micromessenger") = = = -1) {
var getQueryString = function (url, name) {
var reg = new RegExp("(^ | \ \? | &)" + name + "=([^&]*)(\\s|&|$)"."i");
if (reg.test(url)) return RegExp.$2.replace(/\+/g."");
};
var param = getQueryString(location.href, "goto") | |""; location.href = param ! ="" ? _AP.decode(param) : "#/alipayTips#error";
}
Copy the code
skills
- Cover image Settings. According to the aspect ratio of the picture, the width of the picture is 100%, and the height is set to the screen width /1.875. (The previous scheme used REM, but this scheme took into account the situation of the font enlarging infinitely, so the maximum screen width obtained was limited to 750px. As a result, the height of the image set by REM does not increase when the screen is larger than 750px.)
/ / height
this.pageCoverPicHeight = window.screen.width / 1.875;
Copy the code
img {
width:100%; / * * / width
}
Copy the code
- Error picture handling
<img
:style="{ height: pageCoverPicHeight + 'px' }"
:src="fundraisingContentInfo.pageCoverPic"
:onerror="errorImg"
alt="Cover art"
/>
Copy the code
errorImg:'this.src="' + require("@/assets/images/[email protected]") + '"'.Copy the code
- The amount is in thousandths
amount.toString().replace(/\B(? =(\d{3})+(? ! \d))/g.",")
Copy the code
- Micro-channel debugging method: micro-channel debugging H5 page _weixin_33935777 blog -CSDN blog
- Wechat cache problem, open blank in wechat browser, open normal in other browsers. Need to clear cache
- Check whether the current environment is IOS
const u = navigator.userAgent;
constisiOS = !! u.match(/\(i[^;] +; ( U;) ? CPU.+Mac OS X/);
Copy the code
- Check whether the current environment is wechat terminal
const userAgent = navigator.userAgent.toLowerCase();
const isWechat = /MicroMessenger/i.test(userAgent);
Copy the code
Compatibility issues
- Because the page title is returned by the back-end interface, it needs to be set dynamically. In ios, this is done by creating a node and then removing it
let i = document.createElement("iframe");
i.src = "";
i.style.display = "none";
i.onload = function () {
setTimeout(function () {
i.remove();
}, 9);
};
document.title = this.projectName;
document.body.appendChild(i);
Copy the code
- When using the fixed property of native CSS, there was a 1px gap at the bottom, and later when using vant components directly
- Record the bottom navigation of wechat ios: display the bottom navigation bar when there is route history, hide the bottom navigation bar when you swipe up; IPhone forward rollback will not trigger any VUE events
- The requirement is that the current page has little content, a background color needs to be filled in, and no scroll bars appear. Thanks to the iPhone will appear at the bottom of the navigation bar, and the document. The documentElement. ClientHeight attribute will not be at the bottom of the column, the influence of this page will appear the situation of the scroll bar. The fixed attribute is used to solve the problem.
position: fixed;
top: 0;
bottom: 0;
width: 100%;
background-color: #fff;
Copy the code
- Requirement: Except the home page (with project parameters), all page URLS need to have project information parameters, so that when opened through the browser, you can jump to the home page and get project information through these parameters. The initial solution is to use the route guard (beforeRouteEnter), which will patch up the parameters for the current address when opening other pages, but this will generate browsing history and need to be rolled back twice. Location. replace was used later. Now think about it. When you jump to a page, you just add parameters.
- #/home/? #/home/? Pid = 2 & code = 3 is onefoundation.yeepay.com/prm/fr/mobi… Generate links to remove # / ok, may be behind the judgment to have parameters, have # will jump onefoundation.yeepay.com/prm/fr/mobi twice…
- IOS needs to click the button twice. You can click the “OK” button when closing the popover to prevent the popover from appearing after clicking the button twice next time
<div
class="agreement-link-donate"
:style="{ color: pageThemeColor }"
@click="onShowDonationAuthorizationDialog"
>Donation Authorization Agreement,</div>
<van-dialog
v-model="showPrivacyDialog"
title=Privacy Agreement
:show-cancel-button="false"
:lock-scroll="true"
:allow-html="true"
:message="agreementInfos.privacyAgreement"
@confirm="clickPage"
>
</van-dialog>
Copy the code
// Display donation authorization popup
onShowDonationAuthorizationDialog() {
this.showDonationAuthorizationDialog = true;
},
// You need to click the next page, in case the next ios click does not work
clickPage() {
document.getElementById("alipayForm").click();
}
Copy the code
- Fix the return to the top problem
Problem description: Click to return to the top, ios version of wechat need to click twice, it is judged that the first time did not trigger the event, after clicking triggered the event
- Scheme 1: Fixed property becomes absolute property, but after setting overflow:hidden, max-height is also needed to hide some elements, but this cannot get the scrollTop value after scrolling, so this scheme is excluded
<div class="home-wrapper">
<div class="home-one-wrapper" id="home-one-wrapper"></div>
<div class="home-two-wrapper"></div>
</div>
Copy the code
.home-wrapper {
position: relatvie;
width: 100%;
height: 100%;
overflow: hidden;
.home-one-wrapper {
width: 100%;
height: 100%;
max-height: 627px;
overflow-y: scroll;
}
.home-two-wrapper {
position: absolute;
bottom: 0;
left: 0;
width: 100%; }}Copy the code
- Plan TWO (compromise) : make the back to the top button permanently displayed
<van-icon
v-show="true"
:style="{ color: pageThemeColor }"
class-prefix="iconfont icon-Top"
class="go-top"
name="extra"
@click="backTop"
/>
Copy the code
- In ios, a network error may occur when you open the payment page through a browser because the page polls the payment result. You need to cancel all polling requests
CancalRequest () {let cancelArr = window.axioscancel; Cancelarr.foreach ((ele, index) => {// el.cancel (" cancelarr.cancel "); // Return this custom error message in the failed function delete window.axiosCancel[index]; }); }, // axios saves all requests window.axiosCancel = []; config.cancelToken = new axios.CancelToken((cancel) => { window.axiosCancel.push({ cancel, }); });Copy the code
Other problems
- H5 needs to handle the no-network situation, the weak network situation
- Use Alibaba’s Iconfont for ICONS and moment library for time processing
- The iPhone has a problem with rotating the screen. No solution has been found
lesson
- Although it is front-end development, you should also take the time to understand the whole development process, especially in the three-party connection, to familiarize yourself with all possible exceptions and find the corresponding solutions in time
- At least one Android machine and one iPhone, due to the particularity of iPhone, there are many pits in the development of wechat H5.