WXCustomAd.ts 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271
  1. export interface IPos {
  2. left?: number;
  3. right?: number;
  4. top?: number;
  5. bottom?: number;
  6. centerX?: number;
  7. centerY?: number;
  8. }
  9. export enum EType {
  10. // * @param type 1矩阵;2横向;3竖向;4单格子
  11. rect = 1,
  12. horizontal,
  13. vertical,
  14. grid,
  15. }
  16. export class WXCustomAd {
  17. /**原生模板广告矩阵样式id */
  18. private static _customc_rect_adunit = ['adunit-b04115e5114f5da0'];
  19. /**原生模板广告横向样式id */
  20. private static _customc_h_adunit = ['adunit-decef95822ca30a1'];
  21. /**原生模板广告竖向样式id */
  22. private static _customc_v_adunit = ['adunit-38b6a6801a71ca88', 'adunit-1637a511c46c5490'];
  23. /**原生模板广告单个样式id */
  24. private static _customc_one_adunit = [];
  25. /**广告缓存 */
  26. private static _ads = {};
  27. /** */
  28. private static _waits = [];
  29. private static sysInfo = null;
  30. private cb: any;
  31. static cb: Function;
  32. /**
  33. * 设置广告id
  34. * @param rectid 矩阵样式id
  35. * @param hid 横向样式id
  36. * @param vid 竖向样式id
  37. * @param oneid 单格子样式id
  38. */
  39. static setadunit(rectid, hid, vid, oneid) {
  40. this._customc_rect_adunit = rectid;
  41. this._customc_h_adunit = hid;
  42. this._customc_v_adunit = vid;
  43. this._customc_one_adunit = oneid;
  44. }
  45. /**
  46. * 创建一个原生广告对象
  47. * @param flag 创建来源标识(用标识来控制显示和隐藏)
  48. * @param type 1矩阵;2横向;3竖向;4单格子
  49. * @param pos 位置(对象可包含left、right、top、bottom、centerX、centerY字段)。分别表示距离左右上下和中心点的距离
  50. * @param failcb:当未拉取到广告(目前仅限报1004错误,如拉取其他错误需自行更改回调)之后,可执行回调。
  51. * @returns
  52. */
  53. static createCustomAd(flag, type: EType, pos: IPos, extraId?: any, failcb?: Function) {
  54. if (!window.wx) return;
  55. if (!this.sysInfo) {
  56. this.sysInfo = wx.getSystemInfoSync()
  57. }
  58. let version = this.sysInfo.SDKVersion;
  59. let ad = null;
  60. let id = "";
  61. let self = this;
  62. if (failcb) {
  63. this.cb = failcb;
  64. }
  65. if (type == 1) {
  66. id = this._customc_rect_adunit[this.rand(0, this._customc_rect_adunit.length - 1)];
  67. } else if (type == 2) {
  68. id = this._customc_h_adunit[this.rand(0, this._customc_h_adunit.length - 1)];
  69. } else if (type == 3) {
  70. id = this._customc_v_adunit[this.rand(0, this._customc_v_adunit.length - 1)];
  71. }
  72. else if (type == 4) {
  73. id = this._customc_one_adunit[this.rand(0, this._customc_one_adunit.length - 1)];
  74. }
  75. if (extraId && extraId !== "") {
  76. if (typeof extraId == "string") {
  77. id = extraId;
  78. } else if (extraId instanceof Array) {
  79. id = extraId[this.rand(0, extraId.length - 1)];
  80. }
  81. }
  82. //id不存在
  83. if (id == "") return;
  84. console.log("显示原生模板广告", flag, this._ads, this._waits);
  85. //缓存有
  86. if (this._ads[flag]) {
  87. ad = this._ads[flag];
  88. console.log("缓存有");
  89. if (!ad.isShow()) ad.show();
  90. }
  91. else if (this.compareVersion(version, '2.11.1') >= 0) {
  92. console.log("创建原生模板广告" + flag, "id:" + id, "pos:", pos);
  93. let p = self.getPos(type, pos);
  94. ad = wx.createCustomAd({
  95. adUnitId: id,
  96. adIntervals: 30,
  97. style: {
  98. top: p.top,
  99. left: p.left,
  100. width: 330, // 用于设置组件宽度,只有部分模板才支持,如矩阵格子模板
  101. fixed: false // fixed 只适用于小程序环境
  102. }
  103. })
  104. ad.onLoad(() => {
  105. self._ads[flag] = ad;
  106. let index = self._waits.indexOf(flag);
  107. console.log("原生模板广告加载完成:" + flag, self._waits, index);
  108. if (index == -1)
  109. ad.show();
  110. else {
  111. self._waits = self._waits.filter(x => x != flag);
  112. // self._waits.splice(index, 1);
  113. ad.hide().then(() => {
  114. }).catch(() => {
  115. // self.hideCustomAd(flag);
  116. console.log("第二次hide");
  117. ad.hide().catch(() => {
  118. console.log("第三次hide");
  119. });
  120. });
  121. }
  122. });
  123. ad.onError((res) => {
  124. console.log('原生模板广告加载失败:', res.errCode, ' ', res.errMsg);
  125. if (parseInt(res.errCode) === 1004 && this.cb) {
  126. console.log("拉取失败");
  127. this.cb();
  128. }
  129. });
  130. ad.onClose(() => {
  131. console.log("原生模板广告关闭");
  132. });
  133. } else {
  134. // 如果希望用户在最新版本的客户端上体验您的小程序,可以这样子提示
  135. // wx.showModal({
  136. // title: '提示',
  137. // content: '当前微信版本过低,无法使用该功能,请升级到最新微信版本后重试。'
  138. // })
  139. }
  140. }
  141. public static rand(min, max) {
  142. return min + Math.floor(Math.random() * (max - min + 1));
  143. }
  144. /**
  145. * 隐藏原生模板广告
  146. * @param flag
  147. */
  148. public static hideCustomAd(flag) {
  149. let ad = null;
  150. console.log("隐藏原生模板广告", flag, this._ads, this._waits);
  151. if (this._ads[flag]) {
  152. ad = this._ads[flag];
  153. if (ad.isShow())
  154. ad.hide().then(() => {
  155. }).catch(() => {
  156. // self.hideCustomAd(flag);
  157. console.log("第二次hide");
  158. ad.hide().catch(() => {
  159. console.log("第三次hide");
  160. });
  161. });
  162. } else {
  163. if (this._waits.indexOf(flag) == -1) {
  164. this._waits.push(flag);
  165. }
  166. }
  167. }
  168. public static destroyCustomAd(flag) {
  169. if (this._ads[flag]) {
  170. this._ads[flag].destroy();
  171. this._ads[flag] = null;
  172. }
  173. }
  174. private static compareVersion(v1, v2) {
  175. v1 = v1.split('.')
  176. v2 = v2.split('.')
  177. const len = Math.max(v1.length, v2.length)
  178. while (v1.length < len) {
  179. v1.push('0')
  180. }
  181. while (v2.length < len) {
  182. v2.push('0')
  183. }
  184. for (let i = 0; i < len; i++) {
  185. const num1 = parseInt(v1[i])
  186. const num2 = parseInt(v2[i])
  187. if (num1 > num2) {
  188. return 1
  189. } else if (num1 < num2) {
  190. return -1
  191. }
  192. }
  193. return 0
  194. }
  195. /**
  196. * 获取实际的位置
  197. * @param type 模板类型
  198. * @param pos 游戏中的相对位置
  199. * @returns
  200. */
  201. private static getPos(type, pos: IPos) {
  202. if (!this.sysInfo) {
  203. this.sysInfo = wx.getSystemInfoSync();
  204. }
  205. let sysInfo = this.sysInfo;
  206. let w = 0, h = 0;
  207. if (type == 1) { w = 330; h = 360; };
  208. if (type == 2) { w = 360; h = 106; };
  209. if (type == 3) { w = 72; h = 250; };
  210. if (type == 4) { w = 68; h = 106; };
  211. // if (type == 1) { w = 330; h = 360; };
  212. // if (type == 2) { w = 72; h = 250; };
  213. // if (type == 3) { w = 72; h = 250; };
  214. // if (type == 4) { w = 68; h = 106; };
  215. let sc_w = sysInfo.windowWidth / cc.winSize.width;
  216. let sc_h = sysInfo.windowHeight / cc.winSize.height;
  217. let l = (sysInfo.windowWidth - w) / 2;
  218. let t = (sysInfo.windowHeight - h) / 2;
  219. if (pos && pos.left != undefined) l = pos.left * sc_w;
  220. if (pos && pos.top != undefined) t = pos.top * sc_h;
  221. if (pos && pos.right != undefined) l = sysInfo.windowWidth - w - pos.right * sc_w;
  222. if (pos && pos.bottom != undefined) t = sysInfo.windowHeight - h - pos.bottom * sc_h;
  223. if (pos && pos.centerX != undefined) l = (sysInfo.windowWidth - w) / 2 + pos.centerX * sc_w;
  224. if (pos && pos.centerY != undefined) t = (sysInfo.windowHeight - h) / 2 + pos.centerY * sc_h;
  225. return {
  226. left: l,
  227. top: t
  228. }
  229. }
  230. public static hideAllAd() {
  231. for (const key in this._ads) {
  232. this.hideCustomAd(key);
  233. }
  234. }
  235. }