# WEB & H5 Using the WeChat gateway

This article introduces how to access WeChat WeChat gateway in WEB application.

Note: WEB Application Access only supports the basic version of the package and above.

# I. Access steps

# 1. WeChat Scan code login WeChat gateway control console

Agree to the WeChat gateway service agreement and agree to complete the opening.On the WeChat Gateway - Business Configuration page, click Add Business to start configuration.

# 2. Add a business page, select the business type as "Web," and then fill in the business name (self fill) and the source domain name.

The source domain name here is the API domain name when the web page makes an API call to the service.For example, you make a request fromhttps://weixin.example.comweb page tohttps://api.exapmple.com, then the configuration should be filled withapi.exapmple.com

# 3. In your own web application, introduce the WeChat Gateway Web SDK
<script src="https://该地址隐藏,请前往控制台获取/cloud.js"></script>

<!-- 下面是 eruda 调试工具,仅供开发时使用,上线前需删除 -->
<script src="//cdn.jsdelivr.net/npm/eruda"></script>
<script>eruda.init();</script>

Note that the SDK above version 2.0.3 no longer allows the DevTools debugging tool to be opened, otherwise the request will be intercepted. Console logs can be viewed using debugging tools such as eruda

# 4. Initialize Gateway objects and instances
const c1 = new cloud.Cloud({
  identityless: true,
  resourceAppid: 'wx069a87eae381af2b', // appid,填入接入的小程序 appid
  config: {
    customDomain: 'https://a224faf18-wx66e29c62636ff9e5.preview.wxcloudrun.com' // 网关接入节点域名,需要完整填入
  }
})
c1.init() // 初始化实例

const gateway = c1.services.Gateway({ domain: 'a224faf18-wx66e29c62636ff9e5.preview.wxcloudrun.com' }) // 网关接入节点域名,不包含协议头
# 5. Request a gateway address
gateway.call({
path: 'https://httpbin.org/post',
    header:{
      'X-WX-HTTP-MODE': 'REROUTE', // 必填
      'Content-Type':'application/json'
    },
method: 'post',
    data: { foo: 'bar' }
}).then(res => {
    console.log(res) // 网关返回结果
})

# II. Capacity development

WeChat The gateway supports H5 in combination with different request libraries. Refer to the following documentation

Using Axios in combination with WeChat WeChat Gateway

WeChat WeChat Gateway

# III. Full Examples

Here is a simple sample HTML that you can adapt to your business after testing.

<script src="https://该地址隐藏,请前往控制台获取/cloud.js" importance="VeryHigh"></script>
<script src="https://cdn.jsdelivr.net/npm/eruda"></script>
<script>
    const DOMAIN = 'XXXXXXXXXX.sh.wxgateway.com' // 网关域名
    const URL = 'https://www.testtest.com' // 你的业务 URL,可自行改造

    window.onload = async function () {
        eruda.init({tool:['console', 'network', 'info'],theme:'Arc Dark', autoScale:true, defaults:{displaySize: 90, transparency: 0.94}});
        const c1 = new window.cloud.Cloud({
            identityless: true,
            config: {
                customDomain: `https://${DOMAIN}`,
            }
        });
        await c1.init()
        const gateway = c1.services.Gateway({ domain: DOMAIN })
        window.gateway = gateway
        window.test()
    }
    window.test = function () {
        window.gateway.call({
            path: URL,
            header: {
                'X-WX-HTTP-MODE': 'REROUTE',
                'Content-Type': 'application/json'
            },
            method: 'GET',
            data: { foo: 'bar' }
        }).then(res => {
            const { callID, data, errMsg, statusCode } = res
            if(statusCode === 200) {
                console.log(`[${callID}] 网关请求成功`, data)
            } else {
                console.log(`[${callID}] 网关请求失败`, errMsg)
            }
        }).catch(err => {
            err = err.toString()
            if(err.includes('base_resp.ret 102006')) {
                console.log(`[${err.match(/callId: ([\w\-]+)/)[1]}] 网关请求非法(开启控制台调试或代理),信息:base_resp.ret 102006`)
            } else if(err.includes('errCode: 102016')){
                console.log(`[${err.match(/callId: ([\w\-]+)/)[1]}] 请求地址不在微信网关的小程序 URL 里,或者网关到期,信息:base_resp.ret 102016`)
            } else if(err.includes('gateway.call:fail 0')){
                console.error('网关请求失败,网络出现问题,受跨域限制或路径不可访问')
            } else {
                console.error('网关请求失败,其他原因:', err)
            }
        })
    }
</script>
<button onclick="window.test()">测试</button>