# Weixin Mini Program Manual access

The document applies to PC Weixin Mini Program, low-base library to run Mini Program, hardware framework to run Mini Program, Mini Program plug-in

In general, it is recommended to use one-key access , which supports various grayscale, one-key disconnection, preheating and other configurations, more flexible and safe.However, in some special scenarios (such as PC side, Web, need to be compatible with the lower version), you can use the following manual access scheme.

We have also launched a video course, so you can go to the video course at the bottom of the document to learn this part.

It's important!!! : Before using a manual access scheme, the following two steps need to be done:

  1. In the WeChat public platform , the gateway domain name (a****-********.sh.wxcloudrun.com) Manually add to the request valid domain name.
  2. If you need to complete it completely manually, do not automatically access the intervention, log in to WeChat Gateway console , in the corresponding Weixin Mini Program business configuration - Advanced settings to configure a list of domain names to be manually accessed (in this case the domain name is the business domain name)

3. After manual access, you need to do your own request de-escalation logic, WeChat gateway does not provide automatic de-escalation capability. For example, if the QPS of the Weixin Mini Program domain exceeds the package specification by manually accessing it, the exceeded request will enter a fail callback.

# 1. Primary Weixin Mini Program

# 1. Inapagejson, add the use ofcloud: trueThe capabilities cover the low version libraries, as follows:

// Apagejson, if it's uniapp in the mp-weixin field in manifest.json, if it's taro in apageconfig.js
{
  "cloud": true,
  "cloudVersion": "release"
}

# 2. Real-world validation introduces effects

Once the configuration is in effect, it is highly recommended to preview in real-world mode to test whether there are abnormalities and whether this will affect the original normal business.

# 3. Supplement the manual access code logic

Cloud: truecapabilities do not support "one-click access" and other capabilities, need to manually complete the implementation of the corresponding capabilities.

You can hijack wx.request by adding the following code to onLaunch in apagejs to achieve the effect of one-click access

// Reference implementation, by hijacking wx.request to complete a similar one-click access effect
App({
    onLaunch() {
        const gateway = wx.cloud.services.Gateway({
            // 接入域名:即在网关接入层生成的域名,请复制“域名配置”中网关的接入域名。
            domain: 'a****-********.sh.wxcloudrun.com',
        })
        // 赋值到 cloud 对象上,方便后续调用
        wx.cloud.gateway = gateway
        const __origin_req = wx.request;
        const gatewayDomainList = [
            "https://domain"
        ] // url 前缀匹配命中 gatewayDomainList 中的访问请求,将使用网关进行访问
        function checkGateway(url) {
            for (const element of gatewayDomainList) {
                if (url.startsWith(element)) {
                    return true
                }
            }
            return false
        }
        // 重写 wx.request
        function request(option) {
            if (checkGateway(option.url)) {
                if (!option.header) option.header = {}
                option.header['X-WX-HTTP-MODE'] = "REROUTE"
                option.header['X-WX-CONF-VERSION'] = "0"
                return gateway.call({
                    path: option.url,
                    ...option, // success 回调在这里注册
                    fail: (err) => {
                      // 如果需要回退到 wx.request,使用第一行进行重试
                      // 如果不需要回退到 wx.request,使用第二行进入 fail 回调
                      return __origin_req(option)
                      // return option.fail(err)
                    }
                })
            }
            return __origin_req(option)
        }
        Object.defineProperty(wx, 'request', {
          value: request,
          enumerable: true,
          configurable: true,
        })
    }
})

# II. Third-party frameworks such as Taro

Some third-party frameworks do not support rewriting wx.request, which can be accessed using the official interceptor, as follows:

# 1. Creating gateway.js

# 1.1 Examples of Taro:
import Taro from '@tarojs/taro'

// The gateway domain name whitelist, URL at the beginning of the following address will be accessed through the gateway
const GATEWAY_INTERCEPT_URLS = [
  'https://example.com'
]

