# 送礼助手
送礼助手小程序是一款互动类的直播小程序。通过下文的介绍,可以学到更多有关小程序SDK的用法与规范,并熟悉小程序的开发流程。
# 小程序截图
- web主播端:
- APP端:
# 主播端开发过程
主播端要实现的功能主要是设置礼物,以及把一些信息保存到服务端。
# 区分主播端和观众端,进入不同的路由展示页面
// containers/Main/index.js
import './index.scss';
import React from 'react';
import { App } from '@fxext/core';
import routers from './routers';
// 小程序初始化处理
const init = async (history, setAppState) => {
const { isAnchor } = await FxExt.isAnchor();
// 判断是否主播端
if (isAnchor) {
// 主播端跳转到礼物设置页面路由
history.replace('/setting');
} else {
history.replace('/playing');
}
return true;
};
export default function Main() {
return <App title="送礼助手" titleStyle="black" routers={routers} init={init} />;
}
路由配置
// containers/Main/routers.js
import GiftSetting from '../GiftSetting';
import Playing from '../Playing';
export default [
{
path: '/setting',
component: GiftSetting,
},
{
path: '/playing',
component: Playing,
},
];
# 拉起礼物选择器设置礼物
// containers/GiftSetting/index.js
import React, { useState } from "react";
import { showGiftPicker } from "@fxext/core";
import './index.scss';
export default function GiftSetting() {
const [giftInfo, setGiftInfo] = useState(null);
const selectGift = () => {
// showGiftPicker方法在sdk版本1.0.4及以上可用,@fxext/core为1.0.2及以上
showGiftPicker(result => {
console.log(result);
setGiftInfo(result);
// 调用后端接口保存到服务器上以便观众端可以获取
FxExt.fetch({
url: 'https://myserver.com/setGiftInfo',
type: 'POST',
dataType: 'json',
data: {
giftInfo: result
}
}).then(res => console.log(res))
});
};
if (giftInfo) {
return (
<div className="gift-setting">
<div>主播公告:送出100个<img src={giftInfo.image} />上管理</div>
</div>
);
}
return (
<div className="gift-setting">
<div>设置上直播间管理礼物</div>
<button onClick={selectGift}>设置礼物</button>
</div>
);
}
主播点击设置礼物按钮后调用 @fxext/core 中提供的 showGiftPicker 即可拉起礼物选择器面板组件,回调函数中可以拿到用户选择结果,如下图所示
# 观众端开发过程
观众端主要从服务端拉取主播设置的礼物信息,并展示送礼按钮提供小程序送礼。
需要使用另外的账号进入已开启该小程序的直播间,该账号需配置内测版本观众白名单,可在版本管理-设置-访问权限中添加
添加完观众白名单后刷新直播间就可以看到悬浮窗的小程序入口
观众端点击送礼按钮拉起小程序送礼弹窗代码示例
// containers/Playing/index.js
import React, { useState, useEffect } from "react";
import './index.scss';
export default function Playing() {
const [giftInfo, setGiftInfo] = useState(null);
useEffect(() => {
// 从服务端接口获取主播设置的礼物信息
FxExt.fetch({
url: "https://myserver.com/getGiftInfo",
type: "GET",
dataType: "json",
}).then(setGiftInfo);
}, []);
const sendGift = () => {
// 拉起小程序送礼面板
FxExt.sendGift({
giftId: giftInfo.giftId, // 礼物id
giftCount: 100, // 礼物数量
}).then((result) => {
if (result.id) {
console.log("送礼成功!");
}
});
};
if (giftInfo) {
return (
<div className="gift-playing">
<div>
主播公告:送出100个
<img src={giftInfo.image} />
上管理
</div>
<div className="send-gift-btn" onClick={sendGift}>
赠送
</div>
</div>
);
}
return <div className="gift-playing">主播暂未设置礼物</div>;
}
# 总结
该小程序主要通过下面的SDK方法实现了主要功能。
- 发起 HTTPS 网络请求(FxExt.fetch)
- 判断当前用户是否为主播(FxExt.isAnchor)
- 获取直播间礼物列表(FxExt.getGiftList)
- 直播间送礼(FxExt.sendGift)
更多的SDK用法可以在这里查阅,使用时注意当前终端和版本是否支持该方法。