wechat.js 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297
  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. console.log(host)
  79. let payloadObject = {
  80. host: host,
  81. event,
  82. token: (event !== "login" && store.getters.isLogin) ? uni.getStorageSync("token") : ""
  83. };
  84. let payload = encodeURIComponent(JSON.stringify(payloadObject));
  85. let redirect_uri = encodeURIComponent(`${host}pages/user/signin?payload=${payload}&uniacid=${UNIACID}`);
  86. let oauthUrl = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + store.getters.appInfo.wechat_appid +
  87. `&redirect_uri=${redirect_uri}&response_type=code&scope=snsapi_userinfo&state=1&uniacid=${UNIACID}`;
  88. uni.setStorageSync("lastPage", window.location.href);
  89. window.location = oauthUrl;
  90. console.log(window.location);
  91. },
  92. // 微信公众号网页静默登录:临时登录获取OpenId 不入库不绑定用户
  93. wxOfficialAccountBaseLogin() {
  94. let state = encodeURIComponent(window.location.href);
  95. window.location = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + store.getters.initWechat.appid +
  96. `&redirect_uri=${API_URL}user/wxOfficialAccountBaseLogin&response_type=code&scope=snsapi_base&state=${state}`;
  97. throw "stop";
  98. },
  99. // #endif
  100. // #ifdef APP-PLUS
  101. // 微信开放平台登录
  102. wxOpenPlatformOauth(event = "login") {
  103. let that = this;
  104. return new Promise((resolve, reject) => {
  105. uni.login({
  106. provider: "weixin",
  107. success: function(loginRes) {
  108. if (loginRes.errMsg === "login:ok") {
  109. let authResult = loginRes.authResult;
  110. api("user.wxOpenPlatformOauth", {
  111. authResult,
  112. event
  113. }, that.eventMap(event)).then(res => {
  114. if (res.code === 1) {
  115. resolve(res.data.token);
  116. } else {
  117. resolve(false);
  118. }
  119. });
  120. }
  121. },
  122. fail: function(res) {
  123. uni.showToast({
  124. title: "登录失败,请稍后再试"
  125. });
  126. resolve(false);
  127. api("common.debug", {
  128. info: res
  129. });
  130. },
  131. complete: function(res) {}
  132. });
  133. });
  134. },
  135. // #endif
  136. // #ifdef MP-WEIXIN
  137. // 微信小程序静默登录
  138. async getWxMiniProgramSessionKey(autoLogin = true) {
  139. let sessionStatus = false;
  140. let session_key = "";
  141. return new Promise((resolve, reject) => {
  142. uni.checkSession({
  143. success(res) {
  144. if (res.errMsg === "checkSession:ok") sessionStatus = true;
  145. },
  146. complete() {
  147. // console.log(uni.getStorageSync("session_key"))
  148. if (uni.getStorageSync("session_key") && sessionStatus && !autoLogin) {
  149. resolve(uni.getStorageSync("session_key"));
  150. } else {
  151. uni.login({
  152. success: function(info) {
  153. let code = info.code;
  154. api("wechat.miniappSilenceAuth", {
  155. code: code
  156. }).then(res => {
  157. if (res.code === 0) {
  158. uni.setStorageSync("session_key", res
  159. .data.session_key);
  160. if (autoLogin) {
  161. if (res.data.token) {
  162. resolve(res.data.token);
  163. } else {
  164. resolve(false);
  165. }
  166. }
  167. resolve(res.data.session_key);
  168. } else {
  169. reject(res.msg);
  170. }
  171. });
  172. }
  173. });
  174. }
  175. }
  176. });
  177. });
  178. },
  179. // 微信小程序获取用户信息登录
  180. wxMiniProgramOauth(event = "login") {
  181. let that = this;
  182. let session_key = uni.getStorageSync("session_key");
  183. uni.showLoading({
  184. title: that.eventMap(event)
  185. });
  186. return new Promise((resolve, reject) => {
  187. uni.getUserProfile({ // 必须手动确认触发
  188. desc: "展示用户头像昵称", // 声明获取用户个人信息后的用途,后续会展示在弹窗中,请谨慎填写
  189. success: res => {
  190. // console.log(res);
  191. if (res.errMsg === "getUserProfile:ok") {
  192. api("wechat.miniapp_auth", {
  193. event,
  194. session_key,
  195. encryptedData: res.encryptedData,
  196. iv: res.iv,
  197. signature: res.signature,
  198. }).then(res => {
  199. // console.log(res)
  200. if (res.code === 0) {
  201. uni.setStorageSync('isLogin',true)
  202. // store.commit('isLogin', true);
  203. store.dispatch('getUserInfo')
  204. resolve(res.data.token);
  205. } else {
  206. uni.removeStorageSync("session_key");
  207. that.getWxMiniProgramSessionKey(false);
  208. resolve(false);
  209. }
  210. });
  211. // console.log(res)
  212. resolve(res.userInfo);
  213. }
  214. },
  215. complete: res => {
  216. uni.hideLoading();
  217. if(res.errMsg === "getUserProfile:fail auth deny"){
  218. resolve(res);
  219. uni.showToast({
  220. title:'获取头像昵称失败',
  221. icon:'none'
  222. })
  223. }
  224. }
  225. });
  226. });
  227. },
  228. getPhoneNumber(e){
  229. let that = this;
  230. let session_key = uni.getStorageSync("session_key");
  231. // console.log(e)
  232. return new Promise((resolve, reject) => {
  233. api("wechat.authBindindPhone", {
  234. encryptedData: e.encryptedData,
  235. iv:e.iv,
  236. session_key,
  237. // client:'yuesao'
  238. }).then(ress => {
  239. if(ress.code === 0){
  240. resolve(ress)
  241. }else{
  242. uni.showToast({
  243. title:'登录失败',
  244. icon:'none'
  245. })
  246. }
  247. });
  248. });
  249. },
  250. // 小程序更新
  251. checkMiniProgramUpdate() {
  252. if (uni.canIUse("getUpdateManager")) {
  253. const updateManager = uni.getUpdateManager();
  254. updateManager.onCheckForUpdate(function(res) {
  255. // 请求完新版本信息的回调
  256. if (res.hasUpdate) {
  257. updateManager.onUpdateReady(function() {
  258. uni.showModal({
  259. title: "更新提示",
  260. content: "新版本已经准备好,是否重启应用?",
  261. confirmColor:'#7728f5',
  262. success: function(res) {
  263. if (res.confirm) {
  264. // 新的版本已经下载好,调用 applyUpdate 应用新版本并重启
  265. updateManager.applyUpdate();
  266. }
  267. }
  268. });
  269. });
  270. updateManager.onUpdateFailed(function() {
  271. // 新的版本下载失败
  272. uni.showModal({
  273. title: "已经有新版本了哟~",
  274. confirmColor:'#7728f5',
  275. content: "新版本已经上线啦~,请您删除当前小程序,重新搜索打开哟~"
  276. });
  277. });
  278. }
  279. });
  280. }
  281. },
  282. // #endif
  283. };