To send template messages in WeChat Mini Programs, developers need a specific token known as a formId. This credential serves as permission for the backend server to dispatch notifications to users. However, this token is ephemeral, expiring after seven days. This mechanism is designed by WeChat to curb spam and ensure notifications are strictly tied to user interactions.
There are two primary ways to generate these tokens: through payment transactions or by submitting a form. A single payment event yields three tokens, whereas a standard form submission provides just one. For applications that do not involve e-commerce or payments, the form submission approach is the only viable method to obtain the necessary credentials.
The framework provides a <form> component that enables this collection. To make it functional, the component must include the report-submit attribute. Additional, the submission is triggered by a <button> element with the form-type set to "submit".
<form report-submit @submit="handleTokenCollection">
<button form-type="submit">
Proceed / Share / Home
</button>
</form>
When the user interacts with the button, the event handler receives an object containing the formId in the detail property. This value must then be transmitted to the backend server to be stored for future message dispatches.
From an operational perspective, accumulating as many tokens as possible is beneficial. Consequently, developers often wrap UI elements that trigger actions—such as navigation or modals—within a form tag to capture the formId generated by the interaction. However, binding a distinct event handler to every form across the application is inefficient. To streamline this, Vue's mixin feature can be utilized to inject a universal handler into every page instance.
// main.js or app.js entry point
Vue.mixin({
methods: {
dispatchToken(event) {
const collectedId = event.detail.formId;
// Send the token to the backend
this.$http.post('/api/v1/collect-token', {
token: collectedId
}).catch(error => console.error(error));
}
}
});
By defining this mixin in the root configuration file, every page component automatically inherits the dispatchToken method. This eliminates the need for boilerplate code in individual files. For further abstraction, developers can encapsulate the form and button logic into a reusable component, such as <action-button>, to simplify the template structure.