百搜论坛欢迎您的加入!
adimg adimg
 
昨日:篇  今日:篇   总帖:篇   会员:
CRMEBLv12 
crmeb多商户系统适配最新小程序授权方案     

微信小程序官方关于登录、授权接口做了相应调整,对应多商户系统需修改如下位置:


对照下图修改对应文件中的代码:http://github.crmeb.net/u/defu

Uni-app按下图修改

Image


最终修改后的完整代码


<template>

        <view>

                <view class='Popup' v-if='isShowAuth'>

                        <view class="logo-auth">

                                <image :src='logoUrl' mode="aspectFit"></image>

                        </view>

                        <view class='title'>授权提醒</view>

                        <view class='tip'>请授权头像等信息,以便为您提供更好的服务</view>

                        <view class='bottom flex'>

                                <view class='item' @click='close'>随便逛逛</view>

                                <!-- #ifdef APP-PLUS -->

                                <button class='item grant' @click="setUserInfo">去授权</button>

                                <!-- #endif -->

                                <!-- #ifdef MP -->

                                <button v-if="canUseGetUserProfile" class="item grant" hover-class="none" @tap="getUserProfile">去授权</button>

                                <button v-else class='item grant' type="primary" open-type="getUserInfo" lang="zh_CN" @getuserinfo="setUserInfo">去授权</button>

                                <!-- #endif -->

                        </view>

                </view>

                <view class='mask' v-if='isShowAuth' @click='close'></view>

        </view>

</template>


<script>

        const app = getApp();

        import Cache from '../utils/cache';

        import {

                getLogo

        } from '../api/public';

        import {

                LOGO_URL

        } from '../config/cache';

        import {

                mapGetters

        } from 'vuex';

        import Routine from '../libs/routine';


        export default {

                name: 'Authorize',

                props: {

                        isAuto: {

                                type: Boolean,

                                default: true

                        },

                        isGoIndex: {

                                type: Boolean,

                                default: true

                        },

                        isShowAuth: {

                                type: Boolean,

                                default: false

                        }

                },

                data() {

                        return {

                                logoUrl: app.globalData.routine_logo,

                                canUseGetUserProfile: false

                        }

                },

                computed: mapGetters(['isLogin', 'userInfo']),

                watch: {

                        isLogin(n) {

                                n === true && this.$emit('onLoadFun', this.userInfo);

                        }

                },

                created() {

                        if (uni.getUserProfile) {

                                this.canUseGetUserProfile = true

                        }

                        this.getLogoUrl();

                        this.setAuthStatus();

                        uni.$on('update', (data) => {

                                this.logoUrl = data.login_logo

                        })

                },

                mounted: function() {

                        this.$nextTick(() => {

                                this.logoUrl = app.globalData.login_logo

                        });

                },

                methods: {

                        setAuthStatus() {

                                Routine.authorize().then(res => {

                                        if (res.islogin === false)

                                                this.setUserInfo();

                                        else

                                                this.$emit('onLoadFun', this.userInfo);

                                }).catch(res => {

                                        if (this.isAuto)

                                                this.$emit('authColse', true);

                                })

                        },

                        getUserInfo(code) {

                                Routine.getUserInfo().then(res => {

                                        let userInfo = res.userInfo

                                        userInfo.code = code;

                                        userInfo.spread_spid = this.$Cache.get("spread") || app.globalData.spid; //获取推广人ID

                                        userInfo.spread_code = app.globalData.code; //获取推广人分享二维码ID

                                        console.log(this.$Cache.get("spread"))

                                        Routine.authUserInfo(userInfo).then(res => {

                                                uni.hideLoading();

                                                this.$emit('authColse', false);

                                                this.$emit('onLoadFun', this.userInfo);

                                        }).catch(res => {

                                                uni.hideLoading();

                                                uni.showToast({

                                                        title: res.msg,

                                                        icon: 'none',

                                                        duration: 2000

                                                });

                                        })

                                }).catch(res => {

                                        uni.hideLoading();

                                })

                        },

                        getUserProfile() {

                                let self = this;

                                Routine.getUserProfile()

                                              .then(res => {

                                                   Routine.getCode()

                                                    .then(code => {

                                                              let userInfo = res.userInfo;

                                                              userInfo.code = code;

                                                              userInfo.spread_spid = app.globalData.spid; //获取推广人ID

                                                              userInfo.spread_code = app.globalData.code; //获取推广人分享二维码ID

                                                              Routine.authUserInfo(userInfo)

                                                                    .then(res => {

                                                                              if (res.data.key !== undefined && res.data.key) {

                                                                                    uni.hideLoading();

                                                                                    self.authKey = res.data.key;

                                                                                    self.isPhoneBox = true;

                                                                                } else {

                                                                                        uni.hideLoading();

                                                                                        let time = res.data.expires_time - self.$Cache.time();

                                                                                        self.$store.commit('LOGIN', {

                                                                                              token: res.data.token,

                                                                                                      time: time

                                                                                                  });

                                                                                     this.getUserInfo()

                                                                                 }

                                                                    })

                                                      .catch(res => {

                                                             uni.hideLoading();

                                                             uni.showToast({

                                                             title: res.msg,

                                                             icon: 'none',

                                                             duration: 2000

                                                                   });

                                                                });

                                                            })

                                                        .catch(res => {

                                                               uni.hideLoading();

                                          });

                             })

                                                                 .catch(res => {

                                                                         uni.hideLoading();

                                                                 });

                                                 },


                        setUserInfo() {

                                uni.showLoading({

                                        title: '正在登录中'

                                });

                                Routine.getCode().then(code => {

                                        this.getUserInfo(code);

                                        this.$emit('authColse', false);

                                }).catch(res => {

                                        uni.hideLoading();

                                })

                        },

                        getLogoUrl() {

                                this.logoUrl = app.globalData.routine_logo

                                // let that = this;

                                // if (Cache.has(LOGO_URL)) {

                                //         this.logoUrl = Cache.get(LOGO_URL);

                                //         return;

                                // }

                                // getLogo().then(res=>{

                                //         that.logoUrl = res.data.logo_url

                                //         Cache.set(LOGO_URL,that.logoUrl);

                                // })

                        },

                        close() {

                                let pages = getCurrentPages(),

                                        currPage = pages[pages.length - 1];

                                if (this.isGoIndex) {

                                        uni.switchTab({

                                                url: '/pages/index/index'

                                        });

                                } else {

                                        this.$emit('authColse', false);

                                }

                                // if (currPage && currPage.isShowAuth != undefined){

                                //         currPage.isShowAuth = true;

                                // }

                        },

                }

        }

