wechat.js 7.3 KB

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