if (Taro.getEnv() === Taro.ENV_TYPE.WEAPP) {
  const gateway = wx.cloud.services.Gateway({
    // 接入域名:即在网关接入层生成的域名,请复制“域名配置”中网关的接入域名。
    domain: '***your-domain***.sh.wxcloudrun.com',
  })

  const gatewayInterceptor = (chain) => {
    const params = chain.requestParams
    if (GATEWAY_INTERCEPT_URLS.some(url => params.url.startsWith(url))) {
      return gateway.call({
        ...params,
        header: {
          ...params.header,
          'X-WX-HTTP-MODE': 'REROUTE',
          'X-WX-CONF-VERSION': '0',
        },
        path: params.url,
      })
    } else {
      return chain.proceed(params)
    }
  }
  Taro.addInterceptor(gatewayInterceptor)
}
# 1.2 Uniapp example:
// #ifdef MP-WEIXIN

// The gateway domain name whitelist, URL at the beginning of the following address will be accessed through the gateway
const GATEWAY_INTERCEPT_URLS = [
  'https://example.com'
]
const gateway = wx.cloud.services.Gateway({
  // 接入域名:即在网关接入层生成的域名,请复制“域名配置”中网关的接入域名。
  domain: '****.sh.wxcloudrun.com',
})


uni.addInterceptor('request', {
  invoke(params) {
    if (GATEWAY_INTERCEPT_URLS.some(url => params.url.startsWith(url))) {
      return gateway.call({
        ...params,
        header: {
          ...params.header,
          'X-WX-HTTP-MODE': 'REROUTE',
          'X-WX-CONF-VERSION': '0',
        },
        path: params.url,
      })
    }
  },
})

// #endif

# 2. Inapp.jswe introduce the above JS.

import './gateway.js'

# 3. Test whether the request is normal

# III. API Access

If you need to use a more granular access scheme, you can use the form of API access:

interface GatewayCallParam {
  path: string
  header: Record<string, string>
  data?: string | ArrayBuffer | any
  method?: string
  success?: (res: GatewayCallResult) => void
  fail?: (err: Error) => void
}
interface GatewayCallResult {
  data: any
  statusCode: number
  header: Record<string, any>
  callID: string
}
interface GatewayInstance {
    call: (param: GatewayCallParam) => Promise<GatewayCallResult>
}
declare interface WxCloud {
    services: {
        Gateway: (opts: { domain: string }) => GatewayInstance
    }
    gateway: GatewayInstance
}
declare interface Wx {
    cloud: WxCloud
}

Use the following example

const gateway = wx.cloud.services.Gateway({
      // 接入域名,可以在网关控制台中获取
      domain: 'a******.sh.wxcloudrun.com',
})
// Assign the value to the cloud object for subsequent calls
wx.cloud.gateway = gateway

const result = wx.cloud.gateway.call({
      // 填写完整域名(包括协议头和 host 部分,如 https://api.example.com/path?query=xxx)
      // 如果 URL 中包含中文,需要手动 encode
      path: 'https://httpbin.org/get?query=xxx',
      // 请求方法
      method: 'GET',
      // 请求 header
      header: {
           //! 重要:需要携带这个 Header,以启用多域名支持能力
          'X-WX-HTTP-MODE': 'REROUTE',
           //! 手工接入需要携带的特殊字段,跳过版本号检查
          'X-WX-CONF-VERSION': '0',
      }
      // 其余参数与 wx.request 相同
}).then(result => {
      console.log(result)
})

# IV. FAQ

# 1. What are the limitations of manual access?

  • Be sure to add the gateway domain name to the MP legitimate domain name by yourself, otherwise the gateway will trigger the link switch, resulting in slow or abnormal request.
  • The following gateway capabilities cannot be used when manual access: native cryptographic optimization, and gateway performance will have some impact depending on the business scenario.
  • If the gateway expires or exceeds the traffic limit, it will enter a fail callback, which needs to be handled manually by the developer.

# 2. How does manual access grey the flow?

When accessing manually, you can use the form of API access and decide whether to use gateway.call or wx.request for the request

# 3. What versions are supported by manual access?

  • WeChat: 2.14.1 base library version and above
  • Enterprise WeChat: 2.20.3 base library version and above
  • Web SDK: Version 2.0.3 SDK and above

In Weixin Mini Program with cloud: true enabled, you will be prompted to use cloud: true