我想通过.p12文件创建带有ios平台的应用。我该怎么办?
这是创建应用程序的方法:
class AppHandler
{
public $USER_AUTH_KEY = 'Insert your key here';
public function create($name, $apns_p12 = null, $apns_p12_password = null, $gcm_key = null, $android_gcm_sender_id = null)
{
$fields = array(
'name' => $name,
'apns_p12' => $apns_p12,
'apns_p12_password' => $apns_p12_password,
'gcm_key' => $gcm_key,
'android_gcm_sender_id' => $android_gcm_sender_id
);
$fields = json_encode($fields);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://onesignal.com/api/v1/apps");
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json; charset=utf-8',
"Authorization: Basic " . $this->USER_AUTH_KEY));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, FALSE);
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
try {
$response = curl_exec($ch);
if (!$response) {
throw new Exception("App wasn't created");
}
} catch (Exception $e) {
echo 'Error: ', $e->getMessage(), "\n";
} finally {
curl_close($ch);
}
$response = json_decode($response, true);
$return = array(
'id' => $response['id'],
'basic_auth_key' => $response['basic_auth_key']
);
return $return;
}
...
这是具有两种获取.p12文件内部信息的方法:
public function getP12($pkcs12, $password = NULL): string
{
/*
// Way 1:
$pkcs12 = file_get_contents($pkcs12);
$encoded = base64_encode($pkcs12);
return $encoded;
*/
// Way 2:
$cert_store = file_get_contents($pkcs12);
if (!$cert_store) {
echo "Error: can't read file.\n";
exit;
}
$pkcs12Read = openssl_pkcs12_read($cert_store, $cert_info, $password);
if ($pkcs12Read) {
$result = base64_encode($cert_info['cert']);
return $result;
} else {
echo "Error: can't read cert.\n";
exit;
}
}
根据onesignal's doc,我必须发送apns_p12作为我的苹果推送通知p12证书文件,转换为字符串并以Base64编码。
而且我是这样的:
$obj = new AppHandler();
$response = $obj->create('TestName', $obj->getP12('cert.p12', 'password'), 'password')
它使用给定名称创建了一个应用程序,但是未设置平台。
您所说的“未建立平台”是什么意思?您在哪里遇到什么错误?
顺便说一句,我终于放弃尝试编写复杂的APNS编程代码,而是使用AWS的简单通知服务:https://aws.amazon.com/sns。它通过使用API设置主题和订阅者来处理Apple和Google通知,此外,您每月可以免费发送多达100万条通知。
好,我明白了。我只需要添加apns_env参数:
$fields = array(
'name' => $name,
'apns_env' => $apns_env,
'apns_p12' => $apns_p12,
'apns_p12_password' => $apns_p12_password,
'gcm_key' => $gcm_key,
'android_gcm_sender_id' => $android_gcm_sender_id
);
而且我应该进入文件的内部并将其转换为字符串,并以类似的方式对Base64进行编码:
public function getP12($pkcs12): string
{
$apns_12 = base64_encode(file_get_contents($pkcs12));
return $apns_12;
}