package main

import (
	"fmt"
	"net/url"
	"net/http"
	"io/ioutil"
	"crypto/hmac"
	"crypto/sha256"
	"encoding/hex"
	"encoding/json"
)

// 本机号码校验接口demo

func sign_param(data url.Values, key string) string {
	message := "appId" + data.Get("appId") +"mobile" + data.Get("mobile") + "token" + data.Get("token")
	mac := hmac.New(sha256.New, []byte(key))
	mac.Write([]byte(message))
	signature := hex.EncodeToString(mac.Sum(nil))
	return string(signature)
}

func main() {
	// 应用APPID
	appId := "xxx"
	// 应用APPKEY
	appKey := "xxx"
	u := "https://api.253.com/open/flashsdk/mobile-validate"
	// SDK返回token
	token := "xxxx"
	// 手机号码
	mobile := "xxxx"
	
	formData := url.Values{}
	formData.Set("appId", appId)
	formData.Set("token", token)
	formData.Set("mobile", mobile)
	formData.Set("sign", sign_param(formData, appKey))
	resp, err := http.PostForm(u, formData)
	if err != nil {
		return
	}
	defer resp.Body.Close()
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return
	}
	respBody := string(body)
	fmt.Printf("本机号校验响应: %s \n ", respBody)
	var mapResult map[string]interface{}
	if err := json.Unmarshal([]byte(respBody), &mapResult); err != nil {
        return
	}
	if mapResult["code"] == "200000" {
		data := (mapResult["data"]).(map[string]interface{})
		// tradeNo := data["tradeNo"].(string)  // 流水号
		isVerify := data["isVerify"].(string)
		if "1" == isVerify {
			fmt.Printf("手机号码校验通过")
		} else {
			fmt.Printf("手机号码校验不通过")
		}
	} else {
		fmt.Printf("本机号校验失败")
	}
}
