miniProgram.js 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260
  1. import third from '@/sheep/api/third';
  2. import $store from '@/sheep/store';
  3. import AuthUtil from '@/sheep/api/member/auth';
  4. const socialType = 34; // 社交类型 - 微信小程序
  5. let sessionId = uni.getStorageSync('sessionId');
  6. let subscribeEventList = [];
  7. // 加载微信小程序
  8. function load() {
  9. checkUpdate();
  10. // const sessionStatus = await checkSession();
  11. // 小程序的接口改动太频繁了 强制每次进入都重新获取
  12. const sessionStatus = false;
  13. if (!sessionStatus) {
  14. getSessionId();
  15. }
  16. getSubscribeTemplate();
  17. }
  18. // 微信小程序静默授权登陆
  19. const login = async () => {
  20. return new Promise(async (resolve, reject) => {
  21. // 1. 获得微信 code
  22. const codeResult = await uni.login();
  23. if (codeResult.errMsg !== 'login:ok') {
  24. resolve(false);
  25. }
  26. // 2. 社交登录
  27. const loginResult = await loginByCode(codeResult.code);
  28. if (loginResult.code === 0) {
  29. setOpenid(loginResult.data.openid);
  30. resolve(true);
  31. } else {
  32. resolve(false);
  33. }
  34. return loginResult.code === 0 ? resolve(true) : resolve(false);
  35. });
  36. };
  37. function loginByCode(code) {
  38. return AuthUtil.socialLogin(socialType, code, 'default');
  39. // TODO 芋艿:shareLog
  40. }
  41. // 微信小程序手机号授权登陆
  42. const mobileLogin = async (e) => {
  43. return new Promise(async (resolve, reject) => {
  44. if (e.errMsg !== 'getPhoneNumber:ok') {
  45. resolve(false);
  46. return;
  47. }
  48. const { error } = await third.wechat.login({
  49. platform: 'miniProgram',
  50. shareInfo: uni.getStorageSync('shareLog') || {},
  51. payload: encodeURIComponent(
  52. JSON.stringify({
  53. sessionId: uni.getStorageSync('sessionId'),
  54. code: e.code,
  55. iv: e.iv,
  56. encryptedData: e.encryptedData,
  57. }),
  58. ),
  59. });
  60. if (error === 0) {
  61. resolve(true);
  62. }
  63. if (error === -1) {
  64. getSessionId(false);
  65. }
  66. resolve(false);
  67. });
  68. };
  69. // 微信小程序绑定
  70. const bind = () => {
  71. return new Promise(async (resolve, reject) => {
  72. const loginRes = await third.wechat.bind({
  73. platform: 'miniProgram',
  74. payload: encodeURIComponent(
  75. JSON.stringify({
  76. sessionId: uni.getStorageSync('sessionId'),
  77. }),
  78. ),
  79. });
  80. if (loginRes.error === -1) {
  81. getSessionId(false);
  82. } else if (loginRes.error === 0) {
  83. resolve(true);
  84. } else {
  85. reject(false);
  86. }
  87. });
  88. };
  89. // 微信小程序解除绑定
  90. const unbind = async () => {
  91. const { error } = await third.wechat.unbind({
  92. platform: 'miniProgram',
  93. });
  94. return !error;
  95. };
  96. // 获取最新sessionId
  97. const getSessionId = async (auto_login = null) => {
  98. // 获取code
  99. let codeStr = '';
  100. const loginResult = await uni.login();
  101. if (loginResult.errMsg === 'login:ok') {
  102. codeStr = loginResult.code;
  103. } else {
  104. getSessionId(auto_login);
  105. return false;
  106. }
  107. if(auto_login === null) {
  108. auto_login = !!($store('app').platform.auto_login && !$store('user').isLogin);
  109. }
  110. const { error, data } = await third.wechat.getSessionId({
  111. platform: 'miniProgram',
  112. payload: encodeURIComponent(
  113. JSON.stringify({
  114. code: codeStr,
  115. auto_login,
  116. }),
  117. ),
  118. });
  119. if (error === 0) {
  120. uni.setStorageSync('sessionId', data.session_id);
  121. return true;
  122. }
  123. return false;
  124. };
  125. // 检查sessionId是否可用
  126. const checkSession = () => {
  127. return new Promise((resolve, reject) => {
  128. if (!sessionId) {
  129. return resolve(false);
  130. }
  131. uni.checkSession({
  132. success() {
  133. return resolve(true);
  134. },
  135. fail() {
  136. uni.removeStorageSync('sessionId');
  137. return resolve(false);
  138. },
  139. });
  140. });
  141. };
  142. // 小程序更新
  143. const checkUpdate = async (silence = true) => {
  144. if (uni.canIUse('getUpdateManager')) {
  145. const updateManager = uni.getUpdateManager();
  146. updateManager.onCheckForUpdate(function (res) {
  147. // 请求完新版本信息的回调
  148. if (res.hasUpdate) {
  149. updateManager.onUpdateReady(function () {
  150. uni.showModal({
  151. title: '更新提示',
  152. content: '新版本已经准备好,是否重启应用?',
  153. success: function (res) {
  154. if (res.confirm) {
  155. // 新的版本已经下载好,调用 applyUpdate 应用新版本并重启
  156. updateManager.applyUpdate();
  157. }
  158. },
  159. });
  160. });
  161. updateManager.onUpdateFailed(function () {
  162. // 新的版本下载失败
  163. // uni.showModal({
  164. // title: '已经有新版本了哟~',
  165. // content: '新版本已经上线啦,请您删除当前小程序,重新搜索打开~',
  166. // });
  167. });
  168. } else {
  169. if (!silence) {
  170. uni.showModal({
  171. title: '当前为最新版本',
  172. showCancel: false,
  173. });
  174. }
  175. }
  176. });
  177. }
  178. };
  179. // 绑定用户手机号
  180. const bindUserPhoneNumber = (e) => {
  181. return new Promise(async (resolve, reject) => {
  182. const { error } = await third.wechat.bindUserPhoneNumber({
  183. platform: 'miniProgram',
  184. payload: encodeURIComponent(
  185. JSON.stringify({
  186. sessionId: uni.getStorageSync('sessionId'),
  187. iv: e.iv,
  188. encryptedData: e.encryptedData,
  189. code: e.code,
  190. }),
  191. ),
  192. });
  193. if (error === 0) {
  194. resolve(true);
  195. }
  196. resolve(false);
  197. });
  198. };
  199. // 获取订阅消息模板
  200. async function getSubscribeTemplate() {
  201. const { error, data } = await third.wechat.subscribeTemplate();
  202. if (error === 0) {
  203. subscribeEventList = data;
  204. }
  205. }
  206. // 订阅消息
  207. function subscribeMessage(event) {
  208. let tmplIds = [];
  209. if (typeof event === 'string') {
  210. tmplIds.push(subscribeEventList[event]);
  211. }
  212. if (typeof event === 'object') {
  213. event.forEach((item) => {
  214. if (typeof subscribeEventList[item] !== 'undefined') tmplIds.push(subscribeEventList[item]);
  215. });
  216. }
  217. if (tmplIds.length === 0) return;
  218. uni.requestSubscribeMessage({
  219. tmplIds,
  220. fail: (err) => {
  221. console.log(err);
  222. },
  223. });
  224. }
  225. // 设置 openid 到本地存储,目前只有 pay 支付时会使用
  226. function setOpenid(openid) {
  227. uni.setStorageSync('openid', openid);
  228. }
  229. export default {
  230. load,
  231. login,
  232. bind,
  233. unbind,
  234. checkUpdate,
  235. bindUserPhoneNumber,
  236. subscribeMessage,
  237. };