</script>


<style scoped lang='scss'>

        .Popup {

                width: 500rpx;

                background-color: #fff;

                position: fixed;

                top: 50%;

                left: 50%;

                margin-left: -250rpx;

                transform: translateY(-50%);

                z-index: 1000;

        }


        .Popup {

                .logo-auth {

                        z-index: -1;

                        position: absolute;

                        left: 50%;

                        top: 0%;

                        transform: translate(-50%, -50%);

                        width: 150rpx;

                        height: 150rpx;

                        display: flex;

                        align-items: center;

                        justify-content: center;

                        border: 8rpx solid #fff;

                        border-radius: 50%;

                        background: #fff;

                }


                image {

                        height: 42rpx;

                        margin-top: -54rpx;

                }

        }


        .Popup .title {

                font-size: 28rpx;

                color: #000;

                text-align: center;

                margin-top: 30rpx

        }


        .Popup .tip {

                font-size: 22rpx;

                color: #555;

                padding: 0 24rpx;

                margin-top: 25rpx;

        }


        .Popup .bottom .item {

                width: 50%;

                height: 80rpx;

                background-color: #eeeeee;

                text-align: center;

                line-height: 80rpx;

                font-size: 24rpx;

                color: #666;

                margin-top: 54rpx;

        }


        .Popup .bottom .item.on {

                width: 100%

        }


        .flex {

                display: flex;

        }


        .Popup .bottom .item.grant {

                font-size: 28rpx;

                color: #fff;

                font-weight: bold;

                background-color: #e93323;

                border-radius: 0;

                padding: 0;

        }


        .mask {

                position: fixed;

                top: 0;

                right: 0;

                left: 0;

                bottom: 0;

                background-color: rgba(0, 0, 0, 0.65);

                z-index: 999;

        }

</style>

Image


