小程序跨账号调用共享云函数和图片的方法
发布于 3 年前 作者 xiuying99 576 次浏览 来自 分享

最近在做小程序开发,需要两个小程序使用一个云服务,我想可通过以下两种方式使用使得方的资源,特别是图片链接交换。请大佬指正。

首先要保证资源方已授权使用方可以共享其资源,并已存在cloudbase_auth云函数,此部分内容可参考官方文档。

一、跨账号调用云函数:(可调用资源方所有云函数)

1.调用方新建函数:可放在工具类中

//运行资源方云函数 通用函数
export async function runCloud(runName, data) {
	let c1 = new wx.cloud.Cloud({
		appid: 'xxxxxxxx',
		// 资源方 AppID
		resourceAppid: 'xxxxxxxx',
		// 资源方环境 ID
		resourceEnv: 'xxxxxxxx',
	})
	await c1.init()

	return await c1.callFunction({
		name: runName,
		data: data,
	})

}

2.假如资源方有如下云函数:login(得到临时图片链接)

const cloud = require('wx-server-sdk')
cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})

exports.main = async (event, context) => {
  console.log("正在调用云函数:[得到临时图片链接]:", event)
  const fileList = event.fileList
  const result = await cloud.getTempFileURL({
    fileList: fileList,
  })
  return result.fileList
}

3.调用方通过如下方式调用:

          runtCloud('login', {
              fileList: tempgoods._goodsPicUrl
            }).then(res => {
              console.log("临时链接-成功", res);
              for (let i = 0; i < res.result.length; i++) {
                console.log(res.result[i].tempFfileIDleURL)
                this.data.files.push(res.result[i].tempFileURL)
              }
              this.setData({
                files: this.data.files
              })
            })
            .catch(err => {
              console.log("临时链接-失败", err);
            })

二、调用方使用本地函数使用资源方的图片方法:

1.调用方新建函数:可放在工具类中

export async function getUrl(fileLis) {
	let c1 = new wx.cloud.Cloud({
		appid: 'xxxxxx',
		// 资源方 AppID
		resourceAppid: 'xxxxxx',
		// 资源方环境 ID
		resourceEnv: 'xxxxxx',
	})
	await c1.init()
	return await c1.getTempFileURL({
		fileList: fileLis
	})
}

2.调用方通过如下方式使用:

     getUrl(tempgoods._goodsPicUrl).then(res => {
          // get temp file URL
          console.log(res.fileList)
        }).catch(error => {
          // handle error
        })
回到顶部