前言
对接Apple渠道的API接口需要在请求中加上证书认证,源证书的格式为.p12,需要转成.pem格式存储Cert与PrivateKey信息,然后利用.pem文件中的信息发送请求。
将p12文件转换为pem文件
直接在mac终端使用命令即可完成:
openssl pkcs12 -in xxx.p12 -out xxx.pem -nodes -clcerts
获取pem文件数据并发送请求的示例 ***
package main import ( "crypto/tls" //"crypto/x509" "encoding/pem" "fmt" "io/ioutil" "net/http" //"testing" ) // func TestPemRequest(t *testing.T) { func PemRequest() { b, _ := ioutil.ReadFile("/Users/Wanghongwei/Downloads/xxx.pem") pem.Decode(b) var pemBlocks []*pem.Block var v *pem.Block var pkey []byte for { v, b = pem.Decode(b) if v == nil { break } if v.Type == "PRIVATE KEY" { pkey = pem.EncodeToMemory(v) } else { pemBlocks = append(pemBlocks, v) } } bytes := pem.EncodeToMemory(pemBlocks[0]) keyString := string(pkey) CertString := string(bytes) fmt.Printf("Cert :\n %s \n Key:\n %s \n ", CertString, keyString) //pool := x509.NewCertPool() c, _ := tls.X509KeyPair(bytes, pkey) //pool.AppendCertsFromPEM(b) cfg := &tls.Config{ Certificates:[]tls.Certificate{c}, } tr := &http.Transport{ TLSClientConfig: cfg, } client := &http.Client{Transport: tr} // request, _ := http.NewRequest("GET", "https://api.searchads.apple.com/api/v3/acls", nil) request.Header.Set("Content-Type", "application/json") resp, err := client.Do(request) // require.Nil(t, err) if err != nil{ fmt.Println("err>>> ",err) }else{ data, _ := ioutil.ReadAll(resp.Body) fmt.Printf(string(data)) } } func main() { PemRequest() }