Skip to content

Commit

Permalink
微信小程序登录状态维护
Browse files Browse the repository at this point in the history
  • Loading branch information
shen100 committed Jun 10, 2017
1 parent 4defd69 commit 785e0c2
Show file tree
Hide file tree
Showing 8 changed files with 135 additions and 18 deletions.
7 changes: 6 additions & 1 deletion configuration.json
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@
"UploadImgDir" : "/Users/liushen/dev/upload/img", /*图片上传的目录*/
"ImgPath" : "/upload/img", /*上传后的图片请求地址前缀*/
"Port" : 8012, /*go监听的端口*/
"SessionID" : "iris.sid", /*后台设置的session id*/
"SessionID" : "sid", /*后台设置的session id*/
"MaxOrder" : 10000, /*最大的排序号*/
"MinOrder" : 0, /*最小的排序号*/
"PageSize" : 20, /*默认每页的条数*/
Expand All @@ -44,6 +44,11 @@
"MaxProductCateCount" : 6, /*商品最多的分类个数*/
"MaxProductImgCount" : 6 /*商品最多的图片集个数*/
},
"weApp": {
"LoginURL" : "https://api.weixin.qq.com/sns/jscode2session?appid={appid}&secret={secret}&js_code={code}&grant_type=authorization_code",
"AppID" : "",
"Secret" : ""
},
"software": {
"name" : "wemall微商城", /*软件名称*/
"version" : "1.0.0", /*软件版本*/
Expand Down
14 changes: 14 additions & 0 deletions go/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,19 @@ func initServer() {
utils.SetStructByJSON(&ServerConfig, jsonData["go"].(map[string]interface{}))
}

type weAppConfig struct {
LoginURL string
AppID string
Secret string
}

// WeAppConfig 微信小程序相关配置
var WeAppConfig weAppConfig

func initWeAppConfig() {
utils.SetStructByJSON(&WeAppConfig, jsonData["weApp"].(map[string]interface{}))
}

type apiConfig struct {
Prefix string
URL string
Expand All @@ -94,5 +107,6 @@ func init() {
initJSON()
initDB()
initServer()
initWeAppConfig()
initAPI()
}
77 changes: 77 additions & 0 deletions go/controller/user/user.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,89 @@ package user

import (
"fmt"
"net/http"
"strings"
"encoding/json"
"time"
"gopkg.in/kataras/iris.v6"
"wemall/go/config"
"wemall/go/model"
"wemall/go/utils"
)

// WeAppLogin 微信小程序登录
func WeAppLogin(ctx *iris.Context) {
code := ctx.FormValue("code")
if code == "" {
ctx.JSON(iris.StatusOK, iris.Map{
"errNo" : model.ErrorCode.ERROR,
"msg" : "code不能为空",
"data" : iris.Map{},
})
return
}
appID := config.WeAppConfig.AppID
secret := config.WeAppConfig.Secret
loginURL := config.WeAppConfig.LoginURL
loginURL = strings.Replace(loginURL, "{appid}", appID, -1)
loginURL = strings.Replace(loginURL, "{secret}", secret, -1)
loginURL = strings.Replace(loginURL, "{code}", code, -1)

resp, err := http.Get(loginURL)
if err != nil {
ctx.JSON(iris.StatusOK, iris.Map{
"errNo" : model.ErrorCode.ERROR,
"msg" : "error",
"data" : iris.Map{},
})
return
}

defer resp.Body.Close()

isErr := false

if resp.StatusCode != 200 {
isErr = true
}

var data map[string]interface{}
err = json.NewDecoder(resp.Body).Decode(&data)
if err != nil {
fmt.Println(err.Error())
isErr = true
}

if _, ok := data["session_key"]; !ok {
isErr = true
}

if isErr {
ctx.JSON(iris.StatusOK, iris.Map{
"errNo" : model.ErrorCode.ERROR,
"msg" : "error",
"data" : iris.Map{},
})
return
}

var openID string
var sessionKey string
openID = data["openid"].(string)
sessionKey = data["session_key"].(string)
session := ctx.Session()
session.Set("weAppOpenID", openID)
session.Set("weAppSessionKey", sessionKey)

resData := iris.Map{}
resData[config.ServerConfig.SessionID] = session.ID()
ctx.JSON(iris.StatusOK, iris.Map{
"errNo" : model.ErrorCode.SUCCESS,
"msg" : "success",
"data" : resData,
})
}

// YesterdayRegisterUser 昨日注册的用户数
func YesterdayRegisterUser(ctx *iris.Context) {
var user model.User;
Expand Down
1 change: 1 addition & 0 deletions go/route/route.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ func Route(app *iris.Framework) {

router := app.Party(apiPrefix)
{
router.Get("/weappLogin", user.WeAppLogin)
router.Get("/categories", category.List)
router.Get("/products", product.List)
router.Get("/product/:id", product.Info)
Expand Down
6 changes: 4 additions & 2 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package main
import (
"fmt"
"os"
"time"
"strconv"
_ "github.com/jinzhu/gorm/dialects/mysql"
"github.com/jinzhu/gorm"
Expand Down Expand Up @@ -41,12 +42,13 @@ func main() {
app.Adapt(iris.DevLogger())
}

app.Adapt(httprouter.New())

app.Adapt(sessions.New(sessions.Config{
Cookie: config.ServerConfig.SessionID,
Expires: time.Minute * 20,
}))

app.Adapt(httprouter.New())

route.Route(app)

app.OnError(iris.StatusNotFound, func(ctx *iris.Context) {
Expand Down
41 changes: 30 additions & 11 deletions wexin/app.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
var config = require('./config/config.js');

var userInfoCallbacks = [];

App({
Expand All @@ -6,18 +8,35 @@ App({
wx.login({
success: function(res) {
console.log(res);
wx.getUserInfo({
success: function(res) {
for (var i = 0; i < userInfoCallbacks.length; i++) {
userInfoCallbacks[i](res.userInfo);

if (res.code) {
wx.request({
url: config.api.weappLogin,
data: {
code: res.code
},
success: function(res) {
try {
wx.setStorageSync(config.wemallSession, res.data.data.sid);
} catch (err) {
console.log(err);
}
}
});

wx.getUserInfo({
success: function(res) {
for (var i = 0; i < userInfoCallbacks.length; i++) {
userInfoCallbacks[i](res.userInfo);
}
userInfoCallbacks = [];
self.globalData.userInfo = res.userInfo;
},
fail: function(data) {
console.log(data);
}
userInfoCallbacks = [];
self.globalData.userInfo = res.userInfo;
},
fail: function(data) {
console.log(data);
}
})
});
}
}
});
},
Expand Down
2 changes: 2 additions & 0 deletions wexin/config/config.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,12 @@ var apiPrefix = 'https://dev.wemall.com/api';

var config = {
name: "爱宝宝微商城",
wemallSession: "wemallSession",
static: {
imageDomain: 'https://dev.wemall.com'
},
api: {
weappLogin: '/weappLogin',
reqCategoryList: '/categories',
reqProductList: '/products',
reqProductDetail: '/product/:id'
Expand Down
5 changes: 1 addition & 4 deletions wexin/pages/index/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,7 @@ Page({
categories: [],
categoryIndex: 0,
itemWidth: '',
products: [],


niaoBuShiColor: '',
products: []
},
onCategoryTap: function() {

Expand Down

0 comments on commit 785e0c2

Please sign in to comment.