officialAccount.js 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112
  1. import third from '@/sheep/api/third';
  2. import $wxsdk from '@/sheep/libs/sdk-h5-weixin';
  3. import $store from '@/sheep/store';
  4. import $platform from '@/sheep/platform';
  5. import { getRootUrl } from '@/sheep/helper';
  6. // 加载微信公众号JSSDK
  7. async function load() {
  8. if (
  9. $store('app').platform.auto_login &&
  10. !$store('user').isLogin &&
  11. location.href.search('pages/index/login') === -1
  12. ) {
  13. // 发起自动登陆
  14. login();
  15. }
  16. $wxsdk.init();
  17. }
  18. // 微信公众号登陆
  19. async function login(code = '') {
  20. // 获取登陆地址
  21. if (!code) {
  22. const loginResult = await getLoginUrl();
  23. if (loginResult.error === 0 && loginResult.data.login_url) {
  24. uni.setStorageSync('returnUrl', location.href);
  25. window.location = loginResult.data.login_url;
  26. }
  27. } else {
  28. // 解密code发起登陆
  29. const loginResult = await loginByCode(code);
  30. if (loginResult.error === 0) {
  31. return loginResult;
  32. }
  33. }
  34. return false;
  35. }
  36. // 微信公众号绑定
  37. async function bind(code = '') {
  38. // 获取绑定地址
  39. if (code === '') {
  40. const loginResult = await getLoginUrl('bind');
  41. if (loginResult.error === 0 && loginResult.data.login_url) {
  42. uni.setStorageSync('returnUrl', location.href);
  43. window.location = loginResult.data.login_url;
  44. }
  45. } else {
  46. // 解密code发起登陆
  47. const loginResult = await bindByCode(code);
  48. if (loginResult.error === 0) {
  49. return loginResult;
  50. }
  51. }
  52. return false;
  53. }
  54. // 微信公众号解除绑定
  55. async function unbind() {
  56. const { error } = await third.wechat.unbind({
  57. platform: 'officialAccount',
  58. });
  59. return Promise.resolve(!error);
  60. }
  61. // 获取公众号登陆地址
  62. function getLoginUrl(event = 'login') {
  63. let page = getRootUrl() + 'pages/index/login';
  64. return third.wechat.oauthLogin({
  65. platform: 'officialAccount',
  66. payload: encodeURIComponent(
  67. JSON.stringify({
  68. page,
  69. event,
  70. }),
  71. ),
  72. });
  73. }
  74. // 此处使用前端发送code在后端解密,防止用户在后端过长时间停留
  75. function loginByCode(code) {
  76. return third.wechat.login({
  77. platform: 'officialAccount',
  78. shareInfo: uni.getStorageSync('shareLog') || {},
  79. payload: encodeURIComponent(
  80. JSON.stringify({
  81. code,
  82. }),
  83. ),
  84. });
  85. }
  86. // 此处使用前端发送code在后端解密,防止用户在后端过长时间停留
  87. function bindByCode(code) {
  88. return third.wechat.bind({
  89. platform: 'officialAccount',
  90. payload: encodeURIComponent(
  91. JSON.stringify({
  92. code,
  93. }),
  94. ),
  95. });
  96. }
  97. export default {
  98. load,
  99. login,
  100. bind,
  101. unbind,
  102. jssdk: $wxsdk,
  103. };