package main

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

// 一键登录，请求获取手机号接口demo
func PKCS5Unpadding(encrypt []byte) []byte {
	padding := encrypt[len(encrypt)-1]
	return encrypt[:len(encrypt)-int(padding)]
}

func sign_param(data url.Values, key string) string {
	message := "appId" + data.Get("appId") + "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 decrpt_phone(data string, key string) string {
	hash := md5.Sum([]byte(key))
	hashString := hex.EncodeToString(hash[:])
	block, _ := aes.NewCipher([]byte(hashString[:16]))
	ecb := cipher.NewCBCDecrypter(block, []byte(hashString[16:]))
	source, _ := hex.DecodeString(data)
	decrypted := make([]byte, len(source))
	ecb.CryptBlocks(decrypted, source)
	return string(PKCS5Unpadding(decrypted))
}

func main() {
	// 应用APPID
	appId := "xxx"
	// 应用APPKEY
	appKey := "xxx"
	u := "https://api.253.com/open/flashsdk/mobile-query"
	// SDK返回token
	token := "xxxx"
	formData := url.Values{}
	formData.Set("appId", appId)
	formData.Set("token", token)
	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)  // 流水号
		mobileName := data["mobileName"].(string)
		fmt.Printf("手机号: %s \n", decrpt_phone(mobileName, appKey))
	} else {
		fmt.Printf("置换手机号失败: %s \n ", respBody)
	}
}
