index.vue 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493
  1. <template>
  2. <view style="z-index: 999;">
  3. <uni-popup ref="popup" :is-mask-click="false" borderRadius="10px 10px 0 0" background-color="#eee" @change="popupChange">
  4. <view class="popup-content">
  5. <view class="popup-content-close">
  6. <view class="icon" @tap="handleClose">
  7. <uni-icons
  8. type="closeempty"
  9. color="#999"
  10. size="24"
  11. />
  12. </view>
  13. </view>
  14. <view class="popup-content-main">
  15. <view class="popup-content-main-count">
  16. <view class="title">{{ title }}</view>
  17. <view class="pay">
  18. <uni-icons color="#000" type="icon-renminbi1688" size="16" custom-prefix="iconfont"></uni-icons>
  19. <view>{{ amount }}</view>
  20. </view>
  21. </view>
  22. <view class="popup-content-main-type">
  23. <view v-if="payTypeList?.length" class="card">
  24. <radio-group @change="radioChange">
  25. <label class="card-label" v-for="item in payTypeList" :key="item.value">
  26. <view class="name">
  27. <uni-icons :color="item.color" class="mr-1" :type="item.icon" size="24" custom-prefix="iconfont"></uni-icons>
  28. {{item.name}}
  29. </view>
  30. <view>
  31. <radio :value="item.value" :disabled="item.disabled" :checked="item.value === channelValue" />
  32. </view>
  33. </label>
  34. </radio-group>
  35. </view>
  36. </view>
  37. </view>
  38. <view class="popup-content-btn">
  39. <button class="popup-content-btn-s" @tap="handlePay(false)">
  40. 确认支付
  41. <uni-icons color="#FFF" type="icon-renminbi1688" size="16" custom-prefix="iconfont"></uni-icons>
  42. {{ amount }}
  43. </button>
  44. </view>
  45. </view>
  46. </uni-popup>
  47. </view>
  48. </template>
  49. <script setup>
  50. import { ref } from 'vue'
  51. import { onHide, onShow } from '@dcloudio/uni-app'
  52. // import { userStore } from '@/store/user'; const useUserStore = userStore()
  53. import { getSocialUser, socialUserBind, payOrderSubmit, getOrderPayStatus, getEnableCodeList } from '@/api/common'
  54. import { createTradeOrder, getUnpaidOrder } from '@/api/new/position'
  55. const emit = defineEmits(['paySuccess', 'close'])
  56. const props = defineProps({
  57. title: { // 标题
  58. type: String,
  59. default: '支付'
  60. },
  61. tabBar: { // 页面底部导航菜单栏控制
  62. type: Boolean,
  63. default: true
  64. },
  65. })
  66. const payType = [
  67. {
  68. name: '微信支付',
  69. value: 'wx_lite',
  70. icon: 'icon-weixinzhifu',
  71. color: '#1AAD19'
  72. },
  73. // {
  74. // name: '钱包支付',
  75. // value: 'wallet',
  76. // disabled: true,
  77. // icon: 'icon-qianbao1',
  78. // color: '#00B760'
  79. // }
  80. ]
  81. // 余额和其他还没有接暂时只支持微信支付
  82. const payTypeList = ref([])
  83. // 获取支付方式
  84. const getPayMethodsList = async () => {
  85. console.log('获取支付方式列表')
  86. payTypeList.value = []
  87. try {
  88. const res = await getEnableCodeList({appId: 10})
  89. if (!res?.data?.length) {
  90. return
  91. }
  92. payTypeList.value.push(...payType.filter(e => res.data.includes(e.value)))
  93. const result = payType.find(item => !item.disabled && item.value)
  94. if (result) channelValue.value = result.value
  95. } catch (error) {
  96. console.log(error)
  97. }
  98. }
  99. const channelValue = ref('')
  100. const radioChange = (e) => {
  101. channelValue.value = e?.detail?.value || ''
  102. }
  103. const query = ref(null)
  104. const amount = ref('') // 支付金额
  105. const handleOpen = async (val) => {
  106. console.log('打开支付popup')
  107. await getPayMethodsList()
  108. query.value = val
  109. amount.value = Number(val?.price) ? Number(val?.price)/100 : 0
  110. popup.value.open('bottom')
  111. }
  112. // 设置 openid 到本地存储,目前只有 pay 支付时会使用
  113. const setOpenid = (openid) => {
  114. uni.setStorageSync('openid', openid)
  115. }
  116. const bind = () => {
  117. return new Promise(async (resolve, reject) => {
  118. // 1. 获得微信 code
  119. const codeResult = await uni.login()
  120. if (codeResult.errMsg !== 'login:ok') {
  121. return resolve(false)
  122. }
  123. // 2. 绑定账号 // // 社交快捷登录
  124. const obj = {
  125. type: socialType,
  126. code: codeResult.code,
  127. state: 'default',
  128. }
  129. const bindResult = await socialUserBind(obj);
  130. if (bindResult.code === 0) {
  131. setOpenid(bindResult.data)
  132. return resolve(true)
  133. } else {
  134. return resolve(false)
  135. }
  136. })
  137. }
  138. const bindWeiXin = () => {
  139. uni.showModal({
  140. title: '微信支付',
  141. content: '请先绑定微信再使用微信支付',
  142. success: function (res) {
  143. if (res.confirm) {
  144. // 微信小程序绑定
  145. bind()
  146. }
  147. },
  148. });
  149. }
  150. const socialType = 34; // 社交类型 - 微信小程序
  151. // 预支付
  152. const prepay = async (channel, orderData) => {
  153. console.log('微信预支付')
  154. return new Promise(async (resolve, reject) => {
  155. let data = {
  156. id: orderData?.payOrder?.id,
  157. channelCode: channel,
  158. channelExtras: {},
  159. };
  160. // 特殊逻辑:微信公众号、小程序支付时,必须传入 openid
  161. if (['wx_pub', 'wx_lite'].includes(channel)) {
  162. const userRes = await getSocialUser(socialType)
  163. const openid = userRes?.data?.openid ? userRes.data.openid : null
  164. // 如果获取不到 openid,微信无法发起支付,此时需要引导
  165. if (!openid) {
  166. bindWeiXin()
  167. return
  168. }
  169. data.channelExtras.openid = openid
  170. }
  171. // 发起预支付 API 调用
  172. payOrderSubmit(data).then((res) => {
  173. // 成功时
  174. res.code === 0 && resolve(res)
  175. // 失败时
  176. if (res.code !== 0 && res.msg.indexOf('无效的openid') >= 0) {
  177. // 特殊逻辑:微信公众号、小程序支付时,必须传入 openid 不正确的情况
  178. if (
  179. res.msg.indexOf('无效的openid') >= 0 || // 获取的 openid 不正确时,或者随便输入了个 openid
  180. res.msg.indexOf('下单账号与支付账号不一致') >= 0
  181. ) {
  182. bindWeiXin()
  183. }
  184. }
  185. })
  186. })
  187. }
  188. let interTimer = null
  189. let payLoading = false
  190. const checkPayStatus = async (id) => {
  191. console.log('进入轮询订单状态')
  192. if (pageHide.value) {
  193. console.log('轮询支付状态:页面隐藏:return')
  194. return
  195. }
  196. if (!id) return
  197. uni.showLoading({ title: '加载中' })
  198. try {
  199. if (payLoading || !interTimer) return
  200. payLoading = true
  201. const res = await getOrderPayStatus({ id })
  202. if (res?.data?.status === 10) {
  203. console.log('轮询订单状态:支付成功')
  204. if (interTimer) clearInterval(interTimer); interTimer = null
  205. // uni.showToast({ title: '支付成功', icon: 'none'})
  206. popup.value.close()
  207. setTimeout(async () => {
  208. emit('paySuccess')
  209. }, 1500)
  210. }
  211. } catch (error) {
  212. console.log('轮询订单状态报错:error', error)
  213. if (interTimer) clearInterval(interTimer)
  214. } finally {
  215. payLoading = false
  216. uni.hideLoading()
  217. }
  218. }
  219. // 轮询订单状态
  220. const initIntervalFun = () => {
  221. console.log('开启轮询订单状态')
  222. if (interTimer) clearInterval(interTimer)
  223. // 查询是否已经支付
  224. const id = orderInfo.value?.payOrder?.id || orderInfo.value?.order?.payOrderId
  225. if (id) {
  226. interTimer = setInterval(() => {
  227. checkPayStatus(id)
  228. }, 1000)
  229. }
  230. }
  231. const orderInfo = ref({})
  232. const weChatMiniProgramPay = async () => {
  233. let res = await prepay(channelValue.value, orderInfo.value); // 预支付
  234. if (res?.code !== 0) {
  235. return;
  236. }
  237. // 调用微信小程序支付
  238. console.log('调用微信小程序支付打印')
  239. const payConfig = res?.data?.displayContent ? JSON.parse(res.data.displayContent) : null
  240. if (!payConfig) return uni.showToast({ title: '购买失败', icon: 'none'})
  241. uni.requestPayment({
  242. provider: 'wxpay',
  243. timeStamp: payConfig.timeStamp,
  244. nonceStr: payConfig.nonceStr,
  245. package: payConfig.packageValue,
  246. signType: 'RSA',
  247. paySign: payConfig.paySign,
  248. success: (res) => {
  249. // 用户支付成功
  250. console.log('用户支付成功success打印')
  251. initIntervalFun() // 轮询订单状态
  252. },
  253. fail: (err) => {
  254. if (err.errMsg === 'requestPayment:fail cancel') {
  255. uni.showToast({ title: '支付已取消', icon: 'none'})
  256. } else {
  257. uni.showToast({ title: '支付失败', icon: 'none'})
  258. }
  259. },
  260. });
  261. }
  262. // 确认支付按钮
  263. const handlePay = async (retry = false) => {
  264. console.log('点击确认支付按钮')
  265. if (!channelValue.value) {
  266. uni.showToast({ title: '请选择支付方式', icon: 'none'})
  267. return
  268. }
  269. // 判断是否已有创建好的订单,有就直接跳转支付,没有就创建订单
  270. try {
  271. const params = {
  272. spuId: query.value?.spuId, // 商品编号
  273. type: query.value?.type // 订单类型 0平台订单|1发布职位|2发布众聘职位|3会员套餐|4企业会员套餐|5招聘会门票
  274. }
  275. if (!params.spuId || params.type === null || params.type === undefined) return
  276. const res = await getUnpaidOrder(params) // 1.查询订单
  277. if (res?.data) {
  278. orderInfo.value = res.data
  279. // 微信小程序支付
  280. weChatMiniProgramPay(res.data)
  281. return
  282. }
  283. if (!retry) setOrderCreated() // 2.创建订单
  284. } catch (error) {
  285. console.log(error)
  286. }
  287. }
  288. // 创建订单
  289. const setOrderCreated = async () => {
  290. const params = {
  291. spuId: query.value?.spuId, // 商品编号
  292. type: query.value?.type, // 订单类型 0平台订单|1发布职位|2发布众聘职位|3会员套餐|4企业会员套餐|5招聘会门票
  293. price: query.value?.price, // 价格
  294. spuName: query.value?.spuName, // 商品名称
  295. }
  296. if (!params.spuId || params.type === null || params.type === undefined || !params.price || !params.spuName) return
  297. await createTradeOrder(params)
  298. handlePay(true) // 避免死循环
  299. }
  300. const popup = ref()
  301. const handleClose = () => { // 手动关闭emit
  302. console.log('手动关闭')
  303. popup.value.close()
  304. emit('close')
  305. }
  306. const tabBarControl = (show = false) => { // 显示/隐藏 TabBar
  307. console.log('TabBar:', show ? '展示' : '隐藏')
  308. const currentPage = getCurrentPages()
  309. if (!currentPage) return
  310. const currentTabBar = currentPage[0]?.getTabBar?.()
  311. currentTabBar?.setData({ show })
  312. }
  313. // 显示/隐藏 TabBar
  314. const popupChange = (e) => {
  315. console.log('popupChange支付弹窗状态', e)
  316. if (!e || e.show === undefined) return
  317. if (!props.tabBar) return // 页面没有底部导航菜单栏
  318. if (e.show) {
  319. // 支付弹窗打开
  320. tabBarControl(false)
  321. } else {
  322. // 支付弹窗关闭
  323. tabBarControl(true)
  324. }
  325. }
  326. const pageHide = ref(false)
  327. onShow(() => {
  328. pageHide.value = false
  329. })
  330. onHide(() => {
  331. pageHide.value = true // 支付的时候会AppHide,不能清空轮询
  332. popup.value.close()
  333. })
  334. defineExpose({
  335. handleOpen
  336. })
  337. </script>
  338. <style lang="scss" scoped>
  339. .pay {
  340. position: sticky;
  341. bottom: 0;
  342. padding: 0 40rpx 50rpx 40rpx;
  343. box-sizing: border-box;
  344. &-box {
  345. width: 100%;
  346. background: linear-gradient(121deg,#fde2c2 29.02%,#c19164 104.03%);
  347. border-radius: 180rpx 0 180rpx 0;
  348. box-shadow: 3rpx 6rpx 10rpx 0rpx rgb(216 160 82);
  349. display: flex;
  350. justify-content: space-between;
  351. align-items: center;
  352. height: 100rpx;
  353. .price {
  354. padding: 0 40rpx;
  355. font-size: 40rpx;
  356. font-weight: 600;
  357. color: #e68735;
  358. }
  359. .btn {
  360. height: 100%;
  361. display: flex;
  362. align-items: center;
  363. padding: 0 40rpx;
  364. border: 2rpx solid #00B760;
  365. background: #00B760;
  366. color: #FFF;
  367. border-radius: 180rpx 0 180rpx 0;
  368. position: relative;
  369. // &::after {
  370. // content: '';
  371. // position: absolute;
  372. // width: 50rpx;
  373. // height: 50rpx;
  374. // background: radial-gradient(top right, transparent 50%, #00B760 50%);
  375. // left: 0;
  376. // top: 0;
  377. // margin-left: -25rpx;
  378. // border-radius: 180rpx;
  379. // }
  380. }
  381. }
  382. }
  383. .popup-content {
  384. z-index: 999;
  385. max-height: 500px;
  386. display: flex;
  387. flex-direction: column;
  388. &-close {
  389. display: flex;
  390. padding: 10px;
  391. justify-content: flex-end;
  392. .icon {
  393. width: 30px;
  394. height: 30px;
  395. background: #ccc;
  396. border-radius: 30px;
  397. display: flex;
  398. align-items: center;
  399. justify-content: center;
  400. }
  401. }
  402. &-main {
  403. flex: 1;
  404. height: 0;
  405. overflow-y: auto;
  406. &-count {
  407. margin-bottom: 20px;
  408. text-align: center;
  409. .title {
  410. font-size: 28rpx;
  411. color: #666
  412. }
  413. .pay {
  414. font-size: 52rpx;
  415. color: #000;
  416. font-weight: 600;
  417. display: flex;
  418. align-items: center;
  419. justify-content: center;
  420. padding: 10px 0;
  421. }
  422. }
  423. &-type {
  424. width: 100%;
  425. padding: 0 20px;
  426. box-sizing: border-box;
  427. .card {
  428. border-radius: 10px;
  429. margin: 0 auto;
  430. background: #FFF;
  431. padding: 10px;
  432. &-label {
  433. padding: 15px 0;
  434. box-sizing: border-box;
  435. display: flex;
  436. justify-content: space-between;
  437. border-bottom: 1px solid #eee;
  438. &:last-of-type {
  439. border-bottom: none;
  440. }
  441. .name {
  442. display: flex;
  443. align-items: center;
  444. color: #333;
  445. }
  446. }
  447. }
  448. }
  449. }
  450. &-btn {
  451. height: 70px;
  452. width: 100%;
  453. margin-top: 10px;
  454. display: flex;
  455. align-items: center;
  456. justify-content: center;
  457. &-s {
  458. height: 40px;
  459. width: 75%;
  460. line-height: 40px;
  461. color: #FFF;
  462. // color: #724d2b;
  463. background: #00B760;
  464. // background: linear-gradient(121deg,#fde2c2 29.02%,#c19164 104.03%);
  465. border-radius: 90px;
  466. }
  467. }
  468. }
  469. .mr-1 {
  470. margin-right: 10px;
  471. }
  472. </style>