officialAccount.js 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  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.code === 1 && 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.code === 1) {
  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.code === 1 && 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.code === 1) {
  49. return loginResult;
  50. }
  51. }
  52. return false;
  53. }
  54. // 微信公众号解除绑定
  55. async function unbind() {
  56. const { code } = await third.wechat.unbind({
  57. platform: 'officialAccount',
  58. });
  59. return !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({ code }, {
  77. platform: 'officialAccount',
  78. shareInfo: uni.getStorageSync('shareLog') || {},
  79. });
  80. }
  81. // 此处使用前端发送code在后端解密,防止用户在后端过长时间停留
  82. function bindByCode(code) {
  83. return third.wechat.bind({ code }, {
  84. platform: 'officialAccount',
  85. });
  86. }
  87. export default {
  88. load,
  89. login,
  90. bind,
  91. unbind,
  92. jssdk: $wxsdk,
  93. };