order_client.go 2.6 KB
package socialwork_sdk

import (
	"encoding/base64"
	"encoding/json"
	"fmt"
	"gitlab.workai.com.cn/chenang/socialwork-sdk/model"
	"log"
)

type OrderClient struct {
	Key                string `json:"key"`
	IV                 string `json:"iv"`
	PublicKey          string `json:"public_key"`
	CustomerPrivateKey string `json:"customer_private_key"`
	PtCode             string `json:"pt_code"`
	IP                 string `json:"ip"`
}

func HelloWorld() {
	fmt.Println("欢迎使用小爱,socialwork-sdk")
}

func NewOrderClient(key, iv, customerPrivateKey, publicKey, ip string) *OrderClient {
	return &OrderClient{
		Key:                key,
		IV:                 iv,
		PublicKey:          publicKey,
		CustomerPrivateKey: customerPrivateKey,
		IP:                 ip,
	}
}

func (o *OrderClient) EncryptAndSign(bs []byte) (string, string, error) {
	cipherText, err := aes_CBC_Encrypt(bs, []byte(o.Key), []byte(o.IV))
	if err != nil {
		log.Printf("Aes_CBC_Encrypt.failed.err=%v\n", err)
		return "", "", err
	}

	sign, err := rsaSignWithMd5Hex(cipherText, o.CustomerPrivateKey)
	if err != nil {
		log.Printf("RsaSignWithMd5Hex.failed.err=%v\n", err)
		return "", "", err
	}
	return cipherText, sign, nil
}

func (o *OrderClient) DecryptAndVerySign(cipherText, sign string) ([]byte, error) {
	_cipherText, err := base64.StdEncoding.DecodeString(cipherText)
	if err != nil {
		return nil, err
	}
	err = rsaVerifySignWithMd5Base64(cipherText, sign, o.PublicKey)
	if err != nil {
		return nil, err
	}
	content, err := aes_CBC_Decrypt(_cipherText, []byte(o.Key), []byte(o.IV))
	if err != nil {
		return nil, err
	}
	return content, nil
}

func (o *OrderClient) SendRequest(businessCode, reqBody string) (string, error) {
	//校验参数 reqbody
	checkErr := o.checkParams(businessCode, reqBody)
	if checkErr != nil {
		return "", checkErr
	}
	cipherText, sign, err := o.EncryptAndSign([]byte(reqBody))
	if err != nil {
		return "", err
	}

	orderModel := model.OrderModel{
		Data:         cipherText,
		Sign:         sign,
		PtCode:       o.PtCode,
		BusinessCode: businessCode,
	}

	_orderModel, err := json.Marshal(orderModel)
	if err != nil {
		return "", err
	}
	respBody, _, err := makeHttpRequestV4(post, o.IP+orderUrl, nil, map[string]interface{}{"jsonbody": string(_orderModel)}, nil)
	if err != nil {
		return "", err
	}

	orderRes := model.OrderModel{}
	json.Unmarshal([]byte(respBody), &orderRes)
	_respBody, err := o.DecryptAndVerySign(orderRes.Data, orderRes.Sign)
	if err != nil {
		return "", err
	}
	return string(_respBody), nil
}

func (o *OrderClient) checkParams(businessCode, reqBody string) error {
	return nil
}