wechat.js 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327
  1. // +----------------------------------------------------------------------
  2. // | CRMEB [ CRMEB赋能开发者,助力企业发展 ]
  3. // +----------------------------------------------------------------------
  4. // | Copyright (c) 2016~2021 https://www.crmeb.com All rights reserved.
  5. // +----------------------------------------------------------------------
  6. // | Licensed CRMEB并不是自由软件,未经许可不能去掉CRMEB相关版权
  7. // +----------------------------------------------------------------------
  8. // | Author: CRMEB Team <admin@crmeb.com>
  9. // +----------------------------------------------------------------------
  10. // #ifdef H5
  11. import WechatJSSDK from "@/plugin/jweixin-module/index.js";
  12. import {
  13. getWechatConfig,
  14. wechatAuth,
  15. getShopConfig,
  16. wechatAuthV2
  17. } from "@/api/public";
  18. import {
  19. WX_AUTH,
  20. STATE_KEY,
  21. LOGINTYPE,
  22. BACK_URL
  23. } from '@/config/cache';
  24. import {
  25. parseQuery
  26. } from '@/utils';
  27. import store from '@/store';
  28. import Cache from '@/utils/cache';
  29. class AuthWechat {
  30. constructor() {
  31. //微信实例化对象
  32. this.instance = WechatJSSDK;
  33. //是否实例化
  34. this.status = false;
  35. this.initConfig = {};
  36. }
  37. isAndroid(){
  38. let u = navigator.userAgent;
  39. return u.indexOf('Android') > -1 || u.indexOf('Adr') > -1;
  40. }
  41. signLink() {
  42. if (typeof window.entryUrl === 'undefined' || window.entryUrl === '') {
  43. window.entryUrl = document.location.href
  44. }
  45. return /(Android)/i.test(navigator.userAgent) ? document.location.href : window.entryUrl;
  46. }
  47. /**
  48. * 初始化wechat(分享配置)
  49. */
  50. wechat() {
  51. return new Promise((resolve, reject) => {
  52. // if (this.status && !this.isAndroid()) return resolve(this.instance);
  53. getWechatConfig()
  54. .then(res => {
  55. this.instance.config(res.data);
  56. this.initConfig = res.data;
  57. this.status = true;
  58. this.instance.ready(() => {
  59. resolve(this.instance);
  60. })
  61. }).catch(err => {
  62. this.status = false;
  63. reject(err);
  64. });
  65. });
  66. }
  67. /**
  68. * 验证是否初始化
  69. */
  70. verifyInstance() {
  71. let that = this;
  72. return new Promise((resolve, reject) => {
  73. if (that.instance === null && !that.status) {
  74. that.wechat().then(res => {
  75. resolve(that.instance);
  76. }).catch(() => {
  77. return reject();
  78. })
  79. } else {
  80. return resolve(that.instance);
  81. }
  82. })
  83. }
  84. // 微信公众号的共享地址
  85. openAddress() {
  86. return new Promise((resolve, reject) => {
  87. this.wechat().then(wx => {
  88. this.toPromise(wx.openAddress).then(res => {
  89. resolve(res);
  90. }).catch(err => {
  91. reject(err);
  92. });
  93. }).catch(err => {
  94. reject(err);
  95. })
  96. });
  97. }
  98. // 获取经纬度;
  99. location(){
  100. return new Promise((resolve, reject) => {
  101. this.wechat().then(wx => {
  102. this.toPromise(wx.getLocation,{type: 'wgs84'}).then(res => {
  103. resolve(res);
  104. }).catch(err => {
  105. reject(err);
  106. });
  107. }).catch(err => {
  108. reject(err);
  109. })
  110. });
  111. }
  112. // 使用微信内置地图查看位置接口;
  113. seeLocation(config){
  114. return new Promise((resolve, reject) => {
  115. this.wechat().then(wx => {
  116. this.toPromise(wx.openLocation, config).then(res => {
  117. resolve(res);
  118. }).catch(err => {
  119. reject(err);
  120. });
  121. }).catch(err => {
  122. reject(err);
  123. })
  124. });
  125. }
  126. /**
  127. * 微信支付
  128. * @param {Object} config
  129. */
  130. pay(config) {
  131. return new Promise((resolve, reject) => {
  132. this.wechat().then((wx) => {
  133. this.toPromise(wx.chooseWXPay, config).then(res => {
  134. resolve(res);
  135. }).catch(res => {
  136. reject(res);
  137. });
  138. }).catch(res => {
  139. reject(res);
  140. });
  141. });
  142. }
  143. toPromise(fn, config = {}) {
  144. return new Promise((resolve, reject) => {
  145. fn({
  146. ...config,
  147. success(res) {
  148. resolve(res);
  149. },
  150. fail(err) {
  151. reject(err);
  152. },
  153. complete(err) {
  154. reject(err);
  155. },
  156. cancel(err) {
  157. reject(err);
  158. }
  159. });
  160. });
  161. }
  162. /**
  163. * 自动去授权
  164. */
  165. oAuth(snsapiBase,url) {
  166. if(uni.getStorageSync('authIng'))return
  167. if (uni.getStorageSync(WX_AUTH) && store.state.app.token && snsapiBase == 'snsapi_base') return;
  168. let {
  169. code
  170. } = parseQuery();
  171. let snsapiCode = uni.getStorageSync('snsapiCode')
  172. if(code instanceof Array){
  173. code = code[code.length-1]
  174. }
  175. if(snsapiCode instanceof Array){
  176. snsapiCode = snsapiCode[snsapiCode.length-1]
  177. }
  178. if (!code || code == snsapiCode){
  179. uni.setStorageSync('authIng',true)
  180. return this.toAuth(snsapiBase,url);
  181. }else{
  182. if(Cache.has('snsapiKey'))
  183. return this.auth(code).catch(error=>{
  184. uni.showToast({
  185. title:error,
  186. icon:'none'
  187. })
  188. })
  189. }
  190. }
  191. clearAuthStatus() {
  192. }
  193. /**
  194. * 授权登陆获取token
  195. * @param {Object} code
  196. */
  197. auth(code) {
  198. return new Promise((resolve, reject) => {
  199. let loginType = Cache.get(LOGINTYPE);
  200. wechatAuthV2(code, parseInt(Cache.get("spread")))
  201. .then(({
  202. data
  203. }) => {
  204. // store.commit("LOGIN", {
  205. // token: data.token,
  206. // time: Cache.strTotime(data.expires_time) - Cache.time()
  207. // });
  208. // store.commit("SETUID", data.userInfo.uid);
  209. Cache.set(WX_AUTH, code);
  210. Cache.clear(STATE_KEY);
  211. resolve(data);
  212. })
  213. .catch(reject);
  214. });
  215. }
  216. /**
  217. * 获取跳转授权后的地址
  218. * @param {Object} appId
  219. */
  220. getAuthUrl(appId,snsapiBase,backUrl) {
  221. let url = `${location.origin}${backUrl}`
  222. if(url.indexOf('?') == -1){
  223. url = url+'?'
  224. }else{
  225. url = url+'&'
  226. }
  227. const redirect_uri = encodeURIComponent(
  228. `${url}scope=${snsapiBase}&back_url=` +
  229. encodeURIComponent(
  230. encodeURIComponent(
  231. uni.getStorageSync(BACK_URL) ?
  232. uni.getStorageSync(BACK_URL) :
  233. location.pathname + location.search
  234. )
  235. )
  236. );
  237. uni.removeStorageSync(BACK_URL);
  238. const state = encodeURIComponent(
  239. ("" + Math.random()).split(".")[1] + "authorizestate"
  240. );
  241. uni.setStorageSync(STATE_KEY, state);
  242. if(snsapiBase==='snsapi_base'){
  243. return `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appId}&redirect_uri=${redirect_uri}&response_type=code&scope=snsapi_base&state=${state}&connect_redirect=1#wechat_redirect`;
  244. }else{
  245. return `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appId}&redirect_uri=${redirect_uri}&response_type=code&scope=snsapi_userinfo&state=${state}&connect_redirect=1#wechat_redirect`;
  246. }
  247. }
  248. /**
  249. * 跳转自动登陆
  250. */
  251. toAuth(snsapiBase,backUrl) {
  252. let that = this;
  253. this.wechat().then(wx => {
  254. location.href = this.getAuthUrl(that.initConfig.appId,snsapiBase,backUrl);
  255. })
  256. }
  257. /**
  258. * 绑定事件
  259. * @param {Object} name 事件名
  260. * @param {Object} config 参数
  261. */
  262. wechatEvevt(name, config) {
  263. let that = this;
  264. return new Promise((resolve, reject) => {
  265. let configDefault = {
  266. fail(res) {
  267. if (that.instance) return reject({
  268. is_ready: true,
  269. wx: that.instance
  270. });
  271. that.verifyInstance().then(wx => {
  272. return reject({
  273. is_ready: true,
  274. wx: wx
  275. });
  276. })
  277. },
  278. success(res) {
  279. return resolve(res,2222);
  280. }
  281. };
  282. Object.assign(configDefault, config);
  283. that.wechat().then(wx => {
  284. if (typeof name === 'object') {
  285. name.forEach(item => {
  286. wx[item] && wx[item](configDefault)
  287. })
  288. } else {
  289. wx[name] && wx[name](configDefault)
  290. }
  291. })
  292. });
  293. }
  294. isWeixin() {
  295. return navigator.userAgent.toLowerCase().indexOf("micromessenger") !== -1;
  296. }
  297. }
  298. export default new AuthWechat();
  299. // #endif