getUserProfile(code) {

                return new Promise((resolve, reject) => {

                        uni.getUserProfile({

                                lang: 'zh_CN',

                                desc: '用于完善会员资料', // 声明获取用户个人信息后的用途,后续会展示在弹窗中,请谨慎填写

                                success(user) {

                                        if (code) user.code = code;

                                        resolve({

                                                userInfo: user,

                                                islogin: false

                                        });

                                },

                                fail(res) {

                                        reject(res);

                                }

                        })

                })

        }






按照下图修改后端 php 代码

Image

public function mpAuth()

    {

        list($code, $post_cache_key) = $this->request->params([

            'code',

            'cache_key',

        ], true);

        $session_key = Cache::get('eb_api_code_' . $post_cache_key);

        if (!$code && !$session_key)

            return app('json')->fail('授权失败,参数有误');

        $miniProgramService = MiniProgramService::create();

        if ($code && !$session_key) {

            try {

                $userInfoCong = $miniProgramService->getUserInfo($code);

                $session_key = $userInfoCong['session_key'];

                $cache_key = md5(time() . $code);

                Cache::set('eb_api_code_' . $cache_key, $session_key, 86400);

            } catch (Exception $e) {

                return app('json')->fail('获取session_key失败,请检查您的配置!', ['line' => $e->getLine(), 'message' => $e->getMessage()]);

            }

        }


        $data = $this->request->params([

            ['spread_spid', 0],

            ['spread_code', ''],

            ['iv', ''],

            ['encryptedData', ''],

        ]);


        try {

            //解密获取用户信息

            $userInfo = $miniProgramService->encryptor($session_key, $data['iv'], $data['encryptedData']);

        } catch (Exception $e) {

            if ($e->getCode() == '-41003') return app('json')->fail('获取会话密匙失败');

            throw $e;

        }

        if (!$userInfo) return app('json')->fail('openid获取失败');

        if (!isset($userInfo['openId'])) $userInfo['openId'] = $userInfoCong['openid'] ?? '';

        if (!$userInfo['openId']) return app('json')->fail('openid获取失败');

        if (!isset($userInfo['unionId'])) $userInfo['unionId'] = '';


        /** @var WechatUserRepository $make */

        $make = app()->make(WechatUserRepository::class);

        $user = $make->syncRoutineUser($userInfo['openId'], $userInfo);

        if (!$user)

            return app('json')->fail('授权失败');

        /** @var UserRepository $make */

        $userRepository = app()->make(UserRepository::class);

        $user[1] = $userRepository->mainUser($user[1]);

        $code = intval($data['spread_code']['id'] ?? $data['spread_code']);

        //获取是否有扫码进小程序

        if ($code && ($info = app()->make(RoutineQrcodeRepository::class)->getRoutineQrcodeFindType($code))) {

            $data['spread_spid'] = $info['third_id'];

        }

        $userRepository->bindSpread($user[1], intval($data['spread_spid']));

        $tokenInfo = $userRepository->createToken($user[1]);

        $userRepository->loginAfter($user[1]);


        return app('json')->success($userRepository->returnToken($user[1], $tokenInfo));

}


按照上文修改完毕后重启 swoole,然后重新提交小程序审核发布


微信官方接口更新详情:

https://developers.weixin.qq.com/community/develop/doc/000cacfa20ce88df04cb468b

c52801?idescene=6

 0  已被阅读了1304次  楼主 2021-04-13 15:28:12
回复列表

回复:crmeb多商户系统适配最新小程序授权方案

联系站长 友链申请桂ICP备19000949号-1     桂ICP备19000949号-1
您的IP:3.144.127.232,2024-04-26 12:45:42,Processed in 0.01922 second(s).
免责声明: 本网不承担任何由内容提供商提供的信息所引起的争议和法律责任。
Powered by HadSky 7.12.9
已有0次打赏
(0) 分享
分享
取消
免责声明
1、本站资源,均来自网络,版权归原作者,所有资源和文章仅限用于学习和研究目的 。
2、不得用于商业或非法用途,否则,一切责任由该用户承担 !
如果觉得本文还不错请点个赞或者打赏点轻币哦~
拒绝伸手党,拿走请回复,尊重楼主,尊重你我他~

侵权删除请致信 E-Mail:207882320@qq.com