wechat.js 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309
  1. import api from "@/common/request/index";
  2. import $platform from "@/common/platform";
  3. import store from "@/common/store";
  4. import {
  5. API_URL,
  6. API_ROOT,
  7. UNIACID
  8. } from '@/common/request/request';
  9. export default {
  10. eventMap(event) {
  11. let map = "";
  12. switch (event) {
  13. case "login":
  14. map = "登录中...";
  15. break;
  16. case "refresh":
  17. map = "更新中...";
  18. break;
  19. case "bind":
  20. map = "绑定中...";
  21. break;
  22. }
  23. return map;
  24. },
  25. async login() {
  26. let token = "";
  27. // #ifdef MP-WEIXIN
  28. token = await this.wxMiniProgramOauth("login");
  29. return token;
  30. // #endif
  31. // #ifdef H5
  32. this.wxOfficialAccountOauth("login");
  33. // #endif
  34. // #ifdef APP-PLUS
  35. token = await this.wxOpenPlatformOauth("login");
  36. return token;
  37. // #endif
  38. },
  39. async refresh() {
  40. let token = "";
  41. // #ifdef MP-WEIXIN
  42. token = await this.wxMiniProgramOauth("refresh");
  43. return token;
  44. // #endif
  45. // #ifdef H5
  46. this.wxOfficialAccountOauth("refresh");
  47. // #endif
  48. // #ifdef APP-PLUS
  49. token = await this.wxOpenPlatformOauth("refresh");
  50. return token;
  51. // #endif
  52. },
  53. async bind() {
  54. let token = "";
  55. // #ifdef MP-WEIXIN
  56. token = await this.wxMiniProgramOauth("bind");
  57. return token;
  58. // #endif
  59. // #ifdef H5
  60. this.wxOfficialAccountOauth("bind");
  61. // #endif
  62. // #ifdef APP-PLUS
  63. token = await this.wxOpenPlatformOauth("bind");
  64. return token;
  65. // #endif
  66. },
  67. // #ifdef H5
  68. // 微信公众号网页登录&刷新头像昵称&绑定
  69. wxOfficialAccountOauth(event = "login") {
  70. if ($platform.get() !== "wxOfficialAccount") {
  71. uni.showToast({
  72. title: "请在微信浏览器中打开",
  73. icon: "none"
  74. });
  75. throw false;
  76. }
  77. let host = $platform.host();
  78. // let host = window.Location.href;
  79. // let host = 'http://www.liwantao.top';
  80. // let host = 'http://t20.9026.com/h5';
  81. let payloadObject = {
  82. host: host,
  83. event,
  84. token: (event !== "login" && store.getters.isLogin) ? uni.getStorageSync("token") : ""
  85. };
  86. let payload = encodeURIComponent(JSON.stringify(payloadObject));
  87. // let redirect_uri = encodeURIComponent(`${host}pages/user/signin?payload=${payload}&uniacid=${UNIACID}`);
  88. let redirect_uri = encodeURIComponent(`${host}?payload=${payload}&uniacid=${UNIACID}`);
  89. let oauthUrl = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + 'wx96cad2970c232f6e' +
  90. `&redirect_uri=${redirect_uri}&response_type=code&scope=snsapi_userinfo&state=1&uniacid=${UNIACID}`;
  91. uni.setStorageSync("lastPage", window.location.href);
  92. window.location = oauthUrl;
  93. console.log(window.location);
  94. uni.showToast({
  95. title: window.location,
  96. icon: 'none',
  97. duration: 60000
  98. })
  99. },
  100. // 微信公众号网页静默登录:临时登录获取OpenId 不入库不绑定用户
  101. wxOfficialAccountBaseLogin() {
  102. let state = encodeURIComponent(window.location.href);
  103. window.location = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + store.getters.initWechat
  104. .appid +
  105. `&redirect_uri=${API_URL}user/wxOfficialAccountBaseLogin&response_type=code&scope=snsapi_base&state=${state}`;
  106. throw "stop";
  107. },
  108. // #endif
  109. // #ifdef APP-PLUS
  110. // 微信开放平台登录
  111. wxOpenPlatformOauth(event = "login") {
  112. let that = this;
  113. return new Promise((resolve, reject) => {
  114. uni.login({
  115. provider: "weixin",
  116. success: function(loginRes) {
  117. if (loginRes.errMsg === "login:ok") {
  118. let authResult = loginRes.authResult;
  119. api("user.wxOpenPlatformOauth", {
  120. authResult,
  121. event
  122. }, that.eventMap(event)).then(res => {
  123. if (res.code === 1) {
  124. resolve(res.data.token);
  125. } else {
  126. resolve(false);
  127. }
  128. });
  129. }
  130. },
  131. fail: function(res) {
  132. uni.showToast({
  133. title: "登录失败,请稍后再试"
  134. });
  135. resolve(false);
  136. api("common.debug", {
  137. info: res
  138. });
  139. },
  140. complete: function(res) {}
  141. });
  142. });
  143. },
  144. // #endif
  145. // #ifdef MP-WEIXIN
  146. // 微信小程序静默登录
  147. async getWxMiniProgramSessionKey(autoLogin = true) {
  148. let sessionStatus = false;
  149. let session_key = "";
  150. return new Promise((resolve, reject) => {
  151. uni.checkSession({
  152. success(res) {
  153. if (res.errMsg === "checkSession:ok") sessionStatus = true;
  154. },
  155. complete() {
  156. // console.log(uni.getStorageSync("session_key"))
  157. if (uni.getStorageSync("session_key") && sessionStatus && !autoLogin) {
  158. resolve(uni.getStorageSync("session_key"));
  159. } else {
  160. uni.login({
  161. success: function(info) {
  162. let code = info.code;
  163. api("wechat.miniappSilenceAuth", {
  164. code: code
  165. }).then(res => {
  166. if (res.code === 0) {
  167. uni.setStorageSync("session_key", res
  168. .data.session_key);
  169. if (autoLogin) {
  170. if (res.data.token) {
  171. resolve(res.data.token);
  172. } else {
  173. resolve(false);
  174. }
  175. }
  176. resolve(res.data.session_key);
  177. } else {
  178. reject(res.msg);
  179. }
  180. });
  181. }
  182. });
  183. }
  184. }
  185. });
  186. });
  187. },
  188. // 微信小程序获取用户信息登录
  189. wxMiniProgramOauth(event = "login") {
  190. let that = this;
  191. let session_key = uni.getStorageSync("session_key");
  192. uni.showLoading({
  193. title: that.eventMap(event)
  194. });
  195. return new Promise((resolve, reject) => {
  196. uni.getUserProfile({ // 必须手动确认触发
  197. desc: "展示用户头像昵称", // 声明获取用户个人信息后的用途,后续会展示在弹窗中,请谨慎填写
  198. success: res => {
  199. // console.log(res);
  200. if (res.errMsg === "getUserProfile:ok") {
  201. api("wechat.miniapp_auth", {
  202. event,
  203. session_key,
  204. encryptedData: res.encryptedData,
  205. iv: res.iv,
  206. signature: res.signature,
  207. }).then(res => {
  208. // console.log(res)
  209. if (res.code === 0) {
  210. uni.setStorageSync('isLogin', true)
  211. // store.commit('isLogin', true);
  212. store.dispatch('getUserInfo')
  213. resolve(res.data.token);
  214. } else {
  215. uni.removeStorageSync("session_key");
  216. that.getWxMiniProgramSessionKey(false);
  217. resolve(false);
  218. }
  219. });
  220. // console.log(res)
  221. resolve(res.userInfo);
  222. }
  223. },
  224. complete: res => {
  225. uni.hideLoading();
  226. if (res.errMsg === "getUserProfile:fail auth deny") {
  227. resolve(res);
  228. uni.showToast({
  229. title: '获取头像昵称失败',
  230. icon: 'none'
  231. })
  232. }
  233. }
  234. });
  235. });
  236. },
  237. getPhoneNumber(e) {
  238. let that = this;
  239. let session_key = uni.getStorageSync("session_key");
  240. // console.log(e)
  241. return new Promise((resolve, reject) => {
  242. api("wechat.authBindindPhone", {
  243. encryptedData: e.encryptedData,
  244. iv: e.iv,
  245. session_key,
  246. // client:'yuesao'
  247. }).then(ress => {
  248. if (ress.code === 0) {
  249. resolve(ress)
  250. } else {
  251. uni.showToast({
  252. title: '登录失败',
  253. icon: 'none'
  254. })
  255. }
  256. });
  257. });
  258. },
  259. // 小程序更新
  260. checkMiniProgramUpdate() {
  261. if (uni.canIUse("getUpdateManager")) {
  262. const updateManager = uni.getUpdateManager();
  263. updateManager.onCheckForUpdate(function(res) {
  264. // 请求完新版本信息的回调
  265. if (res.hasUpdate) {
  266. updateManager.onUpdateReady(function() {
  267. uni.showModal({
  268. title: "更新提示",
  269. content: "新版本已经准备好,是否重启应用?",
  270. confirmColor: '#7728f5',
  271. success: function(res) {
  272. if (res.confirm) {
  273. // 新的版本已经下载好,调用 applyUpdate 应用新版本并重启
  274. updateManager.applyUpdate();
  275. }
  276. }
  277. });
  278. });
  279. updateManager.onUpdateFailed(function() {
  280. // 新的版本下载失败
  281. uni.showModal({
  282. title: "已经有新版本了哟~",
  283. confirmColor: '#7728f5',
  284. content: "新版本已经上线啦~,请您删除当前小程序,重新搜索打开哟~"
  285. });
  286. });
  287. }
  288. });
  289. }
  290. },
  291. // #endif
  